PackageManagerService.java revision 35e46d297255363a20ccde62af3c58c4ce3c13c5
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_SHARED_USER_INCOMPATIBLE;
53import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
54import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
56import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
57import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
58import static android.content.pm.PackageManager.INSTALL_INTERNAL;
59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
65import static android.content.pm.PackageManager.MATCH_ALL;
66import static android.content.pm.PackageManager.MATCH_ANY_USER;
67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
79import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
80import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
81import static android.content.pm.PackageManager.PERMISSION_DENIED;
82import static android.content.pm.PackageManager.PERMISSION_GRANTED;
83import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
84import static android.content.pm.PackageParser.isApkFile;
85import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
86import static android.system.OsConstants.O_CREAT;
87import static android.system.OsConstants.O_RDWR;
88import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
89import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
90import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
91import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
92import static com.android.internal.util.ArrayUtils.appendInt;
93import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
94import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
95import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
96import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
97import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
98import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
99import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
101import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
103import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
104
105import android.Manifest;
106import android.annotation.IntDef;
107import android.annotation.NonNull;
108import android.annotation.Nullable;
109import android.app.ActivityManager;
110import android.app.AppOpsManager;
111import android.app.IActivityManager;
112import android.app.ResourcesManager;
113import android.app.admin.IDevicePolicyManager;
114import android.app.admin.SecurityLog;
115import android.app.backup.IBackupManager;
116import android.content.BroadcastReceiver;
117import android.content.ComponentName;
118import android.content.ContentResolver;
119import android.content.Context;
120import android.content.IIntentReceiver;
121import android.content.Intent;
122import android.content.IntentFilter;
123import android.content.IntentSender;
124import android.content.IntentSender.SendIntentException;
125import android.content.ServiceConnection;
126import android.content.pm.ActivityInfo;
127import android.content.pm.ApplicationInfo;
128import android.content.pm.AppsQueryHelper;
129import android.content.pm.AuxiliaryResolveInfo;
130import android.content.pm.ChangedPackages;
131import android.content.pm.FallbackCategoryProvider;
132import android.content.pm.FeatureInfo;
133import android.content.pm.IDexModuleRegisterCallback;
134import android.content.pm.IOnPermissionsChangeListener;
135import android.content.pm.IPackageDataObserver;
136import android.content.pm.IPackageDeleteObserver;
137import android.content.pm.IPackageDeleteObserver2;
138import android.content.pm.IPackageInstallObserver2;
139import android.content.pm.IPackageInstaller;
140import android.content.pm.IPackageManager;
141import android.content.pm.IPackageMoveObserver;
142import android.content.pm.IPackageStatsObserver;
143import android.content.pm.InstantAppInfo;
144import android.content.pm.InstantAppRequest;
145import android.content.pm.InstantAppResolveInfo;
146import android.content.pm.InstrumentationInfo;
147import android.content.pm.IntentFilterVerificationInfo;
148import android.content.pm.KeySet;
149import android.content.pm.PackageCleanItem;
150import android.content.pm.PackageInfo;
151import android.content.pm.PackageInfoLite;
152import android.content.pm.PackageInstaller;
153import android.content.pm.PackageManager;
154import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
155import android.content.pm.PackageManagerInternal;
156import android.content.pm.PackageParser;
157import android.content.pm.PackageParser.ActivityIntentInfo;
158import android.content.pm.PackageParser.PackageLite;
159import android.content.pm.PackageParser.PackageParserException;
160import android.content.pm.PackageStats;
161import android.content.pm.PackageUserState;
162import android.content.pm.ParceledListSlice;
163import android.content.pm.PermissionGroupInfo;
164import android.content.pm.PermissionInfo;
165import android.content.pm.ProviderInfo;
166import android.content.pm.ResolveInfo;
167import android.content.pm.ServiceInfo;
168import android.content.pm.SharedLibraryInfo;
169import android.content.pm.Signature;
170import android.content.pm.UserInfo;
171import android.content.pm.VerifierDeviceIdentity;
172import android.content.pm.VerifierInfo;
173import android.content.pm.VersionedPackage;
174import android.content.res.Resources;
175import android.database.ContentObserver;
176import android.graphics.Bitmap;
177import android.hardware.display.DisplayManager;
178import android.net.Uri;
179import android.os.Binder;
180import android.os.Build;
181import android.os.Bundle;
182import android.os.Debug;
183import android.os.Environment;
184import android.os.Environment.UserEnvironment;
185import android.os.FileUtils;
186import android.os.Handler;
187import android.os.IBinder;
188import android.os.Looper;
189import android.os.Message;
190import android.os.Parcel;
191import android.os.ParcelFileDescriptor;
192import android.os.PatternMatcher;
193import android.os.Process;
194import android.os.RemoteCallbackList;
195import android.os.RemoteException;
196import android.os.ResultReceiver;
197import android.os.SELinux;
198import android.os.ServiceManager;
199import android.os.ShellCallback;
200import android.os.SystemClock;
201import android.os.SystemProperties;
202import android.os.Trace;
203import android.os.UserHandle;
204import android.os.UserManager;
205import android.os.UserManagerInternal;
206import android.os.storage.IStorageManager;
207import android.os.storage.StorageEventListener;
208import android.os.storage.StorageManager;
209import android.os.storage.StorageManagerInternal;
210import android.os.storage.VolumeInfo;
211import android.os.storage.VolumeRecord;
212import android.provider.Settings.Global;
213import android.provider.Settings.Secure;
214import android.security.KeyStore;
215import android.security.SystemKeyStore;
216import android.service.pm.PackageServiceDumpProto;
217import android.system.ErrnoException;
218import android.system.Os;
219import android.text.TextUtils;
220import android.text.format.DateUtils;
221import android.util.ArrayMap;
222import android.util.ArraySet;
223import android.util.Base64;
224import android.util.BootTimingsTraceLog;
225import android.util.DisplayMetrics;
226import android.util.EventLog;
227import android.util.ExceptionUtils;
228import android.util.Log;
229import android.util.LogPrinter;
230import android.util.MathUtils;
231import android.util.PackageUtils;
232import android.util.Pair;
233import android.util.PrintStreamPrinter;
234import android.util.Slog;
235import android.util.SparseArray;
236import android.util.SparseBooleanArray;
237import android.util.SparseIntArray;
238import android.util.Xml;
239import android.util.jar.StrictJarFile;
240import android.util.proto.ProtoOutputStream;
241import android.view.Display;
242
243import com.android.internal.R;
244import com.android.internal.annotations.GuardedBy;
245import com.android.internal.app.IMediaContainerService;
246import com.android.internal.app.ResolverActivity;
247import com.android.internal.content.NativeLibraryHelper;
248import com.android.internal.content.PackageHelper;
249import com.android.internal.logging.MetricsLogger;
250import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
251import com.android.internal.os.IParcelFileDescriptorFactory;
252import com.android.internal.os.RoSystemProperties;
253import com.android.internal.os.SomeArgs;
254import com.android.internal.os.Zygote;
255import com.android.internal.telephony.CarrierAppUtils;
256import com.android.internal.util.ArrayUtils;
257import com.android.internal.util.ConcurrentUtils;
258import com.android.internal.util.DumpUtils;
259import com.android.internal.util.FastPrintWriter;
260import com.android.internal.util.FastXmlSerializer;
261import com.android.internal.util.IndentingPrintWriter;
262import com.android.internal.util.Preconditions;
263import com.android.internal.util.XmlUtils;
264import com.android.server.AttributeCache;
265import com.android.server.DeviceIdleController;
266import com.android.server.EventLogTags;
267import com.android.server.FgThread;
268import com.android.server.IntentResolver;
269import com.android.server.LocalServices;
270import com.android.server.LockGuard;
271import com.android.server.ServiceThread;
272import com.android.server.SystemConfig;
273import com.android.server.SystemServerInitThreadPool;
274import com.android.server.Watchdog;
275import com.android.server.net.NetworkPolicyManagerInternal;
276import com.android.server.pm.Installer.InstallerException;
277import com.android.server.pm.PermissionsState.PermissionState;
278import com.android.server.pm.Settings.DatabaseVersion;
279import com.android.server.pm.Settings.VersionInfo;
280import com.android.server.pm.dex.DexManager;
281import com.android.server.storage.DeviceStorageMonitorInternal;
282
283import dalvik.system.CloseGuard;
284import dalvik.system.DexFile;
285import dalvik.system.VMRuntime;
286
287import libcore.io.IoUtils;
288import libcore.util.EmptyArray;
289
290import org.xmlpull.v1.XmlPullParser;
291import org.xmlpull.v1.XmlPullParserException;
292import org.xmlpull.v1.XmlSerializer;
293
294import java.io.BufferedOutputStream;
295import java.io.BufferedReader;
296import java.io.ByteArrayInputStream;
297import java.io.ByteArrayOutputStream;
298import java.io.File;
299import java.io.FileDescriptor;
300import java.io.FileInputStream;
301import java.io.FileOutputStream;
302import java.io.FileReader;
303import java.io.FilenameFilter;
304import java.io.IOException;
305import java.io.PrintWriter;
306import java.lang.annotation.Retention;
307import java.lang.annotation.RetentionPolicy;
308import java.nio.charset.StandardCharsets;
309import java.security.DigestInputStream;
310import java.security.MessageDigest;
311import java.security.NoSuchAlgorithmException;
312import java.security.PublicKey;
313import java.security.SecureRandom;
314import java.security.cert.Certificate;
315import java.security.cert.CertificateEncodingException;
316import java.security.cert.CertificateException;
317import java.text.SimpleDateFormat;
318import java.util.ArrayList;
319import java.util.Arrays;
320import java.util.Collection;
321import java.util.Collections;
322import java.util.Comparator;
323import java.util.Date;
324import java.util.HashMap;
325import java.util.HashSet;
326import java.util.Iterator;
327import java.util.List;
328import java.util.Map;
329import java.util.Objects;
330import java.util.Set;
331import java.util.concurrent.CountDownLatch;
332import java.util.concurrent.Future;
333import java.util.concurrent.TimeUnit;
334import java.util.concurrent.atomic.AtomicBoolean;
335import java.util.concurrent.atomic.AtomicInteger;
336
337/**
338 * Keep track of all those APKs everywhere.
339 * <p>
340 * Internally there are two important locks:
341 * <ul>
342 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
343 * and other related state. It is a fine-grained lock that should only be held
344 * momentarily, as it's one of the most contended locks in the system.
345 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
346 * operations typically involve heavy lifting of application data on disk. Since
347 * {@code installd} is single-threaded, and it's operations can often be slow,
348 * this lock should never be acquired while already holding {@link #mPackages}.
349 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
350 * holding {@link #mInstallLock}.
351 * </ul>
352 * Many internal methods rely on the caller to hold the appropriate locks, and
353 * this contract is expressed through method name suffixes:
354 * <ul>
355 * <li>fooLI(): the caller must hold {@link #mInstallLock}
356 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
357 * being modified must be frozen
358 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
359 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
360 * </ul>
361 * <p>
362 * Because this class is very central to the platform's security; please run all
363 * CTS and unit tests whenever making modifications:
364 *
365 * <pre>
366 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
367 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
368 * </pre>
369 */
370public class PackageManagerService extends IPackageManager.Stub
371        implements PackageSender {
372    static final String TAG = "PackageManager";
373    static final boolean DEBUG_SETTINGS = false;
374    static final boolean DEBUG_PREFERRED = false;
375    static final boolean DEBUG_UPGRADE = false;
376    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
377    private static final boolean DEBUG_BACKUP = false;
378    private static final boolean DEBUG_INSTALL = false;
379    private static final boolean DEBUG_REMOVE = false;
380    private static final boolean DEBUG_BROADCASTS = false;
381    private static final boolean DEBUG_SHOW_INFO = false;
382    private static final boolean DEBUG_PACKAGE_INFO = false;
383    private static final boolean DEBUG_INTENT_MATCHING = false;
384    private static final boolean DEBUG_PACKAGE_SCANNING = false;
385    private static final boolean DEBUG_VERIFY = false;
386    private static final boolean DEBUG_FILTERS = false;
387    private static final boolean DEBUG_PERMISSIONS = false;
388    private static final boolean DEBUG_SHARED_LIBRARIES = false;
389
390    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
391    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
392    // user, but by default initialize to this.
393    public static final boolean DEBUG_DEXOPT = false;
394
395    private static final boolean DEBUG_ABI_SELECTION = false;
396    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
397    private static final boolean DEBUG_TRIAGED_MISSING = false;
398    private static final boolean DEBUG_APP_DATA = false;
399
400    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
401    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
402
403    private static final boolean HIDE_EPHEMERAL_APIS = false;
404
405    private static final boolean ENABLE_FREE_CACHE_V2 =
406            SystemProperties.getBoolean("fw.free_cache_v2", true);
407
408    private static final int RADIO_UID = Process.PHONE_UID;
409    private static final int LOG_UID = Process.LOG_UID;
410    private static final int NFC_UID = Process.NFC_UID;
411    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
412    private static final int SHELL_UID = Process.SHELL_UID;
413
414    // Cap the size of permission trees that 3rd party apps can define
415    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
416
417    // Suffix used during package installation when copying/moving
418    // package apks to install directory.
419    private static final String INSTALL_PACKAGE_SUFFIX = "-";
420
421    static final int SCAN_NO_DEX = 1<<1;
422    static final int SCAN_FORCE_DEX = 1<<2;
423    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
424    static final int SCAN_NEW_INSTALL = 1<<4;
425    static final int SCAN_UPDATE_TIME = 1<<5;
426    static final int SCAN_BOOTING = 1<<6;
427    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
428    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
429    static final int SCAN_REPLACING = 1<<9;
430    static final int SCAN_REQUIRE_KNOWN = 1<<10;
431    static final int SCAN_MOVE = 1<<11;
432    static final int SCAN_INITIAL = 1<<12;
433    static final int SCAN_CHECK_ONLY = 1<<13;
434    static final int SCAN_DONT_KILL_APP = 1<<14;
435    static final int SCAN_IGNORE_FROZEN = 1<<15;
436    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
437    static final int SCAN_AS_INSTANT_APP = 1<<17;
438    static final int SCAN_AS_FULL_APP = 1<<18;
439    /** Should not be with the scan flags */
440    static final int FLAGS_REMOVE_CHATTY = 1<<31;
441
442    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
443
444    private static final int[] EMPTY_INT_ARRAY = new int[0];
445
446    private static final int TYPE_UNKNOWN = 0;
447    private static final int TYPE_ACTIVITY = 1;
448    private static final int TYPE_RECEIVER = 2;
449    private static final int TYPE_SERVICE = 3;
450    private static final int TYPE_PROVIDER = 4;
451    @IntDef(prefix = { "TYPE_" }, value = {
452            TYPE_UNKNOWN,
453            TYPE_ACTIVITY,
454            TYPE_RECEIVER,
455            TYPE_SERVICE,
456            TYPE_PROVIDER,
457    })
458    @Retention(RetentionPolicy.SOURCE)
459    public @interface ComponentType {}
460
461    /**
462     * Timeout (in milliseconds) after which the watchdog should declare that
463     * our handler thread is wedged.  The usual default for such things is one
464     * minute but we sometimes do very lengthy I/O operations on this thread,
465     * such as installing multi-gigabyte applications, so ours needs to be longer.
466     */
467    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
468
469    /**
470     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
471     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
472     * settings entry if available, otherwise we use the hardcoded default.  If it's been
473     * more than this long since the last fstrim, we force one during the boot sequence.
474     *
475     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
476     * one gets run at the next available charging+idle time.  This final mandatory
477     * no-fstrim check kicks in only of the other scheduling criteria is never met.
478     */
479    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
480
481    /**
482     * Whether verification is enabled by default.
483     */
484    private static final boolean DEFAULT_VERIFY_ENABLE = true;
485
486    /**
487     * The default maximum time to wait for the verification agent to return in
488     * milliseconds.
489     */
490    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
491
492    /**
493     * The default response for package verification timeout.
494     *
495     * This can be either PackageManager.VERIFICATION_ALLOW or
496     * PackageManager.VERIFICATION_REJECT.
497     */
498    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
499
500    static final String PLATFORM_PACKAGE_NAME = "android";
501
502    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
503
504    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
505            DEFAULT_CONTAINER_PACKAGE,
506            "com.android.defcontainer.DefaultContainerService");
507
508    private static final String KILL_APP_REASON_GIDS_CHANGED =
509            "permission grant or revoke changed gids";
510
511    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
512            "permissions revoked";
513
514    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
515
516    private static final String PACKAGE_SCHEME = "package";
517
518    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
519
520    /** Permission grant: not grant the permission. */
521    private static final int GRANT_DENIED = 1;
522
523    /** Permission grant: grant the permission as an install permission. */
524    private static final int GRANT_INSTALL = 2;
525
526    /** Permission grant: grant the permission as a runtime one. */
527    private static final int GRANT_RUNTIME = 3;
528
529    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
530    private static final int GRANT_UPGRADE = 4;
531
532    /** Canonical intent used to identify what counts as a "web browser" app */
533    private static final Intent sBrowserIntent;
534    static {
535        sBrowserIntent = new Intent();
536        sBrowserIntent.setAction(Intent.ACTION_VIEW);
537        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
538        sBrowserIntent.setData(Uri.parse("http:"));
539    }
540
541    /**
542     * The set of all protected actions [i.e. those actions for which a high priority
543     * intent filter is disallowed].
544     */
545    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
546    static {
547        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
548        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
549        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
550        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
551    }
552
553    // Compilation reasons.
554    public static final int REASON_FIRST_BOOT = 0;
555    public static final int REASON_BOOT = 1;
556    public static final int REASON_INSTALL = 2;
557    public static final int REASON_BACKGROUND_DEXOPT = 3;
558    public static final int REASON_AB_OTA = 4;
559
560    public static final int REASON_LAST = REASON_AB_OTA;
561
562    /** All dangerous permission names in the same order as the events in MetricsEvent */
563    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
564            Manifest.permission.READ_CALENDAR,
565            Manifest.permission.WRITE_CALENDAR,
566            Manifest.permission.CAMERA,
567            Manifest.permission.READ_CONTACTS,
568            Manifest.permission.WRITE_CONTACTS,
569            Manifest.permission.GET_ACCOUNTS,
570            Manifest.permission.ACCESS_FINE_LOCATION,
571            Manifest.permission.ACCESS_COARSE_LOCATION,
572            Manifest.permission.RECORD_AUDIO,
573            Manifest.permission.READ_PHONE_STATE,
574            Manifest.permission.CALL_PHONE,
575            Manifest.permission.READ_CALL_LOG,
576            Manifest.permission.WRITE_CALL_LOG,
577            Manifest.permission.ADD_VOICEMAIL,
578            Manifest.permission.USE_SIP,
579            Manifest.permission.PROCESS_OUTGOING_CALLS,
580            Manifest.permission.READ_CELL_BROADCASTS,
581            Manifest.permission.BODY_SENSORS,
582            Manifest.permission.SEND_SMS,
583            Manifest.permission.RECEIVE_SMS,
584            Manifest.permission.READ_SMS,
585            Manifest.permission.RECEIVE_WAP_PUSH,
586            Manifest.permission.RECEIVE_MMS,
587            Manifest.permission.READ_EXTERNAL_STORAGE,
588            Manifest.permission.WRITE_EXTERNAL_STORAGE,
589            Manifest.permission.READ_PHONE_NUMBERS,
590            Manifest.permission.ANSWER_PHONE_CALLS);
591
592
593    /**
594     * Version number for the package parser cache. Increment this whenever the format or
595     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
596     */
597    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
598
599    /**
600     * Whether the package parser cache is enabled.
601     */
602    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
603
604    final ServiceThread mHandlerThread;
605
606    final PackageHandler mHandler;
607
608    private final ProcessLoggingHandler mProcessLoggingHandler;
609
610    /**
611     * Messages for {@link #mHandler} that need to wait for system ready before
612     * being dispatched.
613     */
614    private ArrayList<Message> mPostSystemReadyMessages;
615
616    final int mSdkVersion = Build.VERSION.SDK_INT;
617
618    final Context mContext;
619    final boolean mFactoryTest;
620    final boolean mOnlyCore;
621    final DisplayMetrics mMetrics;
622    final int mDefParseFlags;
623    final String[] mSeparateProcesses;
624    final boolean mIsUpgrade;
625    final boolean mIsPreNUpgrade;
626    final boolean mIsPreNMR1Upgrade;
627
628    // Have we told the Activity Manager to whitelist the default container service by uid yet?
629    @GuardedBy("mPackages")
630    boolean mDefaultContainerWhitelisted = false;
631
632    @GuardedBy("mPackages")
633    private boolean mDexOptDialogShown;
634
635    /** The location for ASEC container files on internal storage. */
636    final String mAsecInternalPath;
637
638    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
639    // LOCK HELD.  Can be called with mInstallLock held.
640    @GuardedBy("mInstallLock")
641    final Installer mInstaller;
642
643    /** Directory where installed third-party apps stored */
644    final File mAppInstallDir;
645
646    /**
647     * Directory to which applications installed internally have their
648     * 32 bit native libraries copied.
649     */
650    private File mAppLib32InstallDir;
651
652    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
653    // apps.
654    final File mDrmAppPrivateInstallDir;
655
656    // ----------------------------------------------------------------
657
658    // Lock for state used when installing and doing other long running
659    // operations.  Methods that must be called with this lock held have
660    // the suffix "LI".
661    final Object mInstallLock = new Object();
662
663    // ----------------------------------------------------------------
664
665    // Keys are String (package name), values are Package.  This also serves
666    // as the lock for the global state.  Methods that must be called with
667    // this lock held have the prefix "LP".
668    @GuardedBy("mPackages")
669    final ArrayMap<String, PackageParser.Package> mPackages =
670            new ArrayMap<String, PackageParser.Package>();
671
672    final ArrayMap<String, Set<String>> mKnownCodebase =
673            new ArrayMap<String, Set<String>>();
674
675    // Keys are isolated uids and values are the uid of the application
676    // that created the isolated proccess.
677    @GuardedBy("mPackages")
678    final SparseIntArray mIsolatedOwners = new SparseIntArray();
679
680    // List of APK paths to load for each user and package. This data is never
681    // persisted by the package manager. Instead, the overlay manager will
682    // ensure the data is up-to-date in runtime.
683    @GuardedBy("mPackages")
684    final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths =
685        new SparseArray<ArrayMap<String, ArrayList<String>>>();
686
687    /**
688     * Tracks new system packages [received in an OTA] that we expect to
689     * find updated user-installed versions. Keys are package name, values
690     * are package location.
691     */
692    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
693    /**
694     * Tracks high priority intent filters for protected actions. During boot, certain
695     * filter actions are protected and should never be allowed to have a high priority
696     * intent filter for them. However, there is one, and only one exception -- the
697     * setup wizard. It must be able to define a high priority intent filter for these
698     * actions to ensure there are no escapes from the wizard. We need to delay processing
699     * of these during boot as we need to look at all of the system packages in order
700     * to know which component is the setup wizard.
701     */
702    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
703    /**
704     * Whether or not processing protected filters should be deferred.
705     */
706    private boolean mDeferProtectedFilters = true;
707
708    /**
709     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
710     */
711    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
712    /**
713     * Whether or not system app permissions should be promoted from install to runtime.
714     */
715    boolean mPromoteSystemApps;
716
717    @GuardedBy("mPackages")
718    final Settings mSettings;
719
720    /**
721     * Set of package names that are currently "frozen", which means active
722     * surgery is being done on the code/data for that package. The platform
723     * will refuse to launch frozen packages to avoid race conditions.
724     *
725     * @see PackageFreezer
726     */
727    @GuardedBy("mPackages")
728    final ArraySet<String> mFrozenPackages = new ArraySet<>();
729
730    final ProtectedPackages mProtectedPackages;
731
732    boolean mFirstBoot;
733
734    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
735
736    // System configuration read by SystemConfig.
737    final int[] mGlobalGids;
738    final SparseArray<ArraySet<String>> mSystemPermissions;
739    @GuardedBy("mAvailableFeatures")
740    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
741
742    // If mac_permissions.xml was found for seinfo labeling.
743    boolean mFoundPolicyFile;
744
745    private final InstantAppRegistry mInstantAppRegistry;
746
747    @GuardedBy("mPackages")
748    int mChangedPackagesSequenceNumber;
749    /**
750     * List of changed [installed, removed or updated] packages.
751     * mapping from user id -> sequence number -> package name
752     */
753    @GuardedBy("mPackages")
754    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
755    /**
756     * The sequence number of the last change to a package.
757     * mapping from user id -> package name -> sequence number
758     */
759    @GuardedBy("mPackages")
760    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
761
762    class PackageParserCallback implements PackageParser.Callback {
763        @Override public final boolean hasFeature(String feature) {
764            return PackageManagerService.this.hasSystemFeature(feature, 0);
765        }
766
767        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
768                Collection<PackageParser.Package> allPackages, String targetPackageName) {
769            List<PackageParser.Package> overlayPackages = null;
770            for (PackageParser.Package p : allPackages) {
771                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
772                    if (overlayPackages == null) {
773                        overlayPackages = new ArrayList<PackageParser.Package>();
774                    }
775                    overlayPackages.add(p);
776                }
777            }
778            if (overlayPackages != null) {
779                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
780                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
781                        return p1.mOverlayPriority - p2.mOverlayPriority;
782                    }
783                };
784                Collections.sort(overlayPackages, cmp);
785            }
786            return overlayPackages;
787        }
788
789        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
790                String targetPackageName, String targetPath) {
791            if ("android".equals(targetPackageName)) {
792                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
793                // native AssetManager.
794                return null;
795            }
796            List<PackageParser.Package> overlayPackages =
797                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
798            if (overlayPackages == null || overlayPackages.isEmpty()) {
799                return null;
800            }
801            List<String> overlayPathList = null;
802            for (PackageParser.Package overlayPackage : overlayPackages) {
803                if (targetPath == null) {
804                    if (overlayPathList == null) {
805                        overlayPathList = new ArrayList<String>();
806                    }
807                    overlayPathList.add(overlayPackage.baseCodePath);
808                    continue;
809                }
810
811                try {
812                    // Creates idmaps for system to parse correctly the Android manifest of the
813                    // target package.
814                    //
815                    // OverlayManagerService will update each of them with a correct gid from its
816                    // target package app id.
817                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
818                            UserHandle.getSharedAppGid(
819                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
820                    if (overlayPathList == null) {
821                        overlayPathList = new ArrayList<String>();
822                    }
823                    overlayPathList.add(overlayPackage.baseCodePath);
824                } catch (InstallerException e) {
825                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
826                            overlayPackage.baseCodePath);
827                }
828            }
829            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
830        }
831
832        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
833            synchronized (mPackages) {
834                return getStaticOverlayPathsLocked(
835                        mPackages.values(), targetPackageName, targetPath);
836            }
837        }
838
839        @Override public final String[] getOverlayApks(String targetPackageName) {
840            return getStaticOverlayPaths(targetPackageName, null);
841        }
842
843        @Override public final String[] getOverlayPaths(String targetPackageName,
844                String targetPath) {
845            return getStaticOverlayPaths(targetPackageName, targetPath);
846        }
847    };
848
849    class ParallelPackageParserCallback extends PackageParserCallback {
850        List<PackageParser.Package> mOverlayPackages = null;
851
852        void findStaticOverlayPackages() {
853            synchronized (mPackages) {
854                for (PackageParser.Package p : mPackages.values()) {
855                    if (p.mIsStaticOverlay) {
856                        if (mOverlayPackages == null) {
857                            mOverlayPackages = new ArrayList<PackageParser.Package>();
858                        }
859                        mOverlayPackages.add(p);
860                    }
861                }
862            }
863        }
864
865        @Override
866        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
867            // We can trust mOverlayPackages without holding mPackages because package uninstall
868            // can't happen while running parallel parsing.
869            // Moreover holding mPackages on each parsing thread causes dead-lock.
870            return mOverlayPackages == null ? null :
871                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
872        }
873    }
874
875    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
876    final ParallelPackageParserCallback mParallelPackageParserCallback =
877            new ParallelPackageParserCallback();
878
879    public static final class SharedLibraryEntry {
880        public final @Nullable String path;
881        public final @Nullable String apk;
882        public final @NonNull SharedLibraryInfo info;
883
884        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
885                String declaringPackageName, int declaringPackageVersionCode) {
886            path = _path;
887            apk = _apk;
888            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
889                    declaringPackageName, declaringPackageVersionCode), null);
890        }
891    }
892
893    // Currently known shared libraries.
894    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
895    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
896            new ArrayMap<>();
897
898    // All available activities, for your resolving pleasure.
899    final ActivityIntentResolver mActivities =
900            new ActivityIntentResolver();
901
902    // All available receivers, for your resolving pleasure.
903    final ActivityIntentResolver mReceivers =
904            new ActivityIntentResolver();
905
906    // All available services, for your resolving pleasure.
907    final ServiceIntentResolver mServices = new ServiceIntentResolver();
908
909    // All available providers, for your resolving pleasure.
910    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
911
912    // Mapping from provider base names (first directory in content URI codePath)
913    // to the provider information.
914    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
915            new ArrayMap<String, PackageParser.Provider>();
916
917    // Mapping from instrumentation class names to info about them.
918    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
919            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
920
921    // Mapping from permission names to info about them.
922    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
923            new ArrayMap<String, PackageParser.PermissionGroup>();
924
925    // Packages whose data we have transfered into another package, thus
926    // should no longer exist.
927    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
928
929    // Broadcast actions that are only available to the system.
930    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
931
932    /** List of packages waiting for verification. */
933    final SparseArray<PackageVerificationState> mPendingVerification
934            = new SparseArray<PackageVerificationState>();
935
936    /** Set of packages associated with each app op permission. */
937    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
938
939    final PackageInstallerService mInstallerService;
940
941    private final PackageDexOptimizer mPackageDexOptimizer;
942    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
943    // is used by other apps).
944    private final DexManager mDexManager;
945
946    private AtomicInteger mNextMoveId = new AtomicInteger();
947    private final MoveCallbacks mMoveCallbacks;
948
949    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
950
951    // Cache of users who need badging.
952    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
953
954    /** Token for keys in mPendingVerification. */
955    private int mPendingVerificationToken = 0;
956
957    volatile boolean mSystemReady;
958    volatile boolean mSafeMode;
959    volatile boolean mHasSystemUidErrors;
960    private volatile boolean mEphemeralAppsDisabled;
961
962    ApplicationInfo mAndroidApplication;
963    final ActivityInfo mResolveActivity = new ActivityInfo();
964    final ResolveInfo mResolveInfo = new ResolveInfo();
965    ComponentName mResolveComponentName;
966    PackageParser.Package mPlatformPackage;
967    ComponentName mCustomResolverComponentName;
968
969    boolean mResolverReplaced = false;
970
971    private final @Nullable ComponentName mIntentFilterVerifierComponent;
972    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
973
974    private int mIntentFilterVerificationToken = 0;
975
976    /** The service connection to the ephemeral resolver */
977    final EphemeralResolverConnection mInstantAppResolverConnection;
978    /** Component used to show resolver settings for Instant Apps */
979    final ComponentName mInstantAppResolverSettingsComponent;
980
981    /** Activity used to install instant applications */
982    ActivityInfo mInstantAppInstallerActivity;
983    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
984
985    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
986            = new SparseArray<IntentFilterVerificationState>();
987
988    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
989
990    // List of packages names to keep cached, even if they are uninstalled for all users
991    private List<String> mKeepUninstalledPackages;
992
993    private UserManagerInternal mUserManagerInternal;
994
995    private DeviceIdleController.LocalService mDeviceIdleController;
996
997    private File mCacheDir;
998
999    private ArraySet<String> mPrivappPermissionsViolations;
1000
1001    private Future<?> mPrepareAppDataFuture;
1002
1003    private static class IFVerificationParams {
1004        PackageParser.Package pkg;
1005        boolean replacing;
1006        int userId;
1007        int verifierUid;
1008
1009        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1010                int _userId, int _verifierUid) {
1011            pkg = _pkg;
1012            replacing = _replacing;
1013            userId = _userId;
1014            replacing = _replacing;
1015            verifierUid = _verifierUid;
1016        }
1017    }
1018
1019    private interface IntentFilterVerifier<T extends IntentFilter> {
1020        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1021                                               T filter, String packageName);
1022        void startVerifications(int userId);
1023        void receiveVerificationResponse(int verificationId);
1024    }
1025
1026    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1027        private Context mContext;
1028        private ComponentName mIntentFilterVerifierComponent;
1029        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1030
1031        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1032            mContext = context;
1033            mIntentFilterVerifierComponent = verifierComponent;
1034        }
1035
1036        private String getDefaultScheme() {
1037            return IntentFilter.SCHEME_HTTPS;
1038        }
1039
1040        @Override
1041        public void startVerifications(int userId) {
1042            // Launch verifications requests
1043            int count = mCurrentIntentFilterVerifications.size();
1044            for (int n=0; n<count; n++) {
1045                int verificationId = mCurrentIntentFilterVerifications.get(n);
1046                final IntentFilterVerificationState ivs =
1047                        mIntentFilterVerificationStates.get(verificationId);
1048
1049                String packageName = ivs.getPackageName();
1050
1051                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1052                final int filterCount = filters.size();
1053                ArraySet<String> domainsSet = new ArraySet<>();
1054                for (int m=0; m<filterCount; m++) {
1055                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1056                    domainsSet.addAll(filter.getHostsList());
1057                }
1058                synchronized (mPackages) {
1059                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1060                            packageName, domainsSet) != null) {
1061                        scheduleWriteSettingsLocked();
1062                    }
1063                }
1064                sendVerificationRequest(userId, verificationId, ivs);
1065            }
1066            mCurrentIntentFilterVerifications.clear();
1067        }
1068
1069        private void sendVerificationRequest(int userId, int verificationId,
1070                IntentFilterVerificationState ivs) {
1071
1072            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1073            verificationIntent.putExtra(
1074                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1075                    verificationId);
1076            verificationIntent.putExtra(
1077                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1078                    getDefaultScheme());
1079            verificationIntent.putExtra(
1080                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1081                    ivs.getHostsString());
1082            verificationIntent.putExtra(
1083                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1084                    ivs.getPackageName());
1085            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1086            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1087
1088            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1089            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1090                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1091                    userId, false, "intent filter verifier");
1092
1093            UserHandle user = new UserHandle(userId);
1094            mContext.sendBroadcastAsUser(verificationIntent, user);
1095            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1096                    "Sending IntentFilter verification broadcast");
1097        }
1098
1099        public void receiveVerificationResponse(int verificationId) {
1100            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1101
1102            final boolean verified = ivs.isVerified();
1103
1104            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1105            final int count = filters.size();
1106            if (DEBUG_DOMAIN_VERIFICATION) {
1107                Slog.i(TAG, "Received verification response " + verificationId
1108                        + " for " + count + " filters, verified=" + verified);
1109            }
1110            for (int n=0; n<count; n++) {
1111                PackageParser.ActivityIntentInfo filter = filters.get(n);
1112                filter.setVerified(verified);
1113
1114                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1115                        + " verified with result:" + verified + " and hosts:"
1116                        + ivs.getHostsString());
1117            }
1118
1119            mIntentFilterVerificationStates.remove(verificationId);
1120
1121            final String packageName = ivs.getPackageName();
1122            IntentFilterVerificationInfo ivi = null;
1123
1124            synchronized (mPackages) {
1125                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1126            }
1127            if (ivi == null) {
1128                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1129                        + verificationId + " packageName:" + packageName);
1130                return;
1131            }
1132            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1133                    "Updating IntentFilterVerificationInfo for package " + packageName
1134                            +" verificationId:" + verificationId);
1135
1136            synchronized (mPackages) {
1137                if (verified) {
1138                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1139                } else {
1140                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1141                }
1142                scheduleWriteSettingsLocked();
1143
1144                final int userId = ivs.getUserId();
1145                if (userId != UserHandle.USER_ALL) {
1146                    final int userStatus =
1147                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1148
1149                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1150                    boolean needUpdate = false;
1151
1152                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1153                    // already been set by the User thru the Disambiguation dialog
1154                    switch (userStatus) {
1155                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1156                            if (verified) {
1157                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1158                            } else {
1159                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1160                            }
1161                            needUpdate = true;
1162                            break;
1163
1164                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1165                            if (verified) {
1166                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1167                                needUpdate = true;
1168                            }
1169                            break;
1170
1171                        default:
1172                            // Nothing to do
1173                    }
1174
1175                    if (needUpdate) {
1176                        mSettings.updateIntentFilterVerificationStatusLPw(
1177                                packageName, updatedStatus, userId);
1178                        scheduleWritePackageRestrictionsLocked(userId);
1179                    }
1180                }
1181            }
1182        }
1183
1184        @Override
1185        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1186                    ActivityIntentInfo filter, String packageName) {
1187            if (!hasValidDomains(filter)) {
1188                return false;
1189            }
1190            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1191            if (ivs == null) {
1192                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1193                        packageName);
1194            }
1195            if (DEBUG_DOMAIN_VERIFICATION) {
1196                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1197            }
1198            ivs.addFilter(filter);
1199            return true;
1200        }
1201
1202        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1203                int userId, int verificationId, String packageName) {
1204            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1205                    verifierUid, userId, packageName);
1206            ivs.setPendingState();
1207            synchronized (mPackages) {
1208                mIntentFilterVerificationStates.append(verificationId, ivs);
1209                mCurrentIntentFilterVerifications.add(verificationId);
1210            }
1211            return ivs;
1212        }
1213    }
1214
1215    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1216        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1217                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1218                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1219    }
1220
1221    // Set of pending broadcasts for aggregating enable/disable of components.
1222    static class PendingPackageBroadcasts {
1223        // for each user id, a map of <package name -> components within that package>
1224        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1225
1226        public PendingPackageBroadcasts() {
1227            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1228        }
1229
1230        public ArrayList<String> get(int userId, String packageName) {
1231            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1232            return packages.get(packageName);
1233        }
1234
1235        public void put(int userId, String packageName, ArrayList<String> components) {
1236            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1237            packages.put(packageName, components);
1238        }
1239
1240        public void remove(int userId, String packageName) {
1241            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1242            if (packages != null) {
1243                packages.remove(packageName);
1244            }
1245        }
1246
1247        public void remove(int userId) {
1248            mUidMap.remove(userId);
1249        }
1250
1251        public int userIdCount() {
1252            return mUidMap.size();
1253        }
1254
1255        public int userIdAt(int n) {
1256            return mUidMap.keyAt(n);
1257        }
1258
1259        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1260            return mUidMap.get(userId);
1261        }
1262
1263        public int size() {
1264            // total number of pending broadcast entries across all userIds
1265            int num = 0;
1266            for (int i = 0; i< mUidMap.size(); i++) {
1267                num += mUidMap.valueAt(i).size();
1268            }
1269            return num;
1270        }
1271
1272        public void clear() {
1273            mUidMap.clear();
1274        }
1275
1276        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1277            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1278            if (map == null) {
1279                map = new ArrayMap<String, ArrayList<String>>();
1280                mUidMap.put(userId, map);
1281            }
1282            return map;
1283        }
1284    }
1285    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1286
1287    // Service Connection to remote media container service to copy
1288    // package uri's from external media onto secure containers
1289    // or internal storage.
1290    private IMediaContainerService mContainerService = null;
1291
1292    static final int SEND_PENDING_BROADCAST = 1;
1293    static final int MCS_BOUND = 3;
1294    static final int END_COPY = 4;
1295    static final int INIT_COPY = 5;
1296    static final int MCS_UNBIND = 6;
1297    static final int START_CLEANING_PACKAGE = 7;
1298    static final int FIND_INSTALL_LOC = 8;
1299    static final int POST_INSTALL = 9;
1300    static final int MCS_RECONNECT = 10;
1301    static final int MCS_GIVE_UP = 11;
1302    static final int UPDATED_MEDIA_STATUS = 12;
1303    static final int WRITE_SETTINGS = 13;
1304    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1305    static final int PACKAGE_VERIFIED = 15;
1306    static final int CHECK_PENDING_VERIFICATION = 16;
1307    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1308    static final int INTENT_FILTER_VERIFIED = 18;
1309    static final int WRITE_PACKAGE_LIST = 19;
1310    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1311
1312    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1313
1314    // Delay time in millisecs
1315    static final int BROADCAST_DELAY = 10 * 1000;
1316
1317    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1318            2 * 60 * 60 * 1000L; /* two hours */
1319
1320    static UserManagerService sUserManager;
1321
1322    // Stores a list of users whose package restrictions file needs to be updated
1323    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1324
1325    final private DefaultContainerConnection mDefContainerConn =
1326            new DefaultContainerConnection();
1327    class DefaultContainerConnection implements ServiceConnection {
1328        public void onServiceConnected(ComponentName name, IBinder service) {
1329            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1330            final IMediaContainerService imcs = IMediaContainerService.Stub
1331                    .asInterface(Binder.allowBlocking(service));
1332            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1333        }
1334
1335        public void onServiceDisconnected(ComponentName name) {
1336            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1337        }
1338    }
1339
1340    // Recordkeeping of restore-after-install operations that are currently in flight
1341    // between the Package Manager and the Backup Manager
1342    static class PostInstallData {
1343        public InstallArgs args;
1344        public PackageInstalledInfo res;
1345
1346        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1347            args = _a;
1348            res = _r;
1349        }
1350    }
1351
1352    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1353    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1354
1355    // XML tags for backup/restore of various bits of state
1356    private static final String TAG_PREFERRED_BACKUP = "pa";
1357    private static final String TAG_DEFAULT_APPS = "da";
1358    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1359
1360    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1361    private static final String TAG_ALL_GRANTS = "rt-grants";
1362    private static final String TAG_GRANT = "grant";
1363    private static final String ATTR_PACKAGE_NAME = "pkg";
1364
1365    private static final String TAG_PERMISSION = "perm";
1366    private static final String ATTR_PERMISSION_NAME = "name";
1367    private static final String ATTR_IS_GRANTED = "g";
1368    private static final String ATTR_USER_SET = "set";
1369    private static final String ATTR_USER_FIXED = "fixed";
1370    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1371
1372    // System/policy permission grants are not backed up
1373    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1374            FLAG_PERMISSION_POLICY_FIXED
1375            | FLAG_PERMISSION_SYSTEM_FIXED
1376            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1377
1378    // And we back up these user-adjusted states
1379    private static final int USER_RUNTIME_GRANT_MASK =
1380            FLAG_PERMISSION_USER_SET
1381            | FLAG_PERMISSION_USER_FIXED
1382            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1383
1384    final @Nullable String mRequiredVerifierPackage;
1385    final @NonNull String mRequiredInstallerPackage;
1386    final @NonNull String mRequiredUninstallerPackage;
1387    final @Nullable String mSetupWizardPackage;
1388    final @Nullable String mStorageManagerPackage;
1389    final @NonNull String mServicesSystemSharedLibraryPackageName;
1390    final @NonNull String mSharedSystemSharedLibraryPackageName;
1391
1392    final boolean mPermissionReviewRequired;
1393
1394    private final PackageUsage mPackageUsage = new PackageUsage();
1395    private final CompilerStats mCompilerStats = new CompilerStats();
1396
1397    class PackageHandler extends Handler {
1398        private boolean mBound = false;
1399        final ArrayList<HandlerParams> mPendingInstalls =
1400            new ArrayList<HandlerParams>();
1401
1402        private boolean connectToService() {
1403            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1404                    " DefaultContainerService");
1405            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1406            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1407            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1408                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1409                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1410                mBound = true;
1411                return true;
1412            }
1413            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1414            return false;
1415        }
1416
1417        private void disconnectService() {
1418            mContainerService = null;
1419            mBound = false;
1420            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1421            mContext.unbindService(mDefContainerConn);
1422            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1423        }
1424
1425        PackageHandler(Looper looper) {
1426            super(looper);
1427        }
1428
1429        public void handleMessage(Message msg) {
1430            try {
1431                doHandleMessage(msg);
1432            } finally {
1433                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1434            }
1435        }
1436
1437        void doHandleMessage(Message msg) {
1438            switch (msg.what) {
1439                case INIT_COPY: {
1440                    HandlerParams params = (HandlerParams) msg.obj;
1441                    int idx = mPendingInstalls.size();
1442                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1443                    // If a bind was already initiated we dont really
1444                    // need to do anything. The pending install
1445                    // will be processed later on.
1446                    if (!mBound) {
1447                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1448                                System.identityHashCode(mHandler));
1449                        // If this is the only one pending we might
1450                        // have to bind to the service again.
1451                        if (!connectToService()) {
1452                            Slog.e(TAG, "Failed to bind to media container service");
1453                            params.serviceError();
1454                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1455                                    System.identityHashCode(mHandler));
1456                            if (params.traceMethod != null) {
1457                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1458                                        params.traceCookie);
1459                            }
1460                            return;
1461                        } else {
1462                            // Once we bind to the service, the first
1463                            // pending request will be processed.
1464                            mPendingInstalls.add(idx, params);
1465                        }
1466                    } else {
1467                        mPendingInstalls.add(idx, params);
1468                        // Already bound to the service. Just make
1469                        // sure we trigger off processing the first request.
1470                        if (idx == 0) {
1471                            mHandler.sendEmptyMessage(MCS_BOUND);
1472                        }
1473                    }
1474                    break;
1475                }
1476                case MCS_BOUND: {
1477                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1478                    if (msg.obj != null) {
1479                        mContainerService = (IMediaContainerService) msg.obj;
1480                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1481                                System.identityHashCode(mHandler));
1482                    }
1483                    if (mContainerService == null) {
1484                        if (!mBound) {
1485                            // Something seriously wrong since we are not bound and we are not
1486                            // waiting for connection. Bail out.
1487                            Slog.e(TAG, "Cannot bind to media container service");
1488                            for (HandlerParams params : mPendingInstalls) {
1489                                // Indicate service bind error
1490                                params.serviceError();
1491                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1492                                        System.identityHashCode(params));
1493                                if (params.traceMethod != null) {
1494                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1495                                            params.traceMethod, params.traceCookie);
1496                                }
1497                                return;
1498                            }
1499                            mPendingInstalls.clear();
1500                        } else {
1501                            Slog.w(TAG, "Waiting to connect to media container service");
1502                        }
1503                    } else if (mPendingInstalls.size() > 0) {
1504                        HandlerParams params = mPendingInstalls.get(0);
1505                        if (params != null) {
1506                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1507                                    System.identityHashCode(params));
1508                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1509                            if (params.startCopy()) {
1510                                // We are done...  look for more work or to
1511                                // go idle.
1512                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1513                                        "Checking for more work or unbind...");
1514                                // Delete pending install
1515                                if (mPendingInstalls.size() > 0) {
1516                                    mPendingInstalls.remove(0);
1517                                }
1518                                if (mPendingInstalls.size() == 0) {
1519                                    if (mBound) {
1520                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1521                                                "Posting delayed MCS_UNBIND");
1522                                        removeMessages(MCS_UNBIND);
1523                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1524                                        // Unbind after a little delay, to avoid
1525                                        // continual thrashing.
1526                                        sendMessageDelayed(ubmsg, 10000);
1527                                    }
1528                                } else {
1529                                    // There are more pending requests in queue.
1530                                    // Just post MCS_BOUND message to trigger processing
1531                                    // of next pending install.
1532                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1533                                            "Posting MCS_BOUND for next work");
1534                                    mHandler.sendEmptyMessage(MCS_BOUND);
1535                                }
1536                            }
1537                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1538                        }
1539                    } else {
1540                        // Should never happen ideally.
1541                        Slog.w(TAG, "Empty queue");
1542                    }
1543                    break;
1544                }
1545                case MCS_RECONNECT: {
1546                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1547                    if (mPendingInstalls.size() > 0) {
1548                        if (mBound) {
1549                            disconnectService();
1550                        }
1551                        if (!connectToService()) {
1552                            Slog.e(TAG, "Failed to bind to media container service");
1553                            for (HandlerParams params : mPendingInstalls) {
1554                                // Indicate service bind error
1555                                params.serviceError();
1556                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1557                                        System.identityHashCode(params));
1558                            }
1559                            mPendingInstalls.clear();
1560                        }
1561                    }
1562                    break;
1563                }
1564                case MCS_UNBIND: {
1565                    // If there is no actual work left, then time to unbind.
1566                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1567
1568                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1569                        if (mBound) {
1570                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1571
1572                            disconnectService();
1573                        }
1574                    } else if (mPendingInstalls.size() > 0) {
1575                        // There are more pending requests in queue.
1576                        // Just post MCS_BOUND message to trigger processing
1577                        // of next pending install.
1578                        mHandler.sendEmptyMessage(MCS_BOUND);
1579                    }
1580
1581                    break;
1582                }
1583                case MCS_GIVE_UP: {
1584                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1585                    HandlerParams params = mPendingInstalls.remove(0);
1586                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1587                            System.identityHashCode(params));
1588                    break;
1589                }
1590                case SEND_PENDING_BROADCAST: {
1591                    String packages[];
1592                    ArrayList<String> components[];
1593                    int size = 0;
1594                    int uids[];
1595                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1596                    synchronized (mPackages) {
1597                        if (mPendingBroadcasts == null) {
1598                            return;
1599                        }
1600                        size = mPendingBroadcasts.size();
1601                        if (size <= 0) {
1602                            // Nothing to be done. Just return
1603                            return;
1604                        }
1605                        packages = new String[size];
1606                        components = new ArrayList[size];
1607                        uids = new int[size];
1608                        int i = 0;  // filling out the above arrays
1609
1610                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1611                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1612                            Iterator<Map.Entry<String, ArrayList<String>>> it
1613                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1614                                            .entrySet().iterator();
1615                            while (it.hasNext() && i < size) {
1616                                Map.Entry<String, ArrayList<String>> ent = it.next();
1617                                packages[i] = ent.getKey();
1618                                components[i] = ent.getValue();
1619                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1620                                uids[i] = (ps != null)
1621                                        ? UserHandle.getUid(packageUserId, ps.appId)
1622                                        : -1;
1623                                i++;
1624                            }
1625                        }
1626                        size = i;
1627                        mPendingBroadcasts.clear();
1628                    }
1629                    // Send broadcasts
1630                    for (int i = 0; i < size; i++) {
1631                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1632                    }
1633                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1634                    break;
1635                }
1636                case START_CLEANING_PACKAGE: {
1637                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1638                    final String packageName = (String)msg.obj;
1639                    final int userId = msg.arg1;
1640                    final boolean andCode = msg.arg2 != 0;
1641                    synchronized (mPackages) {
1642                        if (userId == UserHandle.USER_ALL) {
1643                            int[] users = sUserManager.getUserIds();
1644                            for (int user : users) {
1645                                mSettings.addPackageToCleanLPw(
1646                                        new PackageCleanItem(user, packageName, andCode));
1647                            }
1648                        } else {
1649                            mSettings.addPackageToCleanLPw(
1650                                    new PackageCleanItem(userId, packageName, andCode));
1651                        }
1652                    }
1653                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1654                    startCleaningPackages();
1655                } break;
1656                case POST_INSTALL: {
1657                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1658
1659                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1660                    final boolean didRestore = (msg.arg2 != 0);
1661                    mRunningInstalls.delete(msg.arg1);
1662
1663                    if (data != null) {
1664                        InstallArgs args = data.args;
1665                        PackageInstalledInfo parentRes = data.res;
1666
1667                        final boolean grantPermissions = (args.installFlags
1668                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1669                        final boolean killApp = (args.installFlags
1670                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1671                        final String[] grantedPermissions = args.installGrantPermissions;
1672
1673                        // Handle the parent package
1674                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1675                                grantedPermissions, didRestore, args.installerPackageName,
1676                                args.observer);
1677
1678                        // Handle the child packages
1679                        final int childCount = (parentRes.addedChildPackages != null)
1680                                ? parentRes.addedChildPackages.size() : 0;
1681                        for (int i = 0; i < childCount; i++) {
1682                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1683                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1684                                    grantedPermissions, false, args.installerPackageName,
1685                                    args.observer);
1686                        }
1687
1688                        // Log tracing if needed
1689                        if (args.traceMethod != null) {
1690                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1691                                    args.traceCookie);
1692                        }
1693                    } else {
1694                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1695                    }
1696
1697                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1698                } break;
1699                case UPDATED_MEDIA_STATUS: {
1700                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1701                    boolean reportStatus = msg.arg1 == 1;
1702                    boolean doGc = msg.arg2 == 1;
1703                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1704                    if (doGc) {
1705                        // Force a gc to clear up stale containers.
1706                        Runtime.getRuntime().gc();
1707                    }
1708                    if (msg.obj != null) {
1709                        @SuppressWarnings("unchecked")
1710                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1711                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1712                        // Unload containers
1713                        unloadAllContainers(args);
1714                    }
1715                    if (reportStatus) {
1716                        try {
1717                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1718                                    "Invoking StorageManagerService call back");
1719                            PackageHelper.getStorageManager().finishMediaUpdate();
1720                        } catch (RemoteException e) {
1721                            Log.e(TAG, "StorageManagerService not running?");
1722                        }
1723                    }
1724                } break;
1725                case WRITE_SETTINGS: {
1726                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1727                    synchronized (mPackages) {
1728                        removeMessages(WRITE_SETTINGS);
1729                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1730                        mSettings.writeLPr();
1731                        mDirtyUsers.clear();
1732                    }
1733                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1734                } break;
1735                case WRITE_PACKAGE_RESTRICTIONS: {
1736                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1737                    synchronized (mPackages) {
1738                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1739                        for (int userId : mDirtyUsers) {
1740                            mSettings.writePackageRestrictionsLPr(userId);
1741                        }
1742                        mDirtyUsers.clear();
1743                    }
1744                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1745                } break;
1746                case WRITE_PACKAGE_LIST: {
1747                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1748                    synchronized (mPackages) {
1749                        removeMessages(WRITE_PACKAGE_LIST);
1750                        mSettings.writePackageListLPr(msg.arg1);
1751                    }
1752                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1753                } break;
1754                case CHECK_PENDING_VERIFICATION: {
1755                    final int verificationId = msg.arg1;
1756                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1757
1758                    if ((state != null) && !state.timeoutExtended()) {
1759                        final InstallArgs args = state.getInstallArgs();
1760                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1761
1762                        Slog.i(TAG, "Verification timed out for " + originUri);
1763                        mPendingVerification.remove(verificationId);
1764
1765                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1766
1767                        final UserHandle user = args.getUser();
1768                        if (getDefaultVerificationResponse(user)
1769                                == PackageManager.VERIFICATION_ALLOW) {
1770                            Slog.i(TAG, "Continuing with installation of " + originUri);
1771                            state.setVerifierResponse(Binder.getCallingUid(),
1772                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1773                            broadcastPackageVerified(verificationId, originUri,
1774                                    PackageManager.VERIFICATION_ALLOW, user);
1775                            try {
1776                                ret = args.copyApk(mContainerService, true);
1777                            } catch (RemoteException e) {
1778                                Slog.e(TAG, "Could not contact the ContainerService");
1779                            }
1780                        } else {
1781                            broadcastPackageVerified(verificationId, originUri,
1782                                    PackageManager.VERIFICATION_REJECT, user);
1783                        }
1784
1785                        Trace.asyncTraceEnd(
1786                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1787
1788                        processPendingInstall(args, ret);
1789                        mHandler.sendEmptyMessage(MCS_UNBIND);
1790                    }
1791                    break;
1792                }
1793                case PACKAGE_VERIFIED: {
1794                    final int verificationId = msg.arg1;
1795
1796                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1797                    if (state == null) {
1798                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1799                        break;
1800                    }
1801
1802                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1803
1804                    state.setVerifierResponse(response.callerUid, response.code);
1805
1806                    if (state.isVerificationComplete()) {
1807                        mPendingVerification.remove(verificationId);
1808
1809                        final InstallArgs args = state.getInstallArgs();
1810                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1811
1812                        int ret;
1813                        if (state.isInstallAllowed()) {
1814                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1815                            broadcastPackageVerified(verificationId, originUri,
1816                                    response.code, state.getInstallArgs().getUser());
1817                            try {
1818                                ret = args.copyApk(mContainerService, true);
1819                            } catch (RemoteException e) {
1820                                Slog.e(TAG, "Could not contact the ContainerService");
1821                            }
1822                        } else {
1823                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1824                        }
1825
1826                        Trace.asyncTraceEnd(
1827                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1828
1829                        processPendingInstall(args, ret);
1830                        mHandler.sendEmptyMessage(MCS_UNBIND);
1831                    }
1832
1833                    break;
1834                }
1835                case START_INTENT_FILTER_VERIFICATIONS: {
1836                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1837                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1838                            params.replacing, params.pkg);
1839                    break;
1840                }
1841                case INTENT_FILTER_VERIFIED: {
1842                    final int verificationId = msg.arg1;
1843
1844                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1845                            verificationId);
1846                    if (state == null) {
1847                        Slog.w(TAG, "Invalid IntentFilter verification token "
1848                                + verificationId + " received");
1849                        break;
1850                    }
1851
1852                    final int userId = state.getUserId();
1853
1854                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1855                            "Processing IntentFilter verification with token:"
1856                            + verificationId + " and userId:" + userId);
1857
1858                    final IntentFilterVerificationResponse response =
1859                            (IntentFilterVerificationResponse) msg.obj;
1860
1861                    state.setVerifierResponse(response.callerUid, response.code);
1862
1863                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1864                            "IntentFilter verification with token:" + verificationId
1865                            + " and userId:" + userId
1866                            + " is settings verifier response with response code:"
1867                            + response.code);
1868
1869                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1870                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1871                                + response.getFailedDomainsString());
1872                    }
1873
1874                    if (state.isVerificationComplete()) {
1875                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1876                    } else {
1877                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1878                                "IntentFilter verification with token:" + verificationId
1879                                + " was not said to be complete");
1880                    }
1881
1882                    break;
1883                }
1884                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1885                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1886                            mInstantAppResolverConnection,
1887                            (InstantAppRequest) msg.obj,
1888                            mInstantAppInstallerActivity,
1889                            mHandler);
1890                }
1891            }
1892        }
1893    }
1894
1895    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1896            boolean killApp, String[] grantedPermissions,
1897            boolean launchedForRestore, String installerPackage,
1898            IPackageInstallObserver2 installObserver) {
1899        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1900            // Send the removed broadcasts
1901            if (res.removedInfo != null) {
1902                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1903            }
1904
1905            // Now that we successfully installed the package, grant runtime
1906            // permissions if requested before broadcasting the install. Also
1907            // for legacy apps in permission review mode we clear the permission
1908            // review flag which is used to emulate runtime permissions for
1909            // legacy apps.
1910            if (grantPermissions) {
1911                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1912            }
1913
1914            final boolean update = res.removedInfo != null
1915                    && res.removedInfo.removedPackage != null;
1916            final String origInstallerPackageName = res.removedInfo != null
1917                    ? res.removedInfo.installerPackageName : null;
1918
1919            // If this is the first time we have child packages for a disabled privileged
1920            // app that had no children, we grant requested runtime permissions to the new
1921            // children if the parent on the system image had them already granted.
1922            if (res.pkg.parentPackage != null) {
1923                synchronized (mPackages) {
1924                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1925                }
1926            }
1927
1928            synchronized (mPackages) {
1929                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1930            }
1931
1932            final String packageName = res.pkg.applicationInfo.packageName;
1933
1934            // Determine the set of users who are adding this package for
1935            // the first time vs. those who are seeing an update.
1936            int[] firstUsers = EMPTY_INT_ARRAY;
1937            int[] updateUsers = EMPTY_INT_ARRAY;
1938            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1939            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1940            for (int newUser : res.newUsers) {
1941                if (ps.getInstantApp(newUser)) {
1942                    continue;
1943                }
1944                if (allNewUsers) {
1945                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1946                    continue;
1947                }
1948                boolean isNew = true;
1949                for (int origUser : res.origUsers) {
1950                    if (origUser == newUser) {
1951                        isNew = false;
1952                        break;
1953                    }
1954                }
1955                if (isNew) {
1956                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1957                } else {
1958                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1959                }
1960            }
1961
1962            // Send installed broadcasts if the package is not a static shared lib.
1963            if (res.pkg.staticSharedLibName == null) {
1964                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1965
1966                // Send added for users that see the package for the first time
1967                // sendPackageAddedForNewUsers also deals with system apps
1968                int appId = UserHandle.getAppId(res.uid);
1969                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1970                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1971
1972                // Send added for users that don't see the package for the first time
1973                Bundle extras = new Bundle(1);
1974                extras.putInt(Intent.EXTRA_UID, res.uid);
1975                if (update) {
1976                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1977                }
1978                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1979                        extras, 0 /*flags*/,
1980                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1981                if (origInstallerPackageName != null) {
1982                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1983                            extras, 0 /*flags*/,
1984                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1985                }
1986
1987                // Send replaced for users that don't see the package for the first time
1988                if (update) {
1989                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1990                            packageName, extras, 0 /*flags*/,
1991                            null /*targetPackage*/, null /*finishedReceiver*/,
1992                            updateUsers);
1993                    if (origInstallerPackageName != null) {
1994                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1995                                extras, 0 /*flags*/,
1996                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1997                    }
1998                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1999                            null /*package*/, null /*extras*/, 0 /*flags*/,
2000                            packageName /*targetPackage*/,
2001                            null /*finishedReceiver*/, updateUsers);
2002                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2003                    // First-install and we did a restore, so we're responsible for the
2004                    // first-launch broadcast.
2005                    if (DEBUG_BACKUP) {
2006                        Slog.i(TAG, "Post-restore of " + packageName
2007                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2008                    }
2009                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2010                }
2011
2012                // Send broadcast package appeared if forward locked/external for all users
2013                // treat asec-hosted packages like removable media on upgrade
2014                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2015                    if (DEBUG_INSTALL) {
2016                        Slog.i(TAG, "upgrading pkg " + res.pkg
2017                                + " is ASEC-hosted -> AVAILABLE");
2018                    }
2019                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2020                    ArrayList<String> pkgList = new ArrayList<>(1);
2021                    pkgList.add(packageName);
2022                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2023                }
2024            }
2025
2026            // Work that needs to happen on first install within each user
2027            if (firstUsers != null && firstUsers.length > 0) {
2028                synchronized (mPackages) {
2029                    for (int userId : firstUsers) {
2030                        // If this app is a browser and it's newly-installed for some
2031                        // users, clear any default-browser state in those users. The
2032                        // app's nature doesn't depend on the user, so we can just check
2033                        // its browser nature in any user and generalize.
2034                        if (packageIsBrowser(packageName, userId)) {
2035                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2036                        }
2037
2038                        // We may also need to apply pending (restored) runtime
2039                        // permission grants within these users.
2040                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2041                    }
2042                }
2043            }
2044
2045            // Log current value of "unknown sources" setting
2046            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2047                    getUnknownSourcesSettings());
2048
2049            // Remove the replaced package's older resources safely now
2050            // We delete after a gc for applications  on sdcard.
2051            if (res.removedInfo != null && res.removedInfo.args != null) {
2052                Runtime.getRuntime().gc();
2053                synchronized (mInstallLock) {
2054                    res.removedInfo.args.doPostDeleteLI(true);
2055                }
2056            } else {
2057                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2058                // and not block here.
2059                VMRuntime.getRuntime().requestConcurrentGC();
2060            }
2061
2062            // Notify DexManager that the package was installed for new users.
2063            // The updated users should already be indexed and the package code paths
2064            // should not change.
2065            // Don't notify the manager for ephemeral apps as they are not expected to
2066            // survive long enough to benefit of background optimizations.
2067            for (int userId : firstUsers) {
2068                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2069                // There's a race currently where some install events may interleave with an uninstall.
2070                // This can lead to package info being null (b/36642664).
2071                if (info != null) {
2072                    mDexManager.notifyPackageInstalled(info, userId);
2073                }
2074            }
2075        }
2076
2077        // If someone is watching installs - notify them
2078        if (installObserver != null) {
2079            try {
2080                Bundle extras = extrasForInstallResult(res);
2081                installObserver.onPackageInstalled(res.name, res.returnCode,
2082                        res.returnMsg, extras);
2083            } catch (RemoteException e) {
2084                Slog.i(TAG, "Observer no longer exists.");
2085            }
2086        }
2087    }
2088
2089    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2090            PackageParser.Package pkg) {
2091        if (pkg.parentPackage == null) {
2092            return;
2093        }
2094        if (pkg.requestedPermissions == null) {
2095            return;
2096        }
2097        final PackageSetting disabledSysParentPs = mSettings
2098                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2099        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2100                || !disabledSysParentPs.isPrivileged()
2101                || (disabledSysParentPs.childPackageNames != null
2102                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2103            return;
2104        }
2105        final int[] allUserIds = sUserManager.getUserIds();
2106        final int permCount = pkg.requestedPermissions.size();
2107        for (int i = 0; i < permCount; i++) {
2108            String permission = pkg.requestedPermissions.get(i);
2109            BasePermission bp = mSettings.mPermissions.get(permission);
2110            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2111                continue;
2112            }
2113            for (int userId : allUserIds) {
2114                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2115                        permission, userId)) {
2116                    grantRuntimePermission(pkg.packageName, permission, userId);
2117                }
2118            }
2119        }
2120    }
2121
2122    private StorageEventListener mStorageListener = new StorageEventListener() {
2123        @Override
2124        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2125            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2126                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2127                    final String volumeUuid = vol.getFsUuid();
2128
2129                    // Clean up any users or apps that were removed or recreated
2130                    // while this volume was missing
2131                    sUserManager.reconcileUsers(volumeUuid);
2132                    reconcileApps(volumeUuid);
2133
2134                    // Clean up any install sessions that expired or were
2135                    // cancelled while this volume was missing
2136                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2137
2138                    loadPrivatePackages(vol);
2139
2140                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2141                    unloadPrivatePackages(vol);
2142                }
2143            }
2144
2145            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2146                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2147                    updateExternalMediaStatus(true, false);
2148                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2149                    updateExternalMediaStatus(false, false);
2150                }
2151            }
2152        }
2153
2154        @Override
2155        public void onVolumeForgotten(String fsUuid) {
2156            if (TextUtils.isEmpty(fsUuid)) {
2157                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2158                return;
2159            }
2160
2161            // Remove any apps installed on the forgotten volume
2162            synchronized (mPackages) {
2163                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2164                for (PackageSetting ps : packages) {
2165                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2166                    deletePackageVersioned(new VersionedPackage(ps.name,
2167                            PackageManager.VERSION_CODE_HIGHEST),
2168                            new LegacyPackageDeleteObserver(null).getBinder(),
2169                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2170                    // Try very hard to release any references to this package
2171                    // so we don't risk the system server being killed due to
2172                    // open FDs
2173                    AttributeCache.instance().removePackage(ps.name);
2174                }
2175
2176                mSettings.onVolumeForgotten(fsUuid);
2177                mSettings.writeLPr();
2178            }
2179        }
2180    };
2181
2182    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2183            String[] grantedPermissions) {
2184        for (int userId : userIds) {
2185            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2186        }
2187    }
2188
2189    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2190            String[] grantedPermissions) {
2191        PackageSetting ps = (PackageSetting) pkg.mExtras;
2192        if (ps == null) {
2193            return;
2194        }
2195
2196        PermissionsState permissionsState = ps.getPermissionsState();
2197
2198        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2199                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2200
2201        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2202                >= Build.VERSION_CODES.M;
2203
2204        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2205
2206        for (String permission : pkg.requestedPermissions) {
2207            final BasePermission bp;
2208            synchronized (mPackages) {
2209                bp = mSettings.mPermissions.get(permission);
2210            }
2211            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2212                    && (!instantApp || bp.isInstant())
2213                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2214                    && (grantedPermissions == null
2215                           || ArrayUtils.contains(grantedPermissions, permission))) {
2216                final int flags = permissionsState.getPermissionFlags(permission, userId);
2217                if (supportsRuntimePermissions) {
2218                    // Installer cannot change immutable permissions.
2219                    if ((flags & immutableFlags) == 0) {
2220                        grantRuntimePermission(pkg.packageName, permission, userId);
2221                    }
2222                } else if (mPermissionReviewRequired) {
2223                    // In permission review mode we clear the review flag when we
2224                    // are asked to install the app with all permissions granted.
2225                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2226                        updatePermissionFlags(permission, pkg.packageName,
2227                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2228                    }
2229                }
2230            }
2231        }
2232    }
2233
2234    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2235        Bundle extras = null;
2236        switch (res.returnCode) {
2237            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2238                extras = new Bundle();
2239                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2240                        res.origPermission);
2241                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2242                        res.origPackage);
2243                break;
2244            }
2245            case PackageManager.INSTALL_SUCCEEDED: {
2246                extras = new Bundle();
2247                extras.putBoolean(Intent.EXTRA_REPLACING,
2248                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2249                break;
2250            }
2251        }
2252        return extras;
2253    }
2254
2255    void scheduleWriteSettingsLocked() {
2256        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2257            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2258        }
2259    }
2260
2261    void scheduleWritePackageListLocked(int userId) {
2262        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2263            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2264            msg.arg1 = userId;
2265            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2266        }
2267    }
2268
2269    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2270        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2271        scheduleWritePackageRestrictionsLocked(userId);
2272    }
2273
2274    void scheduleWritePackageRestrictionsLocked(int userId) {
2275        final int[] userIds = (userId == UserHandle.USER_ALL)
2276                ? sUserManager.getUserIds() : new int[]{userId};
2277        for (int nextUserId : userIds) {
2278            if (!sUserManager.exists(nextUserId)) return;
2279            mDirtyUsers.add(nextUserId);
2280            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2281                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2282            }
2283        }
2284    }
2285
2286    public static PackageManagerService main(Context context, Installer installer,
2287            boolean factoryTest, boolean onlyCore) {
2288        // Self-check for initial settings.
2289        PackageManagerServiceCompilerMapping.checkProperties();
2290
2291        PackageManagerService m = new PackageManagerService(context, installer,
2292                factoryTest, onlyCore);
2293        m.enableSystemUserPackages();
2294        ServiceManager.addService("package", m);
2295        return m;
2296    }
2297
2298    private void enableSystemUserPackages() {
2299        if (!UserManager.isSplitSystemUser()) {
2300            return;
2301        }
2302        // For system user, enable apps based on the following conditions:
2303        // - app is whitelisted or belong to one of these groups:
2304        //   -- system app which has no launcher icons
2305        //   -- system app which has INTERACT_ACROSS_USERS permission
2306        //   -- system IME app
2307        // - app is not in the blacklist
2308        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2309        Set<String> enableApps = new ArraySet<>();
2310        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2311                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2312                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2313        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2314        enableApps.addAll(wlApps);
2315        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2316                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2317        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2318        enableApps.removeAll(blApps);
2319        Log.i(TAG, "Applications installed for system user: " + enableApps);
2320        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2321                UserHandle.SYSTEM);
2322        final int allAppsSize = allAps.size();
2323        synchronized (mPackages) {
2324            for (int i = 0; i < allAppsSize; i++) {
2325                String pName = allAps.get(i);
2326                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2327                // Should not happen, but we shouldn't be failing if it does
2328                if (pkgSetting == null) {
2329                    continue;
2330                }
2331                boolean install = enableApps.contains(pName);
2332                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2333                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2334                            + " for system user");
2335                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2336                }
2337            }
2338            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2339        }
2340    }
2341
2342    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2343        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2344                Context.DISPLAY_SERVICE);
2345        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2346    }
2347
2348    /**
2349     * Requests that files preopted on a secondary system partition be copied to the data partition
2350     * if possible.  Note that the actual copying of the files is accomplished by init for security
2351     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2352     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2353     */
2354    private static void requestCopyPreoptedFiles() {
2355        final int WAIT_TIME_MS = 100;
2356        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2357        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2358            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2359            // We will wait for up to 100 seconds.
2360            final long timeStart = SystemClock.uptimeMillis();
2361            final long timeEnd = timeStart + 100 * 1000;
2362            long timeNow = timeStart;
2363            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2364                try {
2365                    Thread.sleep(WAIT_TIME_MS);
2366                } catch (InterruptedException e) {
2367                    // Do nothing
2368                }
2369                timeNow = SystemClock.uptimeMillis();
2370                if (timeNow > timeEnd) {
2371                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2372                    Slog.wtf(TAG, "cppreopt did not finish!");
2373                    break;
2374                }
2375            }
2376
2377            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2378        }
2379    }
2380
2381    public PackageManagerService(Context context, Installer installer,
2382            boolean factoryTest, boolean onlyCore) {
2383        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2384        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2385        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2386                SystemClock.uptimeMillis());
2387
2388        if (mSdkVersion <= 0) {
2389            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2390        }
2391
2392        mContext = context;
2393
2394        mPermissionReviewRequired = context.getResources().getBoolean(
2395                R.bool.config_permissionReviewRequired);
2396
2397        mFactoryTest = factoryTest;
2398        mOnlyCore = onlyCore;
2399        mMetrics = new DisplayMetrics();
2400        mSettings = new Settings(mPackages);
2401        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2402                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2403        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2404                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2405        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2406                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2407        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2408                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2409        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2410                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2411        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2412                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2413
2414        String separateProcesses = SystemProperties.get("debug.separate_processes");
2415        if (separateProcesses != null && separateProcesses.length() > 0) {
2416            if ("*".equals(separateProcesses)) {
2417                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2418                mSeparateProcesses = null;
2419                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2420            } else {
2421                mDefParseFlags = 0;
2422                mSeparateProcesses = separateProcesses.split(",");
2423                Slog.w(TAG, "Running with debug.separate_processes: "
2424                        + separateProcesses);
2425            }
2426        } else {
2427            mDefParseFlags = 0;
2428            mSeparateProcesses = null;
2429        }
2430
2431        mInstaller = installer;
2432        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2433                "*dexopt*");
2434        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2435        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2436
2437        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2438                FgThread.get().getLooper());
2439
2440        getDefaultDisplayMetrics(context, mMetrics);
2441
2442        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2443        SystemConfig systemConfig = SystemConfig.getInstance();
2444        mGlobalGids = systemConfig.getGlobalGids();
2445        mSystemPermissions = systemConfig.getSystemPermissions();
2446        mAvailableFeatures = systemConfig.getAvailableFeatures();
2447        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2448
2449        mProtectedPackages = new ProtectedPackages(mContext);
2450
2451        synchronized (mInstallLock) {
2452        // writer
2453        synchronized (mPackages) {
2454            mHandlerThread = new ServiceThread(TAG,
2455                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2456            mHandlerThread.start();
2457            mHandler = new PackageHandler(mHandlerThread.getLooper());
2458            mProcessLoggingHandler = new ProcessLoggingHandler();
2459            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2460
2461            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2462            mInstantAppRegistry = new InstantAppRegistry(this);
2463
2464            File dataDir = Environment.getDataDirectory();
2465            mAppInstallDir = new File(dataDir, "app");
2466            mAppLib32InstallDir = new File(dataDir, "app-lib");
2467            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2468            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2469            sUserManager = new UserManagerService(context, this,
2470                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2471
2472            // Propagate permission configuration in to package manager.
2473            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2474                    = systemConfig.getPermissions();
2475            for (int i=0; i<permConfig.size(); i++) {
2476                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2477                BasePermission bp = mSettings.mPermissions.get(perm.name);
2478                if (bp == null) {
2479                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2480                    mSettings.mPermissions.put(perm.name, bp);
2481                }
2482                if (perm.gids != null) {
2483                    bp.setGids(perm.gids, perm.perUser);
2484                }
2485            }
2486
2487            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2488            final int builtInLibCount = libConfig.size();
2489            for (int i = 0; i < builtInLibCount; i++) {
2490                String name = libConfig.keyAt(i);
2491                String path = libConfig.valueAt(i);
2492                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2493                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2494            }
2495
2496            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2497
2498            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2499            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2500            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2501
2502            // Clean up orphaned packages for which the code path doesn't exist
2503            // and they are an update to a system app - caused by bug/32321269
2504            final int packageSettingCount = mSettings.mPackages.size();
2505            for (int i = packageSettingCount - 1; i >= 0; i--) {
2506                PackageSetting ps = mSettings.mPackages.valueAt(i);
2507                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2508                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2509                    mSettings.mPackages.removeAt(i);
2510                    mSettings.enableSystemPackageLPw(ps.name);
2511                }
2512            }
2513
2514            if (mFirstBoot) {
2515                requestCopyPreoptedFiles();
2516            }
2517
2518            String customResolverActivity = Resources.getSystem().getString(
2519                    R.string.config_customResolverActivity);
2520            if (TextUtils.isEmpty(customResolverActivity)) {
2521                customResolverActivity = null;
2522            } else {
2523                mCustomResolverComponentName = ComponentName.unflattenFromString(
2524                        customResolverActivity);
2525            }
2526
2527            long startTime = SystemClock.uptimeMillis();
2528
2529            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2530                    startTime);
2531
2532            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2533            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2534
2535            if (bootClassPath == null) {
2536                Slog.w(TAG, "No BOOTCLASSPATH found!");
2537            }
2538
2539            if (systemServerClassPath == null) {
2540                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2541            }
2542
2543            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2544
2545            final VersionInfo ver = mSettings.getInternalVersion();
2546            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2547            if (mIsUpgrade) {
2548                logCriticalInfo(Log.INFO,
2549                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2550            }
2551
2552            // when upgrading from pre-M, promote system app permissions from install to runtime
2553            mPromoteSystemApps =
2554                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2555
2556            // When upgrading from pre-N, we need to handle package extraction like first boot,
2557            // as there is no profiling data available.
2558            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2559
2560            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2561
2562            // save off the names of pre-existing system packages prior to scanning; we don't
2563            // want to automatically grant runtime permissions for new system apps
2564            if (mPromoteSystemApps) {
2565                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2566                while (pkgSettingIter.hasNext()) {
2567                    PackageSetting ps = pkgSettingIter.next();
2568                    if (isSystemApp(ps)) {
2569                        mExistingSystemPackages.add(ps.name);
2570                    }
2571                }
2572            }
2573
2574            mCacheDir = preparePackageParserCache(mIsUpgrade);
2575
2576            // Set flag to monitor and not change apk file paths when
2577            // scanning install directories.
2578            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2579
2580            if (mIsUpgrade || mFirstBoot) {
2581                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2582            }
2583
2584            // Collect vendor overlay packages. (Do this before scanning any apps.)
2585            // For security and version matching reason, only consider
2586            // overlay packages if they reside in the right directory.
2587            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2588                    | PackageParser.PARSE_IS_SYSTEM
2589                    | PackageParser.PARSE_IS_SYSTEM_DIR
2590                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2591
2592            mParallelPackageParserCallback.findStaticOverlayPackages();
2593
2594            // Find base frameworks (resource packages without code).
2595            scanDirTracedLI(frameworkDir, mDefParseFlags
2596                    | PackageParser.PARSE_IS_SYSTEM
2597                    | PackageParser.PARSE_IS_SYSTEM_DIR
2598                    | PackageParser.PARSE_IS_PRIVILEGED,
2599                    scanFlags | SCAN_NO_DEX, 0);
2600
2601            // Collected privileged system packages.
2602            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2603            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2604                    | PackageParser.PARSE_IS_SYSTEM
2605                    | PackageParser.PARSE_IS_SYSTEM_DIR
2606                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2607
2608            // Collect ordinary system packages.
2609            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2610            scanDirTracedLI(systemAppDir, mDefParseFlags
2611                    | PackageParser.PARSE_IS_SYSTEM
2612                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2613
2614            // Collect all vendor packages.
2615            File vendorAppDir = new File("/vendor/app");
2616            try {
2617                vendorAppDir = vendorAppDir.getCanonicalFile();
2618            } catch (IOException e) {
2619                // failed to look up canonical path, continue with original one
2620            }
2621            scanDirTracedLI(vendorAppDir, mDefParseFlags
2622                    | PackageParser.PARSE_IS_SYSTEM
2623                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2624
2625            // Collect all OEM packages.
2626            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2627            scanDirTracedLI(oemAppDir, mDefParseFlags
2628                    | PackageParser.PARSE_IS_SYSTEM
2629                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2630
2631            // Prune any system packages that no longer exist.
2632            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2633            if (!mOnlyCore) {
2634                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2635                while (psit.hasNext()) {
2636                    PackageSetting ps = psit.next();
2637
2638                    /*
2639                     * If this is not a system app, it can't be a
2640                     * disable system app.
2641                     */
2642                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2643                        continue;
2644                    }
2645
2646                    /*
2647                     * If the package is scanned, it's not erased.
2648                     */
2649                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2650                    if (scannedPkg != null) {
2651                        /*
2652                         * If the system app is both scanned and in the
2653                         * disabled packages list, then it must have been
2654                         * added via OTA. Remove it from the currently
2655                         * scanned package so the previously user-installed
2656                         * application can be scanned.
2657                         */
2658                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2659                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2660                                    + ps.name + "; removing system app.  Last known codePath="
2661                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2662                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2663                                    + scannedPkg.mVersionCode);
2664                            removePackageLI(scannedPkg, true);
2665                            mExpectingBetter.put(ps.name, ps.codePath);
2666                        }
2667
2668                        continue;
2669                    }
2670
2671                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2672                        psit.remove();
2673                        logCriticalInfo(Log.WARN, "System package " + ps.name
2674                                + " no longer exists; it's data will be wiped");
2675                        // Actual deletion of code and data will be handled by later
2676                        // reconciliation step
2677                    } else {
2678                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2679                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2680                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2681                        }
2682                    }
2683                }
2684            }
2685
2686            //look for any incomplete package installations
2687            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2688            for (int i = 0; i < deletePkgsList.size(); i++) {
2689                // Actual deletion of code and data will be handled by later
2690                // reconciliation step
2691                final String packageName = deletePkgsList.get(i).name;
2692                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2693                synchronized (mPackages) {
2694                    mSettings.removePackageLPw(packageName);
2695                }
2696            }
2697
2698            //delete tmp files
2699            deleteTempPackageFiles();
2700
2701            // Remove any shared userIDs that have no associated packages
2702            mSettings.pruneSharedUsersLPw();
2703
2704            if (!mOnlyCore) {
2705                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2706                        SystemClock.uptimeMillis());
2707                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2708
2709                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2710                        | PackageParser.PARSE_FORWARD_LOCK,
2711                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2712
2713                /**
2714                 * Remove disable package settings for any updated system
2715                 * apps that were removed via an OTA. If they're not a
2716                 * previously-updated app, remove them completely.
2717                 * Otherwise, just revoke their system-level permissions.
2718                 */
2719                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2720                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2721                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2722
2723                    String msg;
2724                    if (deletedPkg == null) {
2725                        msg = "Updated system package " + deletedAppName
2726                                + " no longer exists; it's data will be wiped";
2727                        // Actual deletion of code and data will be handled by later
2728                        // reconciliation step
2729                    } else {
2730                        msg = "Updated system app + " + deletedAppName
2731                                + " no longer present; removing system privileges for "
2732                                + deletedAppName;
2733
2734                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2735
2736                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2737                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2738                    }
2739                    logCriticalInfo(Log.WARN, msg);
2740                }
2741
2742                /**
2743                 * Make sure all system apps that we expected to appear on
2744                 * the userdata partition actually showed up. If they never
2745                 * appeared, crawl back and revive the system version.
2746                 */
2747                for (int i = 0; i < mExpectingBetter.size(); i++) {
2748                    final String packageName = mExpectingBetter.keyAt(i);
2749                    if (!mPackages.containsKey(packageName)) {
2750                        final File scanFile = mExpectingBetter.valueAt(i);
2751
2752                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2753                                + " but never showed up; reverting to system");
2754
2755                        int reparseFlags = mDefParseFlags;
2756                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2757                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2758                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2759                                    | PackageParser.PARSE_IS_PRIVILEGED;
2760                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2761                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2762                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2763                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2764                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2765                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2766                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2767                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2768                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2769                        } else {
2770                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2771                            continue;
2772                        }
2773
2774                        mSettings.enableSystemPackageLPw(packageName);
2775
2776                        try {
2777                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2778                        } catch (PackageManagerException e) {
2779                            Slog.e(TAG, "Failed to parse original system package: "
2780                                    + e.getMessage());
2781                        }
2782                    }
2783                }
2784            }
2785            mExpectingBetter.clear();
2786
2787            // Resolve the storage manager.
2788            mStorageManagerPackage = getStorageManagerPackageName();
2789
2790            // Resolve protected action filters. Only the setup wizard is allowed to
2791            // have a high priority filter for these actions.
2792            mSetupWizardPackage = getSetupWizardPackageName();
2793            if (mProtectedFilters.size() > 0) {
2794                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2795                    Slog.i(TAG, "No setup wizard;"
2796                        + " All protected intents capped to priority 0");
2797                }
2798                for (ActivityIntentInfo filter : mProtectedFilters) {
2799                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2800                        if (DEBUG_FILTERS) {
2801                            Slog.i(TAG, "Found setup wizard;"
2802                                + " allow priority " + filter.getPriority() + ";"
2803                                + " package: " + filter.activity.info.packageName
2804                                + " activity: " + filter.activity.className
2805                                + " priority: " + filter.getPriority());
2806                        }
2807                        // skip setup wizard; allow it to keep the high priority filter
2808                        continue;
2809                    }
2810                    if (DEBUG_FILTERS) {
2811                        Slog.i(TAG, "Protected action; cap priority to 0;"
2812                                + " package: " + filter.activity.info.packageName
2813                                + " activity: " + filter.activity.className
2814                                + " origPrio: " + filter.getPriority());
2815                    }
2816                    filter.setPriority(0);
2817                }
2818            }
2819            mDeferProtectedFilters = false;
2820            mProtectedFilters.clear();
2821
2822            // Now that we know all of the shared libraries, update all clients to have
2823            // the correct library paths.
2824            updateAllSharedLibrariesLPw(null);
2825
2826            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2827                // NOTE: We ignore potential failures here during a system scan (like
2828                // the rest of the commands above) because there's precious little we
2829                // can do about it. A settings error is reported, though.
2830                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2831            }
2832
2833            // Now that we know all the packages we are keeping,
2834            // read and update their last usage times.
2835            mPackageUsage.read(mPackages);
2836            mCompilerStats.read();
2837
2838            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2839                    SystemClock.uptimeMillis());
2840            Slog.i(TAG, "Time to scan packages: "
2841                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2842                    + " seconds");
2843
2844            // If the platform SDK has changed since the last time we booted,
2845            // we need to re-grant app permission to catch any new ones that
2846            // appear.  This is really a hack, and means that apps can in some
2847            // cases get permissions that the user didn't initially explicitly
2848            // allow...  it would be nice to have some better way to handle
2849            // this situation.
2850            int updateFlags = UPDATE_PERMISSIONS_ALL;
2851            if (ver.sdkVersion != mSdkVersion) {
2852                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2853                        + mSdkVersion + "; regranting permissions for internal storage");
2854                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2855            }
2856            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2857            ver.sdkVersion = mSdkVersion;
2858
2859            // If this is the first boot or an update from pre-M, and it is a normal
2860            // boot, then we need to initialize the default preferred apps across
2861            // all defined users.
2862            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2863                for (UserInfo user : sUserManager.getUsers(true)) {
2864                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2865                    applyFactoryDefaultBrowserLPw(user.id);
2866                    primeDomainVerificationsLPw(user.id);
2867                }
2868            }
2869
2870            // Prepare storage for system user really early during boot,
2871            // since core system apps like SettingsProvider and SystemUI
2872            // can't wait for user to start
2873            final int storageFlags;
2874            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2875                storageFlags = StorageManager.FLAG_STORAGE_DE;
2876            } else {
2877                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2878            }
2879            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2880                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2881                    true /* onlyCoreApps */);
2882            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2883                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2884                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2885                traceLog.traceBegin("AppDataFixup");
2886                try {
2887                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2888                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2889                } catch (InstallerException e) {
2890                    Slog.w(TAG, "Trouble fixing GIDs", e);
2891                }
2892                traceLog.traceEnd();
2893
2894                traceLog.traceBegin("AppDataPrepare");
2895                if (deferPackages == null || deferPackages.isEmpty()) {
2896                    return;
2897                }
2898                int count = 0;
2899                for (String pkgName : deferPackages) {
2900                    PackageParser.Package pkg = null;
2901                    synchronized (mPackages) {
2902                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2903                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2904                            pkg = ps.pkg;
2905                        }
2906                    }
2907                    if (pkg != null) {
2908                        synchronized (mInstallLock) {
2909                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2910                                    true /* maybeMigrateAppData */);
2911                        }
2912                        count++;
2913                    }
2914                }
2915                traceLog.traceEnd();
2916                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2917            }, "prepareAppData");
2918
2919            // If this is first boot after an OTA, and a normal boot, then
2920            // we need to clear code cache directories.
2921            // Note that we do *not* clear the application profiles. These remain valid
2922            // across OTAs and are used to drive profile verification (post OTA) and
2923            // profile compilation (without waiting to collect a fresh set of profiles).
2924            if (mIsUpgrade && !onlyCore) {
2925                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2926                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2927                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2928                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2929                        // No apps are running this early, so no need to freeze
2930                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2931                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2932                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2933                    }
2934                }
2935                ver.fingerprint = Build.FINGERPRINT;
2936            }
2937
2938            checkDefaultBrowser();
2939
2940            // clear only after permissions and other defaults have been updated
2941            mExistingSystemPackages.clear();
2942            mPromoteSystemApps = false;
2943
2944            // All the changes are done during package scanning.
2945            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2946
2947            // can downgrade to reader
2948            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2949            mSettings.writeLPr();
2950            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2951            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2952                    SystemClock.uptimeMillis());
2953
2954            if (!mOnlyCore) {
2955                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2956                mRequiredInstallerPackage = getRequiredInstallerLPr();
2957                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2958                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2959                if (mIntentFilterVerifierComponent != null) {
2960                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2961                            mIntentFilterVerifierComponent);
2962                } else {
2963                    mIntentFilterVerifier = null;
2964                }
2965                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2966                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2967                        SharedLibraryInfo.VERSION_UNDEFINED);
2968                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2969                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2970                        SharedLibraryInfo.VERSION_UNDEFINED);
2971            } else {
2972                mRequiredVerifierPackage = null;
2973                mRequiredInstallerPackage = null;
2974                mRequiredUninstallerPackage = null;
2975                mIntentFilterVerifierComponent = null;
2976                mIntentFilterVerifier = null;
2977                mServicesSystemSharedLibraryPackageName = null;
2978                mSharedSystemSharedLibraryPackageName = null;
2979            }
2980
2981            mInstallerService = new PackageInstallerService(context, this);
2982            final Pair<ComponentName, String> instantAppResolverComponent =
2983                    getInstantAppResolverLPr();
2984            if (instantAppResolverComponent != null) {
2985                if (DEBUG_EPHEMERAL) {
2986                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2987                }
2988                mInstantAppResolverConnection = new EphemeralResolverConnection(
2989                        mContext, instantAppResolverComponent.first,
2990                        instantAppResolverComponent.second);
2991                mInstantAppResolverSettingsComponent =
2992                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2993            } else {
2994                mInstantAppResolverConnection = null;
2995                mInstantAppResolverSettingsComponent = null;
2996            }
2997            updateInstantAppInstallerLocked(null);
2998
2999            // Read and update the usage of dex files.
3000            // Do this at the end of PM init so that all the packages have their
3001            // data directory reconciled.
3002            // At this point we know the code paths of the packages, so we can validate
3003            // the disk file and build the internal cache.
3004            // The usage file is expected to be small so loading and verifying it
3005            // should take a fairly small time compare to the other activities (e.g. package
3006            // scanning).
3007            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3008            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3009            for (int userId : currentUserIds) {
3010                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3011            }
3012            mDexManager.load(userPackages);
3013        } // synchronized (mPackages)
3014        } // synchronized (mInstallLock)
3015
3016        // Now after opening every single application zip, make sure they
3017        // are all flushed.  Not really needed, but keeps things nice and
3018        // tidy.
3019        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3020        Runtime.getRuntime().gc();
3021        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3022
3023        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3024        FallbackCategoryProvider.loadFallbacks();
3025        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3026
3027        // The initial scanning above does many calls into installd while
3028        // holding the mPackages lock, but we're mostly interested in yelling
3029        // once we have a booted system.
3030        mInstaller.setWarnIfHeld(mPackages);
3031
3032        // Expose private service for system components to use.
3033        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3034        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3035    }
3036
3037    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3038        // we're only interested in updating the installer appliction when 1) it's not
3039        // already set or 2) the modified package is the installer
3040        if (mInstantAppInstallerActivity != null
3041                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3042                        .equals(modifiedPackage)) {
3043            return;
3044        }
3045        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3046    }
3047
3048    private static File preparePackageParserCache(boolean isUpgrade) {
3049        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3050            return null;
3051        }
3052
3053        // Disable package parsing on eng builds to allow for faster incremental development.
3054        if ("eng".equals(Build.TYPE)) {
3055            return null;
3056        }
3057
3058        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3059            Slog.i(TAG, "Disabling package parser cache due to system property.");
3060            return null;
3061        }
3062
3063        // The base directory for the package parser cache lives under /data/system/.
3064        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3065                "package_cache");
3066        if (cacheBaseDir == null) {
3067            return null;
3068        }
3069
3070        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3071        // This also serves to "GC" unused entries when the package cache version changes (which
3072        // can only happen during upgrades).
3073        if (isUpgrade) {
3074            FileUtils.deleteContents(cacheBaseDir);
3075        }
3076
3077
3078        // Return the versioned package cache directory. This is something like
3079        // "/data/system/package_cache/1"
3080        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3081
3082        // The following is a workaround to aid development on non-numbered userdebug
3083        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3084        // the system partition is newer.
3085        //
3086        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3087        // that starts with "eng." to signify that this is an engineering build and not
3088        // destined for release.
3089        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3090            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3091
3092            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3093            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3094            // in general and should not be used for production changes. In this specific case,
3095            // we know that they will work.
3096            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3097            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3098                FileUtils.deleteContents(cacheBaseDir);
3099                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3100            }
3101        }
3102
3103        return cacheDir;
3104    }
3105
3106    @Override
3107    public boolean isFirstBoot() {
3108        // allow instant applications
3109        return mFirstBoot;
3110    }
3111
3112    @Override
3113    public boolean isOnlyCoreApps() {
3114        // allow instant applications
3115        return mOnlyCore;
3116    }
3117
3118    @Override
3119    public boolean isUpgrade() {
3120        // allow instant applications
3121        return mIsUpgrade;
3122    }
3123
3124    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3125        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3126
3127        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3128                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3129                UserHandle.USER_SYSTEM);
3130        if (matches.size() == 1) {
3131            return matches.get(0).getComponentInfo().packageName;
3132        } else if (matches.size() == 0) {
3133            Log.e(TAG, "There should probably be a verifier, but, none were found");
3134            return null;
3135        }
3136        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3137    }
3138
3139    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3140        synchronized (mPackages) {
3141            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3142            if (libraryEntry == null) {
3143                throw new IllegalStateException("Missing required shared library:" + name);
3144            }
3145            return libraryEntry.apk;
3146        }
3147    }
3148
3149    private @NonNull String getRequiredInstallerLPr() {
3150        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3151        intent.addCategory(Intent.CATEGORY_DEFAULT);
3152        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3153
3154        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3155                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3156                UserHandle.USER_SYSTEM);
3157        if (matches.size() == 1) {
3158            ResolveInfo resolveInfo = matches.get(0);
3159            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3160                throw new RuntimeException("The installer must be a privileged app");
3161            }
3162            return matches.get(0).getComponentInfo().packageName;
3163        } else {
3164            throw new RuntimeException("There must be exactly one installer; found " + matches);
3165        }
3166    }
3167
3168    private @NonNull String getRequiredUninstallerLPr() {
3169        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3170        intent.addCategory(Intent.CATEGORY_DEFAULT);
3171        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3172
3173        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3174                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3175                UserHandle.USER_SYSTEM);
3176        if (resolveInfo == null ||
3177                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3178            throw new RuntimeException("There must be exactly one uninstaller; found "
3179                    + resolveInfo);
3180        }
3181        return resolveInfo.getComponentInfo().packageName;
3182    }
3183
3184    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3185        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3186
3187        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3188                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3189                UserHandle.USER_SYSTEM);
3190        ResolveInfo best = null;
3191        final int N = matches.size();
3192        for (int i = 0; i < N; i++) {
3193            final ResolveInfo cur = matches.get(i);
3194            final String packageName = cur.getComponentInfo().packageName;
3195            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3196                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3197                continue;
3198            }
3199
3200            if (best == null || cur.priority > best.priority) {
3201                best = cur;
3202            }
3203        }
3204
3205        if (best != null) {
3206            return best.getComponentInfo().getComponentName();
3207        }
3208        Slog.w(TAG, "Intent filter verifier not found");
3209        return null;
3210    }
3211
3212    @Override
3213    public @Nullable ComponentName getInstantAppResolverComponent() {
3214        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3215            return null;
3216        }
3217        synchronized (mPackages) {
3218            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3219            if (instantAppResolver == null) {
3220                return null;
3221            }
3222            return instantAppResolver.first;
3223        }
3224    }
3225
3226    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3227        final String[] packageArray =
3228                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3229        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3230            if (DEBUG_EPHEMERAL) {
3231                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3232            }
3233            return null;
3234        }
3235
3236        final int callingUid = Binder.getCallingUid();
3237        final int resolveFlags =
3238                MATCH_DIRECT_BOOT_AWARE
3239                | MATCH_DIRECT_BOOT_UNAWARE
3240                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3241        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3242        final Intent resolverIntent = new Intent(actionName);
3243        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3244                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3245        // temporarily look for the old action
3246        if (resolvers.size() == 0) {
3247            if (DEBUG_EPHEMERAL) {
3248                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3249            }
3250            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3251            resolverIntent.setAction(actionName);
3252            resolvers = queryIntentServicesInternal(resolverIntent, null,
3253                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3254        }
3255        final int N = resolvers.size();
3256        if (N == 0) {
3257            if (DEBUG_EPHEMERAL) {
3258                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3259            }
3260            return null;
3261        }
3262
3263        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3264        for (int i = 0; i < N; i++) {
3265            final ResolveInfo info = resolvers.get(i);
3266
3267            if (info.serviceInfo == null) {
3268                continue;
3269            }
3270
3271            final String packageName = info.serviceInfo.packageName;
3272            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3273                if (DEBUG_EPHEMERAL) {
3274                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3275                            + " pkg: " + packageName + ", info:" + info);
3276                }
3277                continue;
3278            }
3279
3280            if (DEBUG_EPHEMERAL) {
3281                Slog.v(TAG, "Ephemeral resolver found;"
3282                        + " pkg: " + packageName + ", info:" + info);
3283            }
3284            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3285        }
3286        if (DEBUG_EPHEMERAL) {
3287            Slog.v(TAG, "Ephemeral resolver NOT found");
3288        }
3289        return null;
3290    }
3291
3292    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3293        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3294        intent.addCategory(Intent.CATEGORY_DEFAULT);
3295        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3296
3297        final int resolveFlags =
3298                MATCH_DIRECT_BOOT_AWARE
3299                | MATCH_DIRECT_BOOT_UNAWARE
3300                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3301        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3302                resolveFlags, UserHandle.USER_SYSTEM);
3303        // temporarily look for the old action
3304        if (matches.isEmpty()) {
3305            if (DEBUG_EPHEMERAL) {
3306                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3307            }
3308            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3309            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3310                    resolveFlags, UserHandle.USER_SYSTEM);
3311        }
3312        Iterator<ResolveInfo> iter = matches.iterator();
3313        while (iter.hasNext()) {
3314            final ResolveInfo rInfo = iter.next();
3315            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3316            if (ps != null) {
3317                final PermissionsState permissionsState = ps.getPermissionsState();
3318                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3319                    continue;
3320                }
3321            }
3322            iter.remove();
3323        }
3324        if (matches.size() == 0) {
3325            return null;
3326        } else if (matches.size() == 1) {
3327            return (ActivityInfo) matches.get(0).getComponentInfo();
3328        } else {
3329            throw new RuntimeException(
3330                    "There must be at most one ephemeral installer; found " + matches);
3331        }
3332    }
3333
3334    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3335            @NonNull ComponentName resolver) {
3336        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3337                .addCategory(Intent.CATEGORY_DEFAULT)
3338                .setPackage(resolver.getPackageName());
3339        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3340        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3341                UserHandle.USER_SYSTEM);
3342        // temporarily look for the old action
3343        if (matches.isEmpty()) {
3344            if (DEBUG_EPHEMERAL) {
3345                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3346            }
3347            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3348            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3349                    UserHandle.USER_SYSTEM);
3350        }
3351        if (matches.isEmpty()) {
3352            return null;
3353        }
3354        return matches.get(0).getComponentInfo().getComponentName();
3355    }
3356
3357    private void primeDomainVerificationsLPw(int userId) {
3358        if (DEBUG_DOMAIN_VERIFICATION) {
3359            Slog.d(TAG, "Priming domain verifications in user " + userId);
3360        }
3361
3362        SystemConfig systemConfig = SystemConfig.getInstance();
3363        ArraySet<String> packages = systemConfig.getLinkedApps();
3364
3365        for (String packageName : packages) {
3366            PackageParser.Package pkg = mPackages.get(packageName);
3367            if (pkg != null) {
3368                if (!pkg.isSystemApp()) {
3369                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3370                    continue;
3371                }
3372
3373                ArraySet<String> domains = null;
3374                for (PackageParser.Activity a : pkg.activities) {
3375                    for (ActivityIntentInfo filter : a.intents) {
3376                        if (hasValidDomains(filter)) {
3377                            if (domains == null) {
3378                                domains = new ArraySet<String>();
3379                            }
3380                            domains.addAll(filter.getHostsList());
3381                        }
3382                    }
3383                }
3384
3385                if (domains != null && domains.size() > 0) {
3386                    if (DEBUG_DOMAIN_VERIFICATION) {
3387                        Slog.v(TAG, "      + " + packageName);
3388                    }
3389                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3390                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3391                    // and then 'always' in the per-user state actually used for intent resolution.
3392                    final IntentFilterVerificationInfo ivi;
3393                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3394                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3395                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3396                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3397                } else {
3398                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3399                            + "' does not handle web links");
3400                }
3401            } else {
3402                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3403            }
3404        }
3405
3406        scheduleWritePackageRestrictionsLocked(userId);
3407        scheduleWriteSettingsLocked();
3408    }
3409
3410    private void applyFactoryDefaultBrowserLPw(int userId) {
3411        // The default browser app's package name is stored in a string resource,
3412        // with a product-specific overlay used for vendor customization.
3413        String browserPkg = mContext.getResources().getString(
3414                com.android.internal.R.string.default_browser);
3415        if (!TextUtils.isEmpty(browserPkg)) {
3416            // non-empty string => required to be a known package
3417            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3418            if (ps == null) {
3419                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3420                browserPkg = null;
3421            } else {
3422                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3423            }
3424        }
3425
3426        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3427        // default.  If there's more than one, just leave everything alone.
3428        if (browserPkg == null) {
3429            calculateDefaultBrowserLPw(userId);
3430        }
3431    }
3432
3433    private void calculateDefaultBrowserLPw(int userId) {
3434        List<String> allBrowsers = resolveAllBrowserApps(userId);
3435        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3436        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3437    }
3438
3439    private List<String> resolveAllBrowserApps(int userId) {
3440        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3441        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3442                PackageManager.MATCH_ALL, userId);
3443
3444        final int count = list.size();
3445        List<String> result = new ArrayList<String>(count);
3446        for (int i=0; i<count; i++) {
3447            ResolveInfo info = list.get(i);
3448            if (info.activityInfo == null
3449                    || !info.handleAllWebDataURI
3450                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3451                    || result.contains(info.activityInfo.packageName)) {
3452                continue;
3453            }
3454            result.add(info.activityInfo.packageName);
3455        }
3456
3457        return result;
3458    }
3459
3460    private boolean packageIsBrowser(String packageName, int userId) {
3461        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3462                PackageManager.MATCH_ALL, userId);
3463        final int N = list.size();
3464        for (int i = 0; i < N; i++) {
3465            ResolveInfo info = list.get(i);
3466            if (packageName.equals(info.activityInfo.packageName)) {
3467                return true;
3468            }
3469        }
3470        return false;
3471    }
3472
3473    private void checkDefaultBrowser() {
3474        final int myUserId = UserHandle.myUserId();
3475        final String packageName = getDefaultBrowserPackageName(myUserId);
3476        if (packageName != null) {
3477            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3478            if (info == null) {
3479                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3480                synchronized (mPackages) {
3481                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3482                }
3483            }
3484        }
3485    }
3486
3487    @Override
3488    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3489            throws RemoteException {
3490        try {
3491            return super.onTransact(code, data, reply, flags);
3492        } catch (RuntimeException e) {
3493            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3494                Slog.wtf(TAG, "Package Manager Crash", e);
3495            }
3496            throw e;
3497        }
3498    }
3499
3500    static int[] appendInts(int[] cur, int[] add) {
3501        if (add == null) return cur;
3502        if (cur == null) return add;
3503        final int N = add.length;
3504        for (int i=0; i<N; i++) {
3505            cur = appendInt(cur, add[i]);
3506        }
3507        return cur;
3508    }
3509
3510    /**
3511     * Returns whether or not a full application can see an instant application.
3512     * <p>
3513     * Currently, there are three cases in which this can occur:
3514     * <ol>
3515     * <li>The calling application is a "special" process. The special
3516     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3517     *     and {@code 0}</li>
3518     * <li>The calling application has the permission
3519     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3520     * <li>The calling application is the default launcher on the
3521     *     system partition.</li>
3522     * </ol>
3523     */
3524    private boolean canViewInstantApps(int callingUid, int userId) {
3525        if (callingUid == Process.SYSTEM_UID
3526                || callingUid == Process.SHELL_UID
3527                || callingUid == Process.ROOT_UID) {
3528            return true;
3529        }
3530        if (mContext.checkCallingOrSelfPermission(
3531                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3532            return true;
3533        }
3534        if (mContext.checkCallingOrSelfPermission(
3535                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3536            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3537            if (homeComponent != null
3538                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3539                return true;
3540            }
3541        }
3542        return false;
3543    }
3544
3545    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3546        if (!sUserManager.exists(userId)) return null;
3547        if (ps == null) {
3548            return null;
3549        }
3550        PackageParser.Package p = ps.pkg;
3551        if (p == null) {
3552            return null;
3553        }
3554        final int callingUid = Binder.getCallingUid();
3555        // Filter out ephemeral app metadata:
3556        //   * The system/shell/root can see metadata for any app
3557        //   * An installed app can see metadata for 1) other installed apps
3558        //     and 2) ephemeral apps that have explicitly interacted with it
3559        //   * Ephemeral apps can only see their own data and exposed installed apps
3560        //   * Holding a signature permission allows seeing instant apps
3561        if (filterAppAccessLPr(ps, callingUid, userId)) {
3562            return null;
3563        }
3564
3565        final PermissionsState permissionsState = ps.getPermissionsState();
3566
3567        // Compute GIDs only if requested
3568        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3569                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3570        // Compute granted permissions only if package has requested permissions
3571        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3572                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3573        final PackageUserState state = ps.readUserState(userId);
3574
3575        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3576                && ps.isSystem()) {
3577            flags |= MATCH_ANY_USER;
3578        }
3579
3580        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3581                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3582
3583        if (packageInfo == null) {
3584            return null;
3585        }
3586
3587        rebaseEnabledOverlays(packageInfo.applicationInfo, userId);
3588
3589        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3590                resolveExternalPackageNameLPr(p);
3591
3592        return packageInfo;
3593    }
3594
3595    @Override
3596    public void checkPackageStartable(String packageName, int userId) {
3597        final int callingUid = Binder.getCallingUid();
3598        if (getInstantAppPackageName(callingUid) != null) {
3599            throw new SecurityException("Instant applications don't have access to this method");
3600        }
3601        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3602        synchronized (mPackages) {
3603            final PackageSetting ps = mSettings.mPackages.get(packageName);
3604            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3605                throw new SecurityException("Package " + packageName + " was not found!");
3606            }
3607
3608            if (!ps.getInstalled(userId)) {
3609                throw new SecurityException(
3610                        "Package " + packageName + " was not installed for user " + userId + "!");
3611            }
3612
3613            if (mSafeMode && !ps.isSystem()) {
3614                throw new SecurityException("Package " + packageName + " not a system app!");
3615            }
3616
3617            if (mFrozenPackages.contains(packageName)) {
3618                throw new SecurityException("Package " + packageName + " is currently frozen!");
3619            }
3620
3621            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3622                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3623                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3624            }
3625        }
3626    }
3627
3628    @Override
3629    public boolean isPackageAvailable(String packageName, int userId) {
3630        if (!sUserManager.exists(userId)) return false;
3631        final int callingUid = Binder.getCallingUid();
3632        enforceCrossUserPermission(callingUid, userId,
3633                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3634        synchronized (mPackages) {
3635            PackageParser.Package p = mPackages.get(packageName);
3636            if (p != null) {
3637                final PackageSetting ps = (PackageSetting) p.mExtras;
3638                if (filterAppAccessLPr(ps, callingUid, userId)) {
3639                    return false;
3640                }
3641                if (ps != null) {
3642                    final PackageUserState state = ps.readUserState(userId);
3643                    if (state != null) {
3644                        return PackageParser.isAvailable(state);
3645                    }
3646                }
3647            }
3648        }
3649        return false;
3650    }
3651
3652    @Override
3653    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3654        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3655                flags, Binder.getCallingUid(), userId);
3656    }
3657
3658    @Override
3659    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3660            int flags, int userId) {
3661        return getPackageInfoInternal(versionedPackage.getPackageName(),
3662                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3663    }
3664
3665    /**
3666     * Important: The provided filterCallingUid is used exclusively to filter out packages
3667     * that can be seen based on user state. It's typically the original caller uid prior
3668     * to clearing. Because it can only be provided by trusted code, it's value can be
3669     * trusted and will be used as-is; unlike userId which will be validated by this method.
3670     */
3671    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3672            int flags, int filterCallingUid, int userId) {
3673        if (!sUserManager.exists(userId)) return null;
3674        flags = updateFlagsForPackage(flags, userId, packageName);
3675        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3676                false /* requireFullPermission */, false /* checkShell */, "get package info");
3677
3678        // reader
3679        synchronized (mPackages) {
3680            // Normalize package name to handle renamed packages and static libs
3681            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3682
3683            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3684            if (matchFactoryOnly) {
3685                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3686                if (ps != null) {
3687                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3688                        return null;
3689                    }
3690                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3691                        return null;
3692                    }
3693                    return generatePackageInfo(ps, flags, userId);
3694                }
3695            }
3696
3697            PackageParser.Package p = mPackages.get(packageName);
3698            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3699                return null;
3700            }
3701            if (DEBUG_PACKAGE_INFO)
3702                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3703            if (p != null) {
3704                final PackageSetting ps = (PackageSetting) p.mExtras;
3705                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3706                    return null;
3707                }
3708                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3709                    return null;
3710                }
3711                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3712            }
3713            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3714                final PackageSetting ps = mSettings.mPackages.get(packageName);
3715                if (ps == null) return null;
3716                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3717                    return null;
3718                }
3719                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3720                    return null;
3721                }
3722                return generatePackageInfo(ps, flags, userId);
3723            }
3724        }
3725        return null;
3726    }
3727
3728    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3729        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3730            return true;
3731        }
3732        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3733            return true;
3734        }
3735        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3736            return true;
3737        }
3738        return false;
3739    }
3740
3741    private boolean isComponentVisibleToInstantApp(
3742            @Nullable ComponentName component, @ComponentType int type) {
3743        if (type == TYPE_ACTIVITY) {
3744            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3745            return activity != null
3746                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3747                    : false;
3748        } else if (type == TYPE_RECEIVER) {
3749            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3750            return activity != null
3751                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3752                    : false;
3753        } else if (type == TYPE_SERVICE) {
3754            final PackageParser.Service service = mServices.mServices.get(component);
3755            return service != null
3756                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3757                    : false;
3758        } else if (type == TYPE_PROVIDER) {
3759            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3760            return provider != null
3761                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3762                    : false;
3763        } else if (type == TYPE_UNKNOWN) {
3764            return isComponentVisibleToInstantApp(component);
3765        }
3766        return false;
3767    }
3768
3769    /**
3770     * Returns whether or not access to the application should be filtered.
3771     * <p>
3772     * Access may be limited based upon whether the calling or target applications
3773     * are instant applications.
3774     *
3775     * @see #canAccessInstantApps(int)
3776     */
3777    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3778            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3779        // if we're in an isolated process, get the real calling UID
3780        if (Process.isIsolated(callingUid)) {
3781            callingUid = mIsolatedOwners.get(callingUid);
3782        }
3783        final String instantAppPkgName = getInstantAppPackageName(callingUid);
3784        final boolean callerIsInstantApp = instantAppPkgName != null;
3785        if (ps == null) {
3786            if (callerIsInstantApp) {
3787                // pretend the application exists, but, needs to be filtered
3788                return true;
3789            }
3790            return false;
3791        }
3792        // if the target and caller are the same application, don't filter
3793        if (isCallerSameApp(ps.name, callingUid)) {
3794            return false;
3795        }
3796        if (callerIsInstantApp) {
3797            // request for a specific component; if it hasn't been explicitly exposed, filter
3798            if (component != null) {
3799                return !isComponentVisibleToInstantApp(component, componentType);
3800            }
3801            // request for application; if no components have been explicitly exposed, filter
3802            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
3803        }
3804        if (ps.getInstantApp(userId)) {
3805            // caller can see all components of all instant applications, don't filter
3806            if (canViewInstantApps(callingUid, userId)) {
3807                return false;
3808            }
3809            // request for a specific instant application component, filter
3810            if (component != null) {
3811                return true;
3812            }
3813            // request for an instant application; if the caller hasn't been granted access, filter
3814            return !mInstantAppRegistry.isInstantAccessGranted(
3815                    userId, UserHandle.getAppId(callingUid), ps.appId);
3816        }
3817        return false;
3818    }
3819
3820    /**
3821     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3822     */
3823    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3824        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
3825    }
3826
3827    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3828            int flags) {
3829        // Callers can access only the libs they depend on, otherwise they need to explicitly
3830        // ask for the shared libraries given the caller is allowed to access all static libs.
3831        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3832            // System/shell/root get to see all static libs
3833            final int appId = UserHandle.getAppId(uid);
3834            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3835                    || appId == Process.ROOT_UID) {
3836                return false;
3837            }
3838        }
3839
3840        // No package means no static lib as it is always on internal storage
3841        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3842            return false;
3843        }
3844
3845        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3846                ps.pkg.staticSharedLibVersion);
3847        if (libEntry == null) {
3848            return false;
3849        }
3850
3851        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3852        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3853        if (uidPackageNames == null) {
3854            return true;
3855        }
3856
3857        for (String uidPackageName : uidPackageNames) {
3858            if (ps.name.equals(uidPackageName)) {
3859                return false;
3860            }
3861            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3862            if (uidPs != null) {
3863                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3864                        libEntry.info.getName());
3865                if (index < 0) {
3866                    continue;
3867                }
3868                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3869                    return false;
3870                }
3871            }
3872        }
3873        return true;
3874    }
3875
3876    @Override
3877    public String[] currentToCanonicalPackageNames(String[] names) {
3878        final int callingUid = Binder.getCallingUid();
3879        if (getInstantAppPackageName(callingUid) != null) {
3880            return names;
3881        }
3882        final String[] out = new String[names.length];
3883        // reader
3884        synchronized (mPackages) {
3885            final int callingUserId = UserHandle.getUserId(callingUid);
3886            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3887            for (int i=names.length-1; i>=0; i--) {
3888                final PackageSetting ps = mSettings.mPackages.get(names[i]);
3889                boolean translateName = false;
3890                if (ps != null && ps.realName != null) {
3891                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
3892                    translateName = !targetIsInstantApp
3893                            || canViewInstantApps
3894                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3895                                    UserHandle.getAppId(callingUid), ps.appId);
3896                }
3897                out[i] = translateName ? ps.realName : names[i];
3898            }
3899        }
3900        return out;
3901    }
3902
3903    @Override
3904    public String[] canonicalToCurrentPackageNames(String[] names) {
3905        final int callingUid = Binder.getCallingUid();
3906        if (getInstantAppPackageName(callingUid) != null) {
3907            return names;
3908        }
3909        final String[] out = new String[names.length];
3910        // reader
3911        synchronized (mPackages) {
3912            final int callingUserId = UserHandle.getUserId(callingUid);
3913            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3914            for (int i=names.length-1; i>=0; i--) {
3915                final String cur = mSettings.getRenamedPackageLPr(names[i]);
3916                boolean translateName = false;
3917                if (cur != null) {
3918                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
3919                    final boolean targetIsInstantApp =
3920                            ps != null && ps.getInstantApp(callingUserId);
3921                    translateName = !targetIsInstantApp
3922                            || canViewInstantApps
3923                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3924                                    UserHandle.getAppId(callingUid), ps.appId);
3925                }
3926                out[i] = translateName ? cur : names[i];
3927            }
3928        }
3929        return out;
3930    }
3931
3932    @Override
3933    public int getPackageUid(String packageName, int flags, int userId) {
3934        if (!sUserManager.exists(userId)) return -1;
3935        final int callingUid = Binder.getCallingUid();
3936        flags = updateFlagsForPackage(flags, userId, packageName);
3937        enforceCrossUserPermission(callingUid, userId,
3938                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
3939
3940        // reader
3941        synchronized (mPackages) {
3942            final PackageParser.Package p = mPackages.get(packageName);
3943            if (p != null && p.isMatch(flags)) {
3944                PackageSetting ps = (PackageSetting) p.mExtras;
3945                if (filterAppAccessLPr(ps, callingUid, userId)) {
3946                    return -1;
3947                }
3948                return UserHandle.getUid(userId, p.applicationInfo.uid);
3949            }
3950            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3951                final PackageSetting ps = mSettings.mPackages.get(packageName);
3952                if (ps != null && ps.isMatch(flags)
3953                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3954                    return UserHandle.getUid(userId, ps.appId);
3955                }
3956            }
3957        }
3958
3959        return -1;
3960    }
3961
3962    @Override
3963    public int[] getPackageGids(String packageName, int flags, int userId) {
3964        if (!sUserManager.exists(userId)) return null;
3965        final int callingUid = Binder.getCallingUid();
3966        flags = updateFlagsForPackage(flags, userId, packageName);
3967        enforceCrossUserPermission(callingUid, userId,
3968                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
3969
3970        // reader
3971        synchronized (mPackages) {
3972            final PackageParser.Package p = mPackages.get(packageName);
3973            if (p != null && p.isMatch(flags)) {
3974                PackageSetting ps = (PackageSetting) p.mExtras;
3975                if (filterAppAccessLPr(ps, callingUid, userId)) {
3976                    return null;
3977                }
3978                // TODO: Shouldn't this be checking for package installed state for userId and
3979                // return null?
3980                return ps.getPermissionsState().computeGids(userId);
3981            }
3982            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3983                final PackageSetting ps = mSettings.mPackages.get(packageName);
3984                if (ps != null && ps.isMatch(flags)
3985                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3986                    return ps.getPermissionsState().computeGids(userId);
3987                }
3988            }
3989        }
3990
3991        return null;
3992    }
3993
3994    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3995        if (bp.perm != null) {
3996            return PackageParser.generatePermissionInfo(bp.perm, flags);
3997        }
3998        PermissionInfo pi = new PermissionInfo();
3999        pi.name = bp.name;
4000        pi.packageName = bp.sourcePackage;
4001        pi.nonLocalizedLabel = bp.name;
4002        pi.protectionLevel = bp.protectionLevel;
4003        return pi;
4004    }
4005
4006    @Override
4007    public PermissionInfo getPermissionInfo(String name, int flags) {
4008        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4009            return null;
4010        }
4011        // reader
4012        synchronized (mPackages) {
4013            final BasePermission p = mSettings.mPermissions.get(name);
4014            if (p != null) {
4015                return generatePermissionInfo(p, flags);
4016            }
4017            return null;
4018        }
4019    }
4020
4021    @Override
4022    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4023            int flags) {
4024        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4025            return null;
4026        }
4027        // reader
4028        synchronized (mPackages) {
4029            if (group != null && !mPermissionGroups.containsKey(group)) {
4030                // This is thrown as NameNotFoundException
4031                return null;
4032            }
4033
4034            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4035            for (BasePermission p : mSettings.mPermissions.values()) {
4036                if (group == null) {
4037                    if (p.perm == null || p.perm.info.group == null) {
4038                        out.add(generatePermissionInfo(p, flags));
4039                    }
4040                } else {
4041                    if (p.perm != null && group.equals(p.perm.info.group)) {
4042                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4043                    }
4044                }
4045            }
4046            return new ParceledListSlice<>(out);
4047        }
4048    }
4049
4050    @Override
4051    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4052        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4053            return null;
4054        }
4055        // reader
4056        synchronized (mPackages) {
4057            return PackageParser.generatePermissionGroupInfo(
4058                    mPermissionGroups.get(name), flags);
4059        }
4060    }
4061
4062    @Override
4063    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4064        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4065            return ParceledListSlice.emptyList();
4066        }
4067        // reader
4068        synchronized (mPackages) {
4069            final int N = mPermissionGroups.size();
4070            ArrayList<PermissionGroupInfo> out
4071                    = new ArrayList<PermissionGroupInfo>(N);
4072            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4073                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4074            }
4075            return new ParceledListSlice<>(out);
4076        }
4077    }
4078
4079    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4080            int filterCallingUid, int userId) {
4081        if (!sUserManager.exists(userId)) return null;
4082        PackageSetting ps = mSettings.mPackages.get(packageName);
4083        if (ps != null) {
4084            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4085                return null;
4086            }
4087            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4088                return null;
4089            }
4090            if (ps.pkg == null) {
4091                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4092                if (pInfo != null) {
4093                    return pInfo.applicationInfo;
4094                }
4095                return null;
4096            }
4097            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4098                    ps.readUserState(userId), userId);
4099            if (ai != null) {
4100                rebaseEnabledOverlays(ai, userId);
4101                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4102            }
4103            return ai;
4104        }
4105        return null;
4106    }
4107
4108    @Override
4109    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4110        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4111    }
4112
4113    /**
4114     * Important: The provided filterCallingUid is used exclusively to filter out applications
4115     * that can be seen based on user state. It's typically the original caller uid prior
4116     * to clearing. Because it can only be provided by trusted code, it's value can be
4117     * trusted and will be used as-is; unlike userId which will be validated by this method.
4118     */
4119    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4120            int filterCallingUid, int userId) {
4121        if (!sUserManager.exists(userId)) return null;
4122        flags = updateFlagsForApplication(flags, userId, packageName);
4123        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4124                false /* requireFullPermission */, false /* checkShell */, "get application info");
4125
4126        // writer
4127        synchronized (mPackages) {
4128            // Normalize package name to handle renamed packages and static libs
4129            packageName = resolveInternalPackageNameLPr(packageName,
4130                    PackageManager.VERSION_CODE_HIGHEST);
4131
4132            PackageParser.Package p = mPackages.get(packageName);
4133            if (DEBUG_PACKAGE_INFO) Log.v(
4134                    TAG, "getApplicationInfo " + packageName
4135                    + ": " + p);
4136            if (p != null) {
4137                PackageSetting ps = mSettings.mPackages.get(packageName);
4138                if (ps == null) return null;
4139                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4140                    return null;
4141                }
4142                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4143                    return null;
4144                }
4145                // Note: isEnabledLP() does not apply here - always return info
4146                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4147                        p, flags, ps.readUserState(userId), userId);
4148                if (ai != null) {
4149                    rebaseEnabledOverlays(ai, userId);
4150                    ai.packageName = resolveExternalPackageNameLPr(p);
4151                }
4152                return ai;
4153            }
4154            if ("android".equals(packageName)||"system".equals(packageName)) {
4155                return mAndroidApplication;
4156            }
4157            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4158                // Already generates the external package name
4159                return generateApplicationInfoFromSettingsLPw(packageName,
4160                        flags, filterCallingUid, userId);
4161            }
4162        }
4163        return null;
4164    }
4165
4166    private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) {
4167        List<String> paths = new ArrayList<>();
4168        ArrayMap<String, ArrayList<String>> userSpecificOverlays =
4169            mEnabledOverlayPaths.get(userId);
4170        if (userSpecificOverlays != null) {
4171            if (!"android".equals(ai.packageName)) {
4172                ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android");
4173                if (frameworkOverlays != null) {
4174                    paths.addAll(frameworkOverlays);
4175                }
4176            }
4177
4178            ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName);
4179            if (appOverlays != null) {
4180                paths.addAll(appOverlays);
4181            }
4182        }
4183        ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null;
4184    }
4185
4186    private String normalizePackageNameLPr(String packageName) {
4187        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4188        return normalizedPackageName != null ? normalizedPackageName : packageName;
4189    }
4190
4191    @Override
4192    public void deletePreloadsFileCache() {
4193        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4194            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4195        }
4196        File dir = Environment.getDataPreloadsFileCacheDirectory();
4197        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4198        FileUtils.deleteContents(dir);
4199    }
4200
4201    @Override
4202    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4203            final int storageFlags, final IPackageDataObserver observer) {
4204        mContext.enforceCallingOrSelfPermission(
4205                android.Manifest.permission.CLEAR_APP_CACHE, null);
4206        mHandler.post(() -> {
4207            boolean success = false;
4208            try {
4209                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4210                success = true;
4211            } catch (IOException e) {
4212                Slog.w(TAG, e);
4213            }
4214            if (observer != null) {
4215                try {
4216                    observer.onRemoveCompleted(null, success);
4217                } catch (RemoteException e) {
4218                    Slog.w(TAG, e);
4219                }
4220            }
4221        });
4222    }
4223
4224    @Override
4225    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4226            final int storageFlags, final IntentSender pi) {
4227        mContext.enforceCallingOrSelfPermission(
4228                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4229        mHandler.post(() -> {
4230            boolean success = false;
4231            try {
4232                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4233                success = true;
4234            } catch (IOException e) {
4235                Slog.w(TAG, e);
4236            }
4237            if (pi != null) {
4238                try {
4239                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4240                } catch (SendIntentException e) {
4241                    Slog.w(TAG, e);
4242                }
4243            }
4244        });
4245    }
4246
4247    /**
4248     * Blocking call to clear various types of cached data across the system
4249     * until the requested bytes are available.
4250     */
4251    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4252        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4253        final File file = storage.findPathForUuid(volumeUuid);
4254        if (file.getUsableSpace() >= bytes) return;
4255
4256        if (ENABLE_FREE_CACHE_V2) {
4257            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4258                    volumeUuid);
4259            final boolean aggressive = (storageFlags
4260                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4261            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4262
4263            // 1. Pre-flight to determine if we have any chance to succeed
4264            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4265            if (internalVolume && (aggressive || SystemProperties
4266                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4267                deletePreloadsFileCache();
4268                if (file.getUsableSpace() >= bytes) return;
4269            }
4270
4271            // 3. Consider parsed APK data (aggressive only)
4272            if (internalVolume && aggressive) {
4273                FileUtils.deleteContents(mCacheDir);
4274                if (file.getUsableSpace() >= bytes) return;
4275            }
4276
4277            // 4. Consider cached app data (above quotas)
4278            try {
4279                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4280                        Installer.FLAG_FREE_CACHE_V2);
4281            } catch (InstallerException ignored) {
4282            }
4283            if (file.getUsableSpace() >= bytes) return;
4284
4285            // 5. Consider shared libraries with refcount=0 and age>min cache period
4286            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4287                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4288                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4289                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4290                return;
4291            }
4292
4293            // 6. Consider dexopt output (aggressive only)
4294            // TODO: Implement
4295
4296            // 7. Consider installed instant apps unused longer than min cache period
4297            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4298                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4299                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4300                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4301                return;
4302            }
4303
4304            // 8. Consider cached app data (below quotas)
4305            try {
4306                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4307                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4308            } catch (InstallerException ignored) {
4309            }
4310            if (file.getUsableSpace() >= bytes) return;
4311
4312            // 9. Consider DropBox entries
4313            // TODO: Implement
4314
4315            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4316            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4317                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4318                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4319                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4320                return;
4321            }
4322        } else {
4323            try {
4324                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4325            } catch (InstallerException ignored) {
4326            }
4327            if (file.getUsableSpace() >= bytes) return;
4328        }
4329
4330        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4331    }
4332
4333    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4334            throws IOException {
4335        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4336        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4337
4338        List<VersionedPackage> packagesToDelete = null;
4339        final long now = System.currentTimeMillis();
4340
4341        synchronized (mPackages) {
4342            final int[] allUsers = sUserManager.getUserIds();
4343            final int libCount = mSharedLibraries.size();
4344            for (int i = 0; i < libCount; i++) {
4345                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4346                if (versionedLib == null) {
4347                    continue;
4348                }
4349                final int versionCount = versionedLib.size();
4350                for (int j = 0; j < versionCount; j++) {
4351                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4352                    // Skip packages that are not static shared libs.
4353                    if (!libInfo.isStatic()) {
4354                        break;
4355                    }
4356                    // Important: We skip static shared libs used for some user since
4357                    // in such a case we need to keep the APK on the device. The check for
4358                    // a lib being used for any user is performed by the uninstall call.
4359                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4360                    // Resolve the package name - we use synthetic package names internally
4361                    final String internalPackageName = resolveInternalPackageNameLPr(
4362                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4363                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4364                    // Skip unused static shared libs cached less than the min period
4365                    // to prevent pruning a lib needed by a subsequently installed package.
4366                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4367                        continue;
4368                    }
4369                    if (packagesToDelete == null) {
4370                        packagesToDelete = new ArrayList<>();
4371                    }
4372                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4373                            declaringPackage.getVersionCode()));
4374                }
4375            }
4376        }
4377
4378        if (packagesToDelete != null) {
4379            final int packageCount = packagesToDelete.size();
4380            for (int i = 0; i < packageCount; i++) {
4381                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4382                // Delete the package synchronously (will fail of the lib used for any user).
4383                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4384                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4385                                == PackageManager.DELETE_SUCCEEDED) {
4386                    if (volume.getUsableSpace() >= neededSpace) {
4387                        return true;
4388                    }
4389                }
4390            }
4391        }
4392
4393        return false;
4394    }
4395
4396    /**
4397     * Update given flags based on encryption status of current user.
4398     */
4399    private int updateFlags(int flags, int userId) {
4400        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4401                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4402            // Caller expressed an explicit opinion about what encryption
4403            // aware/unaware components they want to see, so fall through and
4404            // give them what they want
4405        } else {
4406            // Caller expressed no opinion, so match based on user state
4407            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4408                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4409            } else {
4410                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4411            }
4412        }
4413        return flags;
4414    }
4415
4416    private UserManagerInternal getUserManagerInternal() {
4417        if (mUserManagerInternal == null) {
4418            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4419        }
4420        return mUserManagerInternal;
4421    }
4422
4423    private DeviceIdleController.LocalService getDeviceIdleController() {
4424        if (mDeviceIdleController == null) {
4425            mDeviceIdleController =
4426                    LocalServices.getService(DeviceIdleController.LocalService.class);
4427        }
4428        return mDeviceIdleController;
4429    }
4430
4431    /**
4432     * Update given flags when being used to request {@link PackageInfo}.
4433     */
4434    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4435        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4436        boolean triaged = true;
4437        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4438                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4439            // Caller is asking for component details, so they'd better be
4440            // asking for specific encryption matching behavior, or be triaged
4441            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4442                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4443                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4444                triaged = false;
4445            }
4446        }
4447        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4448                | PackageManager.MATCH_SYSTEM_ONLY
4449                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4450            triaged = false;
4451        }
4452        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4453            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4454                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4455                    + Debug.getCallers(5));
4456        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4457                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4458            // If the caller wants all packages and has a restricted profile associated with it,
4459            // then match all users. This is to make sure that launchers that need to access work
4460            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4461            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4462            flags |= PackageManager.MATCH_ANY_USER;
4463        }
4464        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4465            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4466                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4467        }
4468        return updateFlags(flags, userId);
4469    }
4470
4471    /**
4472     * Update given flags when being used to request {@link ApplicationInfo}.
4473     */
4474    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4475        return updateFlagsForPackage(flags, userId, cookie);
4476    }
4477
4478    /**
4479     * Update given flags when being used to request {@link ComponentInfo}.
4480     */
4481    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4482        if (cookie instanceof Intent) {
4483            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4484                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4485            }
4486        }
4487
4488        boolean triaged = true;
4489        // Caller is asking for component details, so they'd better be
4490        // asking for specific encryption matching behavior, or be triaged
4491        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4492                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4493                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4494            triaged = false;
4495        }
4496        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4497            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4498                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4499        }
4500
4501        return updateFlags(flags, userId);
4502    }
4503
4504    /**
4505     * Update given intent when being used to request {@link ResolveInfo}.
4506     */
4507    private Intent updateIntentForResolve(Intent intent) {
4508        if (intent.getSelector() != null) {
4509            intent = intent.getSelector();
4510        }
4511        if (DEBUG_PREFERRED) {
4512            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4513        }
4514        return intent;
4515    }
4516
4517    /**
4518     * Update given flags when being used to request {@link ResolveInfo}.
4519     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4520     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4521     * flag set. However, this flag is only honoured in three circumstances:
4522     * <ul>
4523     * <li>when called from a system process</li>
4524     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4525     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4526     * action and a {@code android.intent.category.BROWSABLE} category</li>
4527     * </ul>
4528     */
4529    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4530        return updateFlagsForResolve(flags, userId, intent, callingUid,
4531                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4532    }
4533    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4534            boolean wantInstantApps) {
4535        return updateFlagsForResolve(flags, userId, intent, callingUid,
4536                wantInstantApps, false /*onlyExposedExplicitly*/);
4537    }
4538    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4539            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4540        // Safe mode means we shouldn't match any third-party components
4541        if (mSafeMode) {
4542            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4543        }
4544        if (getInstantAppPackageName(callingUid) != null) {
4545            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4546            if (onlyExposedExplicitly) {
4547                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4548            }
4549            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4550            flags |= PackageManager.MATCH_INSTANT;
4551        } else {
4552            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4553            final boolean allowMatchInstant =
4554                    (wantInstantApps
4555                            && Intent.ACTION_VIEW.equals(intent.getAction())
4556                            && hasWebURI(intent))
4557                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4558            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4559                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4560            if (!allowMatchInstant) {
4561                flags &= ~PackageManager.MATCH_INSTANT;
4562            }
4563        }
4564        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4565    }
4566
4567    private ActivityInfo generateActivityInfo(ActivityInfo ai, int flags, PackageUserState state,
4568            int userId) {
4569        ActivityInfo ret = PackageParser.generateActivityInfo(ai, flags, state, userId);
4570        if (ret != null) {
4571            rebaseEnabledOverlays(ret.applicationInfo, userId);
4572        }
4573        return ret;
4574    }
4575
4576    private ActivityInfo generateActivityInfo(PackageParser.Activity a, int flags,
4577            PackageUserState state, int userId) {
4578        ActivityInfo ai = PackageParser.generateActivityInfo(a, flags, state, userId);
4579        if (ai != null) {
4580            rebaseEnabledOverlays(ai.applicationInfo, userId);
4581        }
4582        return ai;
4583    }
4584
4585    @Override
4586    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4587        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4588    }
4589
4590    /**
4591     * Important: The provided filterCallingUid is used exclusively to filter out activities
4592     * that can be seen based on user state. It's typically the original caller uid prior
4593     * to clearing. Because it can only be provided by trusted code, it's value can be
4594     * trusted and will be used as-is; unlike userId which will be validated by this method.
4595     */
4596    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4597            int filterCallingUid, int userId) {
4598        if (!sUserManager.exists(userId)) return null;
4599        flags = updateFlagsForComponent(flags, userId, component);
4600        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4601                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4602        synchronized (mPackages) {
4603            PackageParser.Activity a = mActivities.mActivities.get(component);
4604
4605            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4606            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4607                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4608                if (ps == null) return null;
4609                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4610                    return null;
4611                }
4612                return generateActivityInfo(a, flags, ps.readUserState(userId), userId);
4613            }
4614            if (mResolveComponentName.equals(component)) {
4615                return generateActivityInfo(mResolveActivity, flags, new PackageUserState(),
4616                        userId);
4617            }
4618        }
4619        return null;
4620    }
4621
4622    @Override
4623    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4624            String resolvedType) {
4625        synchronized (mPackages) {
4626            if (component.equals(mResolveComponentName)) {
4627                // The resolver supports EVERYTHING!
4628                return true;
4629            }
4630            final int callingUid = Binder.getCallingUid();
4631            final int callingUserId = UserHandle.getUserId(callingUid);
4632            PackageParser.Activity a = mActivities.mActivities.get(component);
4633            if (a == null) {
4634                return false;
4635            }
4636            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4637            if (ps == null) {
4638                return false;
4639            }
4640            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4641                return false;
4642            }
4643            for (int i=0; i<a.intents.size(); i++) {
4644                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4645                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4646                    return true;
4647                }
4648            }
4649            return false;
4650        }
4651    }
4652
4653    @Override
4654    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4655        if (!sUserManager.exists(userId)) return null;
4656        final int callingUid = Binder.getCallingUid();
4657        flags = updateFlagsForComponent(flags, userId, component);
4658        enforceCrossUserPermission(callingUid, userId,
4659                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4660        synchronized (mPackages) {
4661            PackageParser.Activity a = mReceivers.mActivities.get(component);
4662            if (DEBUG_PACKAGE_INFO) Log.v(
4663                TAG, "getReceiverInfo " + component + ": " + a);
4664            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4665                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4666                if (ps == null) return null;
4667                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4668                    return null;
4669                }
4670                return generateActivityInfo(a, flags, ps.readUserState(userId), userId);
4671            }
4672        }
4673        return null;
4674    }
4675
4676    @Override
4677    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4678            int flags, int userId) {
4679        if (!sUserManager.exists(userId)) return null;
4680        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4681        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4682            return null;
4683        }
4684
4685        flags = updateFlagsForPackage(flags, userId, null);
4686
4687        final boolean canSeeStaticLibraries =
4688                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4689                        == PERMISSION_GRANTED
4690                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4691                        == PERMISSION_GRANTED
4692                || canRequestPackageInstallsInternal(packageName,
4693                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4694                        false  /* throwIfPermNotDeclared*/)
4695                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4696                        == PERMISSION_GRANTED;
4697
4698        synchronized (mPackages) {
4699            List<SharedLibraryInfo> result = null;
4700
4701            final int libCount = mSharedLibraries.size();
4702            for (int i = 0; i < libCount; i++) {
4703                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4704                if (versionedLib == null) {
4705                    continue;
4706                }
4707
4708                final int versionCount = versionedLib.size();
4709                for (int j = 0; j < versionCount; j++) {
4710                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4711                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4712                        break;
4713                    }
4714                    final long identity = Binder.clearCallingIdentity();
4715                    try {
4716                        PackageInfo packageInfo = getPackageInfoVersioned(
4717                                libInfo.getDeclaringPackage(), flags
4718                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4719                        if (packageInfo == null) {
4720                            continue;
4721                        }
4722                    } finally {
4723                        Binder.restoreCallingIdentity(identity);
4724                    }
4725
4726                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4727                            libInfo.getVersion(), libInfo.getType(),
4728                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4729                            flags, userId));
4730
4731                    if (result == null) {
4732                        result = new ArrayList<>();
4733                    }
4734                    result.add(resLibInfo);
4735                }
4736            }
4737
4738            return result != null ? new ParceledListSlice<>(result) : null;
4739        }
4740    }
4741
4742    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4743            SharedLibraryInfo libInfo, int flags, int userId) {
4744        List<VersionedPackage> versionedPackages = null;
4745        final int packageCount = mSettings.mPackages.size();
4746        for (int i = 0; i < packageCount; i++) {
4747            PackageSetting ps = mSettings.mPackages.valueAt(i);
4748
4749            if (ps == null) {
4750                continue;
4751            }
4752
4753            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4754                continue;
4755            }
4756
4757            final String libName = libInfo.getName();
4758            if (libInfo.isStatic()) {
4759                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4760                if (libIdx < 0) {
4761                    continue;
4762                }
4763                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4764                    continue;
4765                }
4766                if (versionedPackages == null) {
4767                    versionedPackages = new ArrayList<>();
4768                }
4769                // If the dependent is a static shared lib, use the public package name
4770                String dependentPackageName = ps.name;
4771                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4772                    dependentPackageName = ps.pkg.manifestPackageName;
4773                }
4774                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4775            } else if (ps.pkg != null) {
4776                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4777                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4778                    if (versionedPackages == null) {
4779                        versionedPackages = new ArrayList<>();
4780                    }
4781                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4782                }
4783            }
4784        }
4785
4786        return versionedPackages;
4787    }
4788
4789    @Override
4790    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4791        if (!sUserManager.exists(userId)) return null;
4792        final int callingUid = Binder.getCallingUid();
4793        flags = updateFlagsForComponent(flags, userId, component);
4794        enforceCrossUserPermission(callingUid, userId,
4795                false /* requireFullPermission */, false /* checkShell */, "get service info");
4796        synchronized (mPackages) {
4797            PackageParser.Service s = mServices.mServices.get(component);
4798            if (DEBUG_PACKAGE_INFO) Log.v(
4799                TAG, "getServiceInfo " + component + ": " + s);
4800            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4801                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4802                if (ps == null) return null;
4803                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4804                    return null;
4805                }
4806                ServiceInfo si = PackageParser.generateServiceInfo(s, flags,
4807                        ps.readUserState(userId), userId);
4808                if (si != null) {
4809                    rebaseEnabledOverlays(si.applicationInfo, userId);
4810                }
4811                return si;
4812            }
4813        }
4814        return null;
4815    }
4816
4817    @Override
4818    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4819        if (!sUserManager.exists(userId)) return null;
4820        final int callingUid = Binder.getCallingUid();
4821        flags = updateFlagsForComponent(flags, userId, component);
4822        enforceCrossUserPermission(callingUid, userId,
4823                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4824        synchronized (mPackages) {
4825            PackageParser.Provider p = mProviders.mProviders.get(component);
4826            if (DEBUG_PACKAGE_INFO) Log.v(
4827                TAG, "getProviderInfo " + component + ": " + p);
4828            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4829                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4830                if (ps == null) return null;
4831                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4832                    return null;
4833                }
4834                ProviderInfo pi = PackageParser.generateProviderInfo(p, flags,
4835                        ps.readUserState(userId), userId);
4836                if (pi != null) {
4837                    rebaseEnabledOverlays(pi.applicationInfo, userId);
4838                }
4839                return pi;
4840            }
4841        }
4842        return null;
4843    }
4844
4845    @Override
4846    public String[] getSystemSharedLibraryNames() {
4847        // allow instant applications
4848        synchronized (mPackages) {
4849            Set<String> libs = null;
4850            final int libCount = mSharedLibraries.size();
4851            for (int i = 0; i < libCount; i++) {
4852                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4853                if (versionedLib == null) {
4854                    continue;
4855                }
4856                final int versionCount = versionedLib.size();
4857                for (int j = 0; j < versionCount; j++) {
4858                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4859                    if (!libEntry.info.isStatic()) {
4860                        if (libs == null) {
4861                            libs = new ArraySet<>();
4862                        }
4863                        libs.add(libEntry.info.getName());
4864                        break;
4865                    }
4866                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4867                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4868                            UserHandle.getUserId(Binder.getCallingUid()),
4869                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4870                        if (libs == null) {
4871                            libs = new ArraySet<>();
4872                        }
4873                        libs.add(libEntry.info.getName());
4874                        break;
4875                    }
4876                }
4877            }
4878
4879            if (libs != null) {
4880                String[] libsArray = new String[libs.size()];
4881                libs.toArray(libsArray);
4882                return libsArray;
4883            }
4884
4885            return null;
4886        }
4887    }
4888
4889    @Override
4890    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4891        // allow instant applications
4892        synchronized (mPackages) {
4893            return mServicesSystemSharedLibraryPackageName;
4894        }
4895    }
4896
4897    @Override
4898    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4899        // allow instant applications
4900        synchronized (mPackages) {
4901            return mSharedSystemSharedLibraryPackageName;
4902        }
4903    }
4904
4905    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
4906        for (int i = userList.length - 1; i >= 0; --i) {
4907            final int userId = userList[i];
4908            // don't add instant app to the list of updates
4909            if (pkgSetting.getInstantApp(userId)) {
4910                continue;
4911            }
4912            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4913            if (changedPackages == null) {
4914                changedPackages = new SparseArray<>();
4915                mChangedPackages.put(userId, changedPackages);
4916            }
4917            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4918            if (sequenceNumbers == null) {
4919                sequenceNumbers = new HashMap<>();
4920                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4921            }
4922            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
4923            if (sequenceNumber != null) {
4924                changedPackages.remove(sequenceNumber);
4925            }
4926            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
4927            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
4928        }
4929        mChangedPackagesSequenceNumber++;
4930    }
4931
4932    @Override
4933    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4934        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4935            return null;
4936        }
4937        synchronized (mPackages) {
4938            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4939                return null;
4940            }
4941            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4942            if (changedPackages == null) {
4943                return null;
4944            }
4945            final List<String> packageNames =
4946                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4947            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4948                final String packageName = changedPackages.get(i);
4949                if (packageName != null) {
4950                    packageNames.add(packageName);
4951                }
4952            }
4953            return packageNames.isEmpty()
4954                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4955        }
4956    }
4957
4958    @Override
4959    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4960        // allow instant applications
4961        ArrayList<FeatureInfo> res;
4962        synchronized (mAvailableFeatures) {
4963            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4964            res.addAll(mAvailableFeatures.values());
4965        }
4966        final FeatureInfo fi = new FeatureInfo();
4967        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4968                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4969        res.add(fi);
4970
4971        return new ParceledListSlice<>(res);
4972    }
4973
4974    @Override
4975    public boolean hasSystemFeature(String name, int version) {
4976        // allow instant applications
4977        synchronized (mAvailableFeatures) {
4978            final FeatureInfo feat = mAvailableFeatures.get(name);
4979            if (feat == null) {
4980                return false;
4981            } else {
4982                return feat.version >= version;
4983            }
4984        }
4985    }
4986
4987    @Override
4988    public int checkPermission(String permName, String pkgName, int userId) {
4989        if (!sUserManager.exists(userId)) {
4990            return PackageManager.PERMISSION_DENIED;
4991        }
4992        final int callingUid = Binder.getCallingUid();
4993
4994        synchronized (mPackages) {
4995            final PackageParser.Package p = mPackages.get(pkgName);
4996            if (p != null && p.mExtras != null) {
4997                final PackageSetting ps = (PackageSetting) p.mExtras;
4998                if (filterAppAccessLPr(ps, callingUid, userId)) {
4999                    return PackageManager.PERMISSION_DENIED;
5000                }
5001                final boolean instantApp = ps.getInstantApp(userId);
5002                final PermissionsState permissionsState = ps.getPermissionsState();
5003                if (permissionsState.hasPermission(permName, userId)) {
5004                    if (instantApp) {
5005                        BasePermission bp = mSettings.mPermissions.get(permName);
5006                        if (bp != null && bp.isInstant()) {
5007                            return PackageManager.PERMISSION_GRANTED;
5008                        }
5009                    } else {
5010                        return PackageManager.PERMISSION_GRANTED;
5011                    }
5012                }
5013                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5014                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5015                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5016                    return PackageManager.PERMISSION_GRANTED;
5017                }
5018            }
5019        }
5020
5021        return PackageManager.PERMISSION_DENIED;
5022    }
5023
5024    @Override
5025    public int checkUidPermission(String permName, int uid) {
5026        final int callingUid = Binder.getCallingUid();
5027        final int callingUserId = UserHandle.getUserId(callingUid);
5028        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5029        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5030        final int userId = UserHandle.getUserId(uid);
5031        if (!sUserManager.exists(userId)) {
5032            return PackageManager.PERMISSION_DENIED;
5033        }
5034
5035        synchronized (mPackages) {
5036            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5037            if (obj != null) {
5038                if (obj instanceof SharedUserSetting) {
5039                    if (isCallerInstantApp) {
5040                        return PackageManager.PERMISSION_DENIED;
5041                    }
5042                } else if (obj instanceof PackageSetting) {
5043                    final PackageSetting ps = (PackageSetting) obj;
5044                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5045                        return PackageManager.PERMISSION_DENIED;
5046                    }
5047                }
5048                final SettingBase settingBase = (SettingBase) obj;
5049                final PermissionsState permissionsState = settingBase.getPermissionsState();
5050                if (permissionsState.hasPermission(permName, userId)) {
5051                    if (isUidInstantApp) {
5052                        BasePermission bp = mSettings.mPermissions.get(permName);
5053                        if (bp != null && bp.isInstant()) {
5054                            return PackageManager.PERMISSION_GRANTED;
5055                        }
5056                    } else {
5057                        return PackageManager.PERMISSION_GRANTED;
5058                    }
5059                }
5060                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5061                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5062                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5063                    return PackageManager.PERMISSION_GRANTED;
5064                }
5065            } else {
5066                ArraySet<String> perms = mSystemPermissions.get(uid);
5067                if (perms != null) {
5068                    if (perms.contains(permName)) {
5069                        return PackageManager.PERMISSION_GRANTED;
5070                    }
5071                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5072                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5073                        return PackageManager.PERMISSION_GRANTED;
5074                    }
5075                }
5076            }
5077        }
5078
5079        return PackageManager.PERMISSION_DENIED;
5080    }
5081
5082    @Override
5083    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5084        if (UserHandle.getCallingUserId() != userId) {
5085            mContext.enforceCallingPermission(
5086                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5087                    "isPermissionRevokedByPolicy for user " + userId);
5088        }
5089
5090        if (checkPermission(permission, packageName, userId)
5091                == PackageManager.PERMISSION_GRANTED) {
5092            return false;
5093        }
5094
5095        final int callingUid = Binder.getCallingUid();
5096        if (getInstantAppPackageName(callingUid) != null) {
5097            if (!isCallerSameApp(packageName, callingUid)) {
5098                return false;
5099            }
5100        } else {
5101            if (isInstantApp(packageName, userId)) {
5102                return false;
5103            }
5104        }
5105
5106        final long identity = Binder.clearCallingIdentity();
5107        try {
5108            final int flags = getPermissionFlags(permission, packageName, userId);
5109            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5110        } finally {
5111            Binder.restoreCallingIdentity(identity);
5112        }
5113    }
5114
5115    @Override
5116    public String getPermissionControllerPackageName() {
5117        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5118            throw new SecurityException("Instant applications don't have access to this method");
5119        }
5120        synchronized (mPackages) {
5121            return mRequiredInstallerPackage;
5122        }
5123    }
5124
5125    /**
5126     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5127     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5128     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5129     * @param message the message to log on security exception
5130     */
5131    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5132            boolean checkShell, String message) {
5133        if (userId < 0) {
5134            throw new IllegalArgumentException("Invalid userId " + userId);
5135        }
5136        if (checkShell) {
5137            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5138        }
5139        if (userId == UserHandle.getUserId(callingUid)) return;
5140        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5141            if (requireFullPermission) {
5142                mContext.enforceCallingOrSelfPermission(
5143                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5144            } else {
5145                try {
5146                    mContext.enforceCallingOrSelfPermission(
5147                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5148                } catch (SecurityException se) {
5149                    mContext.enforceCallingOrSelfPermission(
5150                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5151                }
5152            }
5153        }
5154    }
5155
5156    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5157        if (callingUid == Process.SHELL_UID) {
5158            if (userHandle >= 0
5159                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5160                throw new SecurityException("Shell does not have permission to access user "
5161                        + userHandle);
5162            } else if (userHandle < 0) {
5163                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5164                        + Debug.getCallers(3));
5165            }
5166        }
5167    }
5168
5169    private BasePermission findPermissionTreeLP(String permName) {
5170        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5171            if (permName.startsWith(bp.name) &&
5172                    permName.length() > bp.name.length() &&
5173                    permName.charAt(bp.name.length()) == '.') {
5174                return bp;
5175            }
5176        }
5177        return null;
5178    }
5179
5180    private BasePermission checkPermissionTreeLP(String permName) {
5181        if (permName != null) {
5182            BasePermission bp = findPermissionTreeLP(permName);
5183            if (bp != null) {
5184                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5185                    return bp;
5186                }
5187                throw new SecurityException("Calling uid "
5188                        + Binder.getCallingUid()
5189                        + " is not allowed to add to permission tree "
5190                        + bp.name + " owned by uid " + bp.uid);
5191            }
5192        }
5193        throw new SecurityException("No permission tree found for " + permName);
5194    }
5195
5196    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5197        if (s1 == null) {
5198            return s2 == null;
5199        }
5200        if (s2 == null) {
5201            return false;
5202        }
5203        if (s1.getClass() != s2.getClass()) {
5204            return false;
5205        }
5206        return s1.equals(s2);
5207    }
5208
5209    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5210        if (pi1.icon != pi2.icon) return false;
5211        if (pi1.logo != pi2.logo) return false;
5212        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5213        if (!compareStrings(pi1.name, pi2.name)) return false;
5214        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5215        // We'll take care of setting this one.
5216        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5217        // These are not currently stored in settings.
5218        //if (!compareStrings(pi1.group, pi2.group)) return false;
5219        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5220        //if (pi1.labelRes != pi2.labelRes) return false;
5221        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5222        return true;
5223    }
5224
5225    int permissionInfoFootprint(PermissionInfo info) {
5226        int size = info.name.length();
5227        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5228        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5229        return size;
5230    }
5231
5232    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5233        int size = 0;
5234        for (BasePermission perm : mSettings.mPermissions.values()) {
5235            if (perm.uid == tree.uid) {
5236                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5237            }
5238        }
5239        return size;
5240    }
5241
5242    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5243        // We calculate the max size of permissions defined by this uid and throw
5244        // if that plus the size of 'info' would exceed our stated maximum.
5245        if (tree.uid != Process.SYSTEM_UID) {
5246            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5247            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5248                throw new SecurityException("Permission tree size cap exceeded");
5249            }
5250        }
5251    }
5252
5253    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5254        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5255            throw new SecurityException("Instant apps can't add permissions");
5256        }
5257        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5258            throw new SecurityException("Label must be specified in permission");
5259        }
5260        BasePermission tree = checkPermissionTreeLP(info.name);
5261        BasePermission bp = mSettings.mPermissions.get(info.name);
5262        boolean added = bp == null;
5263        boolean changed = true;
5264        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5265        if (added) {
5266            enforcePermissionCapLocked(info, tree);
5267            bp = new BasePermission(info.name, tree.sourcePackage,
5268                    BasePermission.TYPE_DYNAMIC);
5269        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5270            throw new SecurityException(
5271                    "Not allowed to modify non-dynamic permission "
5272                    + info.name);
5273        } else {
5274            if (bp.protectionLevel == fixedLevel
5275                    && bp.perm.owner.equals(tree.perm.owner)
5276                    && bp.uid == tree.uid
5277                    && comparePermissionInfos(bp.perm.info, info)) {
5278                changed = false;
5279            }
5280        }
5281        bp.protectionLevel = fixedLevel;
5282        info = new PermissionInfo(info);
5283        info.protectionLevel = fixedLevel;
5284        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5285        bp.perm.info.packageName = tree.perm.info.packageName;
5286        bp.uid = tree.uid;
5287        if (added) {
5288            mSettings.mPermissions.put(info.name, bp);
5289        }
5290        if (changed) {
5291            if (!async) {
5292                mSettings.writeLPr();
5293            } else {
5294                scheduleWriteSettingsLocked();
5295            }
5296        }
5297        return added;
5298    }
5299
5300    @Override
5301    public boolean addPermission(PermissionInfo info) {
5302        synchronized (mPackages) {
5303            return addPermissionLocked(info, false);
5304        }
5305    }
5306
5307    @Override
5308    public boolean addPermissionAsync(PermissionInfo info) {
5309        synchronized (mPackages) {
5310            return addPermissionLocked(info, true);
5311        }
5312    }
5313
5314    @Override
5315    public void removePermission(String name) {
5316        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5317            throw new SecurityException("Instant applications don't have access to this method");
5318        }
5319        synchronized (mPackages) {
5320            checkPermissionTreeLP(name);
5321            BasePermission bp = mSettings.mPermissions.get(name);
5322            if (bp != null) {
5323                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5324                    throw new SecurityException(
5325                            "Not allowed to modify non-dynamic permission "
5326                            + name);
5327                }
5328                mSettings.mPermissions.remove(name);
5329                mSettings.writeLPr();
5330            }
5331        }
5332    }
5333
5334    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5335            PackageParser.Package pkg, BasePermission bp) {
5336        int index = pkg.requestedPermissions.indexOf(bp.name);
5337        if (index == -1) {
5338            throw new SecurityException("Package " + pkg.packageName
5339                    + " has not requested permission " + bp.name);
5340        }
5341        if (!bp.isRuntime() && !bp.isDevelopment()) {
5342            throw new SecurityException("Permission " + bp.name
5343                    + " is not a changeable permission type");
5344        }
5345    }
5346
5347    @Override
5348    public void grantRuntimePermission(String packageName, String name, final int userId) {
5349        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5350    }
5351
5352    private void grantRuntimePermission(String packageName, String name, final int userId,
5353            boolean overridePolicy) {
5354        if (!sUserManager.exists(userId)) {
5355            Log.e(TAG, "No such user:" + userId);
5356            return;
5357        }
5358        final int callingUid = Binder.getCallingUid();
5359
5360        mContext.enforceCallingOrSelfPermission(
5361                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5362                "grantRuntimePermission");
5363
5364        enforceCrossUserPermission(callingUid, userId,
5365                true /* requireFullPermission */, true /* checkShell */,
5366                "grantRuntimePermission");
5367
5368        final int uid;
5369        final PackageSetting ps;
5370
5371        synchronized (mPackages) {
5372            final PackageParser.Package pkg = mPackages.get(packageName);
5373            if (pkg == null) {
5374                throw new IllegalArgumentException("Unknown package: " + packageName);
5375            }
5376            final BasePermission bp = mSettings.mPermissions.get(name);
5377            if (bp == null) {
5378                throw new IllegalArgumentException("Unknown permission: " + name);
5379            }
5380            ps = (PackageSetting) pkg.mExtras;
5381            if (ps == null
5382                    || filterAppAccessLPr(ps, callingUid, userId)) {
5383                throw new IllegalArgumentException("Unknown package: " + packageName);
5384            }
5385
5386            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5387
5388            // If a permission review is required for legacy apps we represent
5389            // their permissions as always granted runtime ones since we need
5390            // to keep the review required permission flag per user while an
5391            // install permission's state is shared across all users.
5392            if (mPermissionReviewRequired
5393                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5394                    && bp.isRuntime()) {
5395                return;
5396            }
5397
5398            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5399
5400            final PermissionsState permissionsState = ps.getPermissionsState();
5401
5402            final int flags = permissionsState.getPermissionFlags(name, userId);
5403            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5404                throw new SecurityException("Cannot grant system fixed permission "
5405                        + name + " for package " + packageName);
5406            }
5407            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5408                throw new SecurityException("Cannot grant policy fixed permission "
5409                        + name + " for package " + packageName);
5410            }
5411
5412            if (bp.isDevelopment()) {
5413                // Development permissions must be handled specially, since they are not
5414                // normal runtime permissions.  For now they apply to all users.
5415                if (permissionsState.grantInstallPermission(bp) !=
5416                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5417                    scheduleWriteSettingsLocked();
5418                }
5419                return;
5420            }
5421
5422            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5423                throw new SecurityException("Cannot grant non-ephemeral permission"
5424                        + name + " for package " + packageName);
5425            }
5426
5427            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5428                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5429                return;
5430            }
5431
5432            final int result = permissionsState.grantRuntimePermission(bp, userId);
5433            switch (result) {
5434                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5435                    return;
5436                }
5437
5438                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5439                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5440                    mHandler.post(new Runnable() {
5441                        @Override
5442                        public void run() {
5443                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5444                        }
5445                    });
5446                }
5447                break;
5448            }
5449
5450            if (bp.isRuntime()) {
5451                logPermissionGranted(mContext, name, packageName);
5452            }
5453
5454            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5455
5456            // Not critical if that is lost - app has to request again.
5457            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5458        }
5459
5460        // Only need to do this if user is initialized. Otherwise it's a new user
5461        // and there are no processes running as the user yet and there's no need
5462        // to make an expensive call to remount processes for the changed permissions.
5463        if (READ_EXTERNAL_STORAGE.equals(name)
5464                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5465            final long token = Binder.clearCallingIdentity();
5466            try {
5467                if (sUserManager.isInitialized(userId)) {
5468                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5469                            StorageManagerInternal.class);
5470                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5471                }
5472            } finally {
5473                Binder.restoreCallingIdentity(token);
5474            }
5475        }
5476    }
5477
5478    @Override
5479    public void revokeRuntimePermission(String packageName, String name, int userId) {
5480        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5481    }
5482
5483    private void revokeRuntimePermission(String packageName, String name, int userId,
5484            boolean overridePolicy) {
5485        if (!sUserManager.exists(userId)) {
5486            Log.e(TAG, "No such user:" + userId);
5487            return;
5488        }
5489
5490        mContext.enforceCallingOrSelfPermission(
5491                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5492                "revokeRuntimePermission");
5493
5494        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5495                true /* requireFullPermission */, true /* checkShell */,
5496                "revokeRuntimePermission");
5497
5498        final int appId;
5499
5500        synchronized (mPackages) {
5501            final PackageParser.Package pkg = mPackages.get(packageName);
5502            if (pkg == null) {
5503                throw new IllegalArgumentException("Unknown package: " + packageName);
5504            }
5505            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5506            if (ps == null
5507                    || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
5508                throw new IllegalArgumentException("Unknown package: " + packageName);
5509            }
5510            final BasePermission bp = mSettings.mPermissions.get(name);
5511            if (bp == null) {
5512                throw new IllegalArgumentException("Unknown permission: " + name);
5513            }
5514
5515            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5516
5517            // If a permission review is required for legacy apps we represent
5518            // their permissions as always granted runtime ones since we need
5519            // to keep the review required permission flag per user while an
5520            // install permission's state is shared across all users.
5521            if (mPermissionReviewRequired
5522                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5523                    && bp.isRuntime()) {
5524                return;
5525            }
5526
5527            final PermissionsState permissionsState = ps.getPermissionsState();
5528
5529            final int flags = permissionsState.getPermissionFlags(name, userId);
5530            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5531                throw new SecurityException("Cannot revoke system fixed permission "
5532                        + name + " for package " + packageName);
5533            }
5534            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5535                throw new SecurityException("Cannot revoke policy fixed permission "
5536                        + name + " for package " + packageName);
5537            }
5538
5539            if (bp.isDevelopment()) {
5540                // Development permissions must be handled specially, since they are not
5541                // normal runtime permissions.  For now they apply to all users.
5542                if (permissionsState.revokeInstallPermission(bp) !=
5543                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5544                    scheduleWriteSettingsLocked();
5545                }
5546                return;
5547            }
5548
5549            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5550                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5551                return;
5552            }
5553
5554            if (bp.isRuntime()) {
5555                logPermissionRevoked(mContext, name, packageName);
5556            }
5557
5558            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5559
5560            // Critical, after this call app should never have the permission.
5561            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5562
5563            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5564        }
5565
5566        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5567    }
5568
5569    /**
5570     * Get the first event id for the permission.
5571     *
5572     * <p>There are four events for each permission: <ul>
5573     *     <li>Request permission: first id + 0</li>
5574     *     <li>Grant permission: first id + 1</li>
5575     *     <li>Request for permission denied: first id + 2</li>
5576     *     <li>Revoke permission: first id + 3</li>
5577     * </ul></p>
5578     *
5579     * @param name name of the permission
5580     *
5581     * @return The first event id for the permission
5582     */
5583    private static int getBaseEventId(@NonNull String name) {
5584        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5585
5586        if (eventIdIndex == -1) {
5587            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5588                    || "user".equals(Build.TYPE)) {
5589                Log.i(TAG, "Unknown permission " + name);
5590
5591                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5592            } else {
5593                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5594                //
5595                // Also update
5596                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5597                // - metrics_constants.proto
5598                throw new IllegalStateException("Unknown permission " + name);
5599            }
5600        }
5601
5602        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5603    }
5604
5605    /**
5606     * Log that a permission was revoked.
5607     *
5608     * @param context Context of the caller
5609     * @param name name of the permission
5610     * @param packageName package permission if for
5611     */
5612    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5613            @NonNull String packageName) {
5614        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5615    }
5616
5617    /**
5618     * Log that a permission request was granted.
5619     *
5620     * @param context Context of the caller
5621     * @param name name of the permission
5622     * @param packageName package permission if for
5623     */
5624    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5625            @NonNull String packageName) {
5626        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5627    }
5628
5629    @Override
5630    public void resetRuntimePermissions() {
5631        mContext.enforceCallingOrSelfPermission(
5632                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5633                "revokeRuntimePermission");
5634
5635        int callingUid = Binder.getCallingUid();
5636        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5637            mContext.enforceCallingOrSelfPermission(
5638                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5639                    "resetRuntimePermissions");
5640        }
5641
5642        synchronized (mPackages) {
5643            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5644            for (int userId : UserManagerService.getInstance().getUserIds()) {
5645                final int packageCount = mPackages.size();
5646                for (int i = 0; i < packageCount; i++) {
5647                    PackageParser.Package pkg = mPackages.valueAt(i);
5648                    if (!(pkg.mExtras instanceof PackageSetting)) {
5649                        continue;
5650                    }
5651                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5652                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5653                }
5654            }
5655        }
5656    }
5657
5658    @Override
5659    public int getPermissionFlags(String name, String packageName, int userId) {
5660        if (!sUserManager.exists(userId)) {
5661            return 0;
5662        }
5663
5664        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5665
5666        final int callingUid = Binder.getCallingUid();
5667        enforceCrossUserPermission(callingUid, userId,
5668                true /* requireFullPermission */, false /* checkShell */,
5669                "getPermissionFlags");
5670
5671        synchronized (mPackages) {
5672            final PackageParser.Package pkg = mPackages.get(packageName);
5673            if (pkg == null) {
5674                return 0;
5675            }
5676            final BasePermission bp = mSettings.mPermissions.get(name);
5677            if (bp == null) {
5678                return 0;
5679            }
5680            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5681            if (ps == null
5682                    || filterAppAccessLPr(ps, callingUid, userId)) {
5683                return 0;
5684            }
5685            PermissionsState permissionsState = ps.getPermissionsState();
5686            return permissionsState.getPermissionFlags(name, userId);
5687        }
5688    }
5689
5690    @Override
5691    public void updatePermissionFlags(String name, String packageName, int flagMask,
5692            int flagValues, int userId) {
5693        if (!sUserManager.exists(userId)) {
5694            return;
5695        }
5696
5697        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5698
5699        final int callingUid = Binder.getCallingUid();
5700        enforceCrossUserPermission(callingUid, userId,
5701                true /* requireFullPermission */, true /* checkShell */,
5702                "updatePermissionFlags");
5703
5704        // Only the system can change these flags and nothing else.
5705        if (getCallingUid() != Process.SYSTEM_UID) {
5706            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5707            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5708            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5709            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5710            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5711        }
5712
5713        synchronized (mPackages) {
5714            final PackageParser.Package pkg = mPackages.get(packageName);
5715            if (pkg == null) {
5716                throw new IllegalArgumentException("Unknown package: " + packageName);
5717            }
5718            final PackageSetting ps = (PackageSetting) pkg.mExtras;
5719            if (ps == null
5720                    || filterAppAccessLPr(ps, callingUid, userId)) {
5721                throw new IllegalArgumentException("Unknown package: " + packageName);
5722            }
5723
5724            final BasePermission bp = mSettings.mPermissions.get(name);
5725            if (bp == null) {
5726                throw new IllegalArgumentException("Unknown permission: " + name);
5727            }
5728
5729            PermissionsState permissionsState = ps.getPermissionsState();
5730
5731            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5732
5733            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5734                // Install and runtime permissions are stored in different places,
5735                // so figure out what permission changed and persist the change.
5736                if (permissionsState.getInstallPermissionState(name) != null) {
5737                    scheduleWriteSettingsLocked();
5738                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5739                        || hadState) {
5740                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5741                }
5742            }
5743        }
5744    }
5745
5746    /**
5747     * Update the permission flags for all packages and runtime permissions of a user in order
5748     * to allow device or profile owner to remove POLICY_FIXED.
5749     */
5750    @Override
5751    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5752        if (!sUserManager.exists(userId)) {
5753            return;
5754        }
5755
5756        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5757
5758        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5759                true /* requireFullPermission */, true /* checkShell */,
5760                "updatePermissionFlagsForAllApps");
5761
5762        // Only the system can change system fixed flags.
5763        if (getCallingUid() != Process.SYSTEM_UID) {
5764            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5765            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5766        }
5767
5768        synchronized (mPackages) {
5769            boolean changed = false;
5770            final int packageCount = mPackages.size();
5771            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5772                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5773                final PackageSetting ps = (PackageSetting) pkg.mExtras;
5774                if (ps == null) {
5775                    continue;
5776                }
5777                PermissionsState permissionsState = ps.getPermissionsState();
5778                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5779                        userId, flagMask, flagValues);
5780            }
5781            if (changed) {
5782                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5783            }
5784        }
5785    }
5786
5787    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5788        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5789                != PackageManager.PERMISSION_GRANTED
5790            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5791                != PackageManager.PERMISSION_GRANTED) {
5792            throw new SecurityException(message + " requires "
5793                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5794                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5795        }
5796    }
5797
5798    @Override
5799    public boolean shouldShowRequestPermissionRationale(String permissionName,
5800            String packageName, int userId) {
5801        if (UserHandle.getCallingUserId() != userId) {
5802            mContext.enforceCallingPermission(
5803                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5804                    "canShowRequestPermissionRationale for user " + userId);
5805        }
5806
5807        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5808        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5809            return false;
5810        }
5811
5812        if (checkPermission(permissionName, packageName, userId)
5813                == PackageManager.PERMISSION_GRANTED) {
5814            return false;
5815        }
5816
5817        final int flags;
5818
5819        final long identity = Binder.clearCallingIdentity();
5820        try {
5821            flags = getPermissionFlags(permissionName,
5822                    packageName, userId);
5823        } finally {
5824            Binder.restoreCallingIdentity(identity);
5825        }
5826
5827        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5828                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5829                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5830
5831        if ((flags & fixedFlags) != 0) {
5832            return false;
5833        }
5834
5835        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5836    }
5837
5838    @Override
5839    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5840        mContext.enforceCallingOrSelfPermission(
5841                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5842                "addOnPermissionsChangeListener");
5843
5844        synchronized (mPackages) {
5845            mOnPermissionChangeListeners.addListenerLocked(listener);
5846        }
5847    }
5848
5849    @Override
5850    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5851        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5852            throw new SecurityException("Instant applications don't have access to this method");
5853        }
5854        synchronized (mPackages) {
5855            mOnPermissionChangeListeners.removeListenerLocked(listener);
5856        }
5857    }
5858
5859    @Override
5860    public boolean isProtectedBroadcast(String actionName) {
5861        // allow instant applications
5862        synchronized (mPackages) {
5863            if (mProtectedBroadcasts.contains(actionName)) {
5864                return true;
5865            } else if (actionName != null) {
5866                // TODO: remove these terrible hacks
5867                if (actionName.startsWith("android.net.netmon.lingerExpired")
5868                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5869                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5870                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5871                    return true;
5872                }
5873            }
5874        }
5875        return false;
5876    }
5877
5878    @Override
5879    public int checkSignatures(String pkg1, String pkg2) {
5880        synchronized (mPackages) {
5881            final PackageParser.Package p1 = mPackages.get(pkg1);
5882            final PackageParser.Package p2 = mPackages.get(pkg2);
5883            if (p1 == null || p1.mExtras == null
5884                    || p2 == null || p2.mExtras == null) {
5885                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5886            }
5887            final int callingUid = Binder.getCallingUid();
5888            final int callingUserId = UserHandle.getUserId(callingUid);
5889            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5890            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5891            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5892                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5893                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5894            }
5895            return compareSignatures(p1.mSignatures, p2.mSignatures);
5896        }
5897    }
5898
5899    @Override
5900    public int checkUidSignatures(int uid1, int uid2) {
5901        final int callingUid = Binder.getCallingUid();
5902        final int callingUserId = UserHandle.getUserId(callingUid);
5903        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5904        // Map to base uids.
5905        uid1 = UserHandle.getAppId(uid1);
5906        uid2 = UserHandle.getAppId(uid2);
5907        // reader
5908        synchronized (mPackages) {
5909            Signature[] s1;
5910            Signature[] s2;
5911            Object obj = mSettings.getUserIdLPr(uid1);
5912            if (obj != null) {
5913                if (obj instanceof SharedUserSetting) {
5914                    if (isCallerInstantApp) {
5915                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5916                    }
5917                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5918                } else if (obj instanceof PackageSetting) {
5919                    final PackageSetting ps = (PackageSetting) obj;
5920                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5921                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5922                    }
5923                    s1 = ps.signatures.mSignatures;
5924                } else {
5925                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5926                }
5927            } else {
5928                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5929            }
5930            obj = mSettings.getUserIdLPr(uid2);
5931            if (obj != null) {
5932                if (obj instanceof SharedUserSetting) {
5933                    if (isCallerInstantApp) {
5934                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5935                    }
5936                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5937                } else if (obj instanceof PackageSetting) {
5938                    final PackageSetting ps = (PackageSetting) obj;
5939                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5940                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5941                    }
5942                    s2 = ps.signatures.mSignatures;
5943                } else {
5944                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5945                }
5946            } else {
5947                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5948            }
5949            return compareSignatures(s1, s2);
5950        }
5951    }
5952
5953    /**
5954     * This method should typically only be used when granting or revoking
5955     * permissions, since the app may immediately restart after this call.
5956     * <p>
5957     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5958     * guard your work against the app being relaunched.
5959     */
5960    private void killUid(int appId, int userId, String reason) {
5961        final long identity = Binder.clearCallingIdentity();
5962        try {
5963            IActivityManager am = ActivityManager.getService();
5964            if (am != null) {
5965                try {
5966                    am.killUid(appId, userId, reason);
5967                } catch (RemoteException e) {
5968                    /* ignore - same process */
5969                }
5970            }
5971        } finally {
5972            Binder.restoreCallingIdentity(identity);
5973        }
5974    }
5975
5976    /**
5977     * Compares two sets of signatures. Returns:
5978     * <br />
5979     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5980     * <br />
5981     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5982     * <br />
5983     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5984     * <br />
5985     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5986     * <br />
5987     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5988     */
5989    static int compareSignatures(Signature[] s1, Signature[] s2) {
5990        if (s1 == null) {
5991            return s2 == null
5992                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5993                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5994        }
5995
5996        if (s2 == null) {
5997            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5998        }
5999
6000        if (s1.length != s2.length) {
6001            return PackageManager.SIGNATURE_NO_MATCH;
6002        }
6003
6004        // Since both signature sets are of size 1, we can compare without HashSets.
6005        if (s1.length == 1) {
6006            return s1[0].equals(s2[0]) ?
6007                    PackageManager.SIGNATURE_MATCH :
6008                    PackageManager.SIGNATURE_NO_MATCH;
6009        }
6010
6011        ArraySet<Signature> set1 = new ArraySet<Signature>();
6012        for (Signature sig : s1) {
6013            set1.add(sig);
6014        }
6015        ArraySet<Signature> set2 = new ArraySet<Signature>();
6016        for (Signature sig : s2) {
6017            set2.add(sig);
6018        }
6019        // Make sure s2 contains all signatures in s1.
6020        if (set1.equals(set2)) {
6021            return PackageManager.SIGNATURE_MATCH;
6022        }
6023        return PackageManager.SIGNATURE_NO_MATCH;
6024    }
6025
6026    /**
6027     * If the database version for this type of package (internal storage or
6028     * external storage) is less than the version where package signatures
6029     * were updated, return true.
6030     */
6031    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6032        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6033        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6034    }
6035
6036    /**
6037     * Used for backward compatibility to make sure any packages with
6038     * certificate chains get upgraded to the new style. {@code existingSigs}
6039     * will be in the old format (since they were stored on disk from before the
6040     * system upgrade) and {@code scannedSigs} will be in the newer format.
6041     */
6042    private int compareSignaturesCompat(PackageSignatures existingSigs,
6043            PackageParser.Package scannedPkg) {
6044        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6045            return PackageManager.SIGNATURE_NO_MATCH;
6046        }
6047
6048        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6049        for (Signature sig : existingSigs.mSignatures) {
6050            existingSet.add(sig);
6051        }
6052        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6053        for (Signature sig : scannedPkg.mSignatures) {
6054            try {
6055                Signature[] chainSignatures = sig.getChainSignatures();
6056                for (Signature chainSig : chainSignatures) {
6057                    scannedCompatSet.add(chainSig);
6058                }
6059            } catch (CertificateEncodingException e) {
6060                scannedCompatSet.add(sig);
6061            }
6062        }
6063        /*
6064         * Make sure the expanded scanned set contains all signatures in the
6065         * existing one.
6066         */
6067        if (scannedCompatSet.equals(existingSet)) {
6068            // Migrate the old signatures to the new scheme.
6069            existingSigs.assignSignatures(scannedPkg.mSignatures);
6070            // The new KeySets will be re-added later in the scanning process.
6071            synchronized (mPackages) {
6072                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6073            }
6074            return PackageManager.SIGNATURE_MATCH;
6075        }
6076        return PackageManager.SIGNATURE_NO_MATCH;
6077    }
6078
6079    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6080        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6081        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6082    }
6083
6084    private int compareSignaturesRecover(PackageSignatures existingSigs,
6085            PackageParser.Package scannedPkg) {
6086        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6087            return PackageManager.SIGNATURE_NO_MATCH;
6088        }
6089
6090        String msg = null;
6091        try {
6092            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6093                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6094                        + scannedPkg.packageName);
6095                return PackageManager.SIGNATURE_MATCH;
6096            }
6097        } catch (CertificateException e) {
6098            msg = e.getMessage();
6099        }
6100
6101        logCriticalInfo(Log.INFO,
6102                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6103        return PackageManager.SIGNATURE_NO_MATCH;
6104    }
6105
6106    @Override
6107    public List<String> getAllPackages() {
6108        final int callingUid = Binder.getCallingUid();
6109        final int callingUserId = UserHandle.getUserId(callingUid);
6110        synchronized (mPackages) {
6111            if (canViewInstantApps(callingUid, callingUserId)) {
6112                return new ArrayList<String>(mPackages.keySet());
6113            }
6114            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6115            final List<String> result = new ArrayList<>();
6116            if (instantAppPkgName != null) {
6117                // caller is an instant application; filter unexposed applications
6118                for (PackageParser.Package pkg : mPackages.values()) {
6119                    if (!pkg.visibleToInstantApps) {
6120                        continue;
6121                    }
6122                    result.add(pkg.packageName);
6123                }
6124            } else {
6125                // caller is a normal application; filter instant applications
6126                for (PackageParser.Package pkg : mPackages.values()) {
6127                    final PackageSetting ps =
6128                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6129                    if (ps != null
6130                            && ps.getInstantApp(callingUserId)
6131                            && !mInstantAppRegistry.isInstantAccessGranted(
6132                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6133                        continue;
6134                    }
6135                    result.add(pkg.packageName);
6136                }
6137            }
6138            return result;
6139        }
6140    }
6141
6142    @Override
6143    public String[] getPackagesForUid(int uid) {
6144        final int callingUid = Binder.getCallingUid();
6145        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6146        final int userId = UserHandle.getUserId(uid);
6147        uid = UserHandle.getAppId(uid);
6148        // reader
6149        synchronized (mPackages) {
6150            Object obj = mSettings.getUserIdLPr(uid);
6151            if (obj instanceof SharedUserSetting) {
6152                if (isCallerInstantApp) {
6153                    return null;
6154                }
6155                final SharedUserSetting sus = (SharedUserSetting) obj;
6156                final int N = sus.packages.size();
6157                String[] res = new String[N];
6158                final Iterator<PackageSetting> it = sus.packages.iterator();
6159                int i = 0;
6160                while (it.hasNext()) {
6161                    PackageSetting ps = it.next();
6162                    if (ps.getInstalled(userId)) {
6163                        res[i++] = ps.name;
6164                    } else {
6165                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6166                    }
6167                }
6168                return res;
6169            } else if (obj instanceof PackageSetting) {
6170                final PackageSetting ps = (PackageSetting) obj;
6171                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6172                    return new String[]{ps.name};
6173                }
6174            }
6175        }
6176        return null;
6177    }
6178
6179    @Override
6180    public String getNameForUid(int uid) {
6181        final int callingUid = Binder.getCallingUid();
6182        if (getInstantAppPackageName(callingUid) != null) {
6183            return null;
6184        }
6185        synchronized (mPackages) {
6186            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6187            if (obj instanceof SharedUserSetting) {
6188                final SharedUserSetting sus = (SharedUserSetting) obj;
6189                return sus.name + ":" + sus.userId;
6190            } else if (obj instanceof PackageSetting) {
6191                final PackageSetting ps = (PackageSetting) obj;
6192                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6193                    return null;
6194                }
6195                return ps.name;
6196            }
6197        }
6198        return null;
6199    }
6200
6201    @Override
6202    public int getUidForSharedUser(String sharedUserName) {
6203        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6204            return -1;
6205        }
6206        if (sharedUserName == null) {
6207            return -1;
6208        }
6209        // reader
6210        synchronized (mPackages) {
6211            SharedUserSetting suid;
6212            try {
6213                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6214                if (suid != null) {
6215                    return suid.userId;
6216                }
6217            } catch (PackageManagerException ignore) {
6218                // can't happen, but, still need to catch it
6219            }
6220            return -1;
6221        }
6222    }
6223
6224    @Override
6225    public int getFlagsForUid(int uid) {
6226        final int callingUid = Binder.getCallingUid();
6227        if (getInstantAppPackageName(callingUid) != null) {
6228            return 0;
6229        }
6230        synchronized (mPackages) {
6231            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6232            if (obj instanceof SharedUserSetting) {
6233                final SharedUserSetting sus = (SharedUserSetting) obj;
6234                return sus.pkgFlags;
6235            } else if (obj instanceof PackageSetting) {
6236                final PackageSetting ps = (PackageSetting) obj;
6237                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6238                    return 0;
6239                }
6240                return ps.pkgFlags;
6241            }
6242        }
6243        return 0;
6244    }
6245
6246    @Override
6247    public int getPrivateFlagsForUid(int uid) {
6248        final int callingUid = Binder.getCallingUid();
6249        if (getInstantAppPackageName(callingUid) != null) {
6250            return 0;
6251        }
6252        synchronized (mPackages) {
6253            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6254            if (obj instanceof SharedUserSetting) {
6255                final SharedUserSetting sus = (SharedUserSetting) obj;
6256                return sus.pkgPrivateFlags;
6257            } else if (obj instanceof PackageSetting) {
6258                final PackageSetting ps = (PackageSetting) obj;
6259                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6260                    return 0;
6261                }
6262                return ps.pkgPrivateFlags;
6263            }
6264        }
6265        return 0;
6266    }
6267
6268    @Override
6269    public boolean isUidPrivileged(int uid) {
6270        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6271            return false;
6272        }
6273        uid = UserHandle.getAppId(uid);
6274        // reader
6275        synchronized (mPackages) {
6276            Object obj = mSettings.getUserIdLPr(uid);
6277            if (obj instanceof SharedUserSetting) {
6278                final SharedUserSetting sus = (SharedUserSetting) obj;
6279                final Iterator<PackageSetting> it = sus.packages.iterator();
6280                while (it.hasNext()) {
6281                    if (it.next().isPrivileged()) {
6282                        return true;
6283                    }
6284                }
6285            } else if (obj instanceof PackageSetting) {
6286                final PackageSetting ps = (PackageSetting) obj;
6287                return ps.isPrivileged();
6288            }
6289        }
6290        return false;
6291    }
6292
6293    @Override
6294    public String[] getAppOpPermissionPackages(String permissionName) {
6295        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6296            return null;
6297        }
6298        synchronized (mPackages) {
6299            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6300            if (pkgs == null) {
6301                return null;
6302            }
6303            return pkgs.toArray(new String[pkgs.size()]);
6304        }
6305    }
6306
6307    @Override
6308    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6309            int flags, int userId) {
6310        return resolveIntentInternal(
6311                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6312    }
6313
6314    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6315            int flags, int userId, boolean resolveForStart) {
6316        try {
6317            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6318
6319            if (!sUserManager.exists(userId)) return null;
6320            final int callingUid = Binder.getCallingUid();
6321            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6322            enforceCrossUserPermission(callingUid, userId,
6323                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6324
6325            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6326            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6327                    flags, callingUid, userId, resolveForStart);
6328            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6329
6330            final ResolveInfo bestChoice =
6331                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6332            return bestChoice;
6333        } finally {
6334            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6335        }
6336    }
6337
6338    @Override
6339    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6340        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6341            throw new SecurityException(
6342                    "findPersistentPreferredActivity can only be run by the system");
6343        }
6344        if (!sUserManager.exists(userId)) {
6345            return null;
6346        }
6347        final int callingUid = Binder.getCallingUid();
6348        intent = updateIntentForResolve(intent);
6349        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6350        final int flags = updateFlagsForResolve(
6351                0, userId, intent, callingUid, false /*includeInstantApps*/);
6352        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6353                userId);
6354        synchronized (mPackages) {
6355            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6356                    userId);
6357        }
6358    }
6359
6360    @Override
6361    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6362            IntentFilter filter, int match, ComponentName activity) {
6363        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6364            return;
6365        }
6366        final int userId = UserHandle.getCallingUserId();
6367        if (DEBUG_PREFERRED) {
6368            Log.v(TAG, "setLastChosenActivity intent=" + intent
6369                + " resolvedType=" + resolvedType
6370                + " flags=" + flags
6371                + " filter=" + filter
6372                + " match=" + match
6373                + " activity=" + activity);
6374            filter.dump(new PrintStreamPrinter(System.out), "    ");
6375        }
6376        intent.setComponent(null);
6377        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6378                userId);
6379        // Find any earlier preferred or last chosen entries and nuke them
6380        findPreferredActivity(intent, resolvedType,
6381                flags, query, 0, false, true, false, userId);
6382        // Add the new activity as the last chosen for this filter
6383        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6384                "Setting last chosen");
6385    }
6386
6387    @Override
6388    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6389        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6390            return null;
6391        }
6392        final int userId = UserHandle.getCallingUserId();
6393        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6394        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6395                userId);
6396        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6397                false, false, false, userId);
6398    }
6399
6400    /**
6401     * Returns whether or not instant apps have been disabled remotely.
6402     */
6403    private boolean isEphemeralDisabled() {
6404        return mEphemeralAppsDisabled;
6405    }
6406
6407    private boolean isInstantAppAllowed(
6408            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6409            boolean skipPackageCheck) {
6410        if (mInstantAppResolverConnection == null) {
6411            return false;
6412        }
6413        if (mInstantAppInstallerActivity == null) {
6414            return false;
6415        }
6416        if (intent.getComponent() != null) {
6417            return false;
6418        }
6419        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6420            return false;
6421        }
6422        if (!skipPackageCheck && intent.getPackage() != null) {
6423            return false;
6424        }
6425        final boolean isWebUri = hasWebURI(intent);
6426        if (!isWebUri || intent.getData().getHost() == null) {
6427            return false;
6428        }
6429        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6430        // Or if there's already an ephemeral app installed that handles the action
6431        synchronized (mPackages) {
6432            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6433            for (int n = 0; n < count; n++) {
6434                final ResolveInfo info = resolvedActivities.get(n);
6435                final String packageName = info.activityInfo.packageName;
6436                final PackageSetting ps = mSettings.mPackages.get(packageName);
6437                if (ps != null) {
6438                    // only check domain verification status if the app is not a browser
6439                    if (!info.handleAllWebDataURI) {
6440                        // Try to get the status from User settings first
6441                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6442                        final int status = (int) (packedStatus >> 32);
6443                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6444                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6445                            if (DEBUG_EPHEMERAL) {
6446                                Slog.v(TAG, "DENY instant app;"
6447                                    + " pkg: " + packageName + ", status: " + status);
6448                            }
6449                            return false;
6450                        }
6451                    }
6452                    if (ps.getInstantApp(userId)) {
6453                        if (DEBUG_EPHEMERAL) {
6454                            Slog.v(TAG, "DENY instant app installed;"
6455                                    + " pkg: " + packageName);
6456                        }
6457                        return false;
6458                    }
6459                }
6460            }
6461        }
6462        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6463        return true;
6464    }
6465
6466    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6467            Intent origIntent, String resolvedType, String callingPackage,
6468            Bundle verificationBundle, int userId) {
6469        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6470                new InstantAppRequest(responseObj, origIntent, resolvedType,
6471                        callingPackage, userId, verificationBundle));
6472        mHandler.sendMessage(msg);
6473    }
6474
6475    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6476            int flags, List<ResolveInfo> query, int userId) {
6477        if (query != null) {
6478            final int N = query.size();
6479            if (N == 1) {
6480                return query.get(0);
6481            } else if (N > 1) {
6482                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6483                // If there is more than one activity with the same priority,
6484                // then let the user decide between them.
6485                ResolveInfo r0 = query.get(0);
6486                ResolveInfo r1 = query.get(1);
6487                if (DEBUG_INTENT_MATCHING || debug) {
6488                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6489                            + r1.activityInfo.name + "=" + r1.priority);
6490                }
6491                // If the first activity has a higher priority, or a different
6492                // default, then it is always desirable to pick it.
6493                if (r0.priority != r1.priority
6494                        || r0.preferredOrder != r1.preferredOrder
6495                        || r0.isDefault != r1.isDefault) {
6496                    return query.get(0);
6497                }
6498                // If we have saved a preference for a preferred activity for
6499                // this Intent, use that.
6500                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6501                        flags, query, r0.priority, true, false, debug, userId);
6502                if (ri != null) {
6503                    return ri;
6504                }
6505                // If we have an ephemeral app, use it
6506                for (int i = 0; i < N; i++) {
6507                    ri = query.get(i);
6508                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6509                        final String packageName = ri.activityInfo.packageName;
6510                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6511                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6512                        final int status = (int)(packedStatus >> 32);
6513                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6514                            return ri;
6515                        }
6516                    }
6517                }
6518                ri = new ResolveInfo(mResolveInfo);
6519                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6520                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6521                // If all of the options come from the same package, show the application's
6522                // label and icon instead of the generic resolver's.
6523                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6524                // and then throw away the ResolveInfo itself, meaning that the caller loses
6525                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6526                // a fallback for this case; we only set the target package's resources on
6527                // the ResolveInfo, not the ActivityInfo.
6528                final String intentPackage = intent.getPackage();
6529                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6530                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6531                    ri.resolvePackageName = intentPackage;
6532                    if (userNeedsBadging(userId)) {
6533                        ri.noResourceId = true;
6534                    } else {
6535                        ri.icon = appi.icon;
6536                    }
6537                    ri.iconResourceId = appi.icon;
6538                    ri.labelRes = appi.labelRes;
6539                }
6540                ri.activityInfo.applicationInfo = new ApplicationInfo(
6541                        ri.activityInfo.applicationInfo);
6542                if (userId != 0) {
6543                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6544                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6545                }
6546                // Make sure that the resolver is displayable in car mode
6547                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6548                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6549                return ri;
6550            }
6551        }
6552        return null;
6553    }
6554
6555    /**
6556     * Return true if the given list is not empty and all of its contents have
6557     * an activityInfo with the given package name.
6558     */
6559    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6560        if (ArrayUtils.isEmpty(list)) {
6561            return false;
6562        }
6563        for (int i = 0, N = list.size(); i < N; i++) {
6564            final ResolveInfo ri = list.get(i);
6565            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6566            if (ai == null || !packageName.equals(ai.packageName)) {
6567                return false;
6568            }
6569        }
6570        return true;
6571    }
6572
6573    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6574            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6575        final int N = query.size();
6576        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6577                .get(userId);
6578        // Get the list of persistent preferred activities that handle the intent
6579        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6580        List<PersistentPreferredActivity> pprefs = ppir != null
6581                ? ppir.queryIntent(intent, resolvedType,
6582                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6583                        userId)
6584                : null;
6585        if (pprefs != null && pprefs.size() > 0) {
6586            final int M = pprefs.size();
6587            for (int i=0; i<M; i++) {
6588                final PersistentPreferredActivity ppa = pprefs.get(i);
6589                if (DEBUG_PREFERRED || debug) {
6590                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6591                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6592                            + "\n  component=" + ppa.mComponent);
6593                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6594                }
6595                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6596                        flags | MATCH_DISABLED_COMPONENTS, userId);
6597                if (DEBUG_PREFERRED || debug) {
6598                    Slog.v(TAG, "Found persistent preferred activity:");
6599                    if (ai != null) {
6600                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6601                    } else {
6602                        Slog.v(TAG, "  null");
6603                    }
6604                }
6605                if (ai == null) {
6606                    // This previously registered persistent preferred activity
6607                    // component is no longer known. Ignore it and do NOT remove it.
6608                    continue;
6609                }
6610                for (int j=0; j<N; j++) {
6611                    final ResolveInfo ri = query.get(j);
6612                    if (!ri.activityInfo.applicationInfo.packageName
6613                            .equals(ai.applicationInfo.packageName)) {
6614                        continue;
6615                    }
6616                    if (!ri.activityInfo.name.equals(ai.name)) {
6617                        continue;
6618                    }
6619                    //  Found a persistent preference that can handle the intent.
6620                    if (DEBUG_PREFERRED || debug) {
6621                        Slog.v(TAG, "Returning persistent preferred activity: " +
6622                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6623                    }
6624                    return ri;
6625                }
6626            }
6627        }
6628        return null;
6629    }
6630
6631    // TODO: handle preferred activities missing while user has amnesia
6632    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6633            List<ResolveInfo> query, int priority, boolean always,
6634            boolean removeMatches, boolean debug, int userId) {
6635        if (!sUserManager.exists(userId)) return null;
6636        final int callingUid = Binder.getCallingUid();
6637        flags = updateFlagsForResolve(
6638                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6639        intent = updateIntentForResolve(intent);
6640        // writer
6641        synchronized (mPackages) {
6642            // Try to find a matching persistent preferred activity.
6643            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6644                    debug, userId);
6645
6646            // If a persistent preferred activity matched, use it.
6647            if (pri != null) {
6648                return pri;
6649            }
6650
6651            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6652            // Get the list of preferred activities that handle the intent
6653            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6654            List<PreferredActivity> prefs = pir != null
6655                    ? pir.queryIntent(intent, resolvedType,
6656                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6657                            userId)
6658                    : null;
6659            if (prefs != null && prefs.size() > 0) {
6660                boolean changed = false;
6661                try {
6662                    // First figure out how good the original match set is.
6663                    // We will only allow preferred activities that came
6664                    // from the same match quality.
6665                    int match = 0;
6666
6667                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6668
6669                    final int N = query.size();
6670                    for (int j=0; j<N; j++) {
6671                        final ResolveInfo ri = query.get(j);
6672                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6673                                + ": 0x" + Integer.toHexString(match));
6674                        if (ri.match > match) {
6675                            match = ri.match;
6676                        }
6677                    }
6678
6679                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6680                            + Integer.toHexString(match));
6681
6682                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6683                    final int M = prefs.size();
6684                    for (int i=0; i<M; i++) {
6685                        final PreferredActivity pa = prefs.get(i);
6686                        if (DEBUG_PREFERRED || debug) {
6687                            Slog.v(TAG, "Checking PreferredActivity ds="
6688                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6689                                    + "\n  component=" + pa.mPref.mComponent);
6690                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6691                        }
6692                        if (pa.mPref.mMatch != match) {
6693                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6694                                    + Integer.toHexString(pa.mPref.mMatch));
6695                            continue;
6696                        }
6697                        // If it's not an "always" type preferred activity and that's what we're
6698                        // looking for, skip it.
6699                        if (always && !pa.mPref.mAlways) {
6700                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6701                            continue;
6702                        }
6703                        final ActivityInfo ai = getActivityInfo(
6704                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6705                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6706                                userId);
6707                        if (DEBUG_PREFERRED || debug) {
6708                            Slog.v(TAG, "Found preferred activity:");
6709                            if (ai != null) {
6710                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6711                            } else {
6712                                Slog.v(TAG, "  null");
6713                            }
6714                        }
6715                        if (ai == null) {
6716                            // This previously registered preferred activity
6717                            // component is no longer known.  Most likely an update
6718                            // to the app was installed and in the new version this
6719                            // component no longer exists.  Clean it up by removing
6720                            // it from the preferred activities list, and skip it.
6721                            Slog.w(TAG, "Removing dangling preferred activity: "
6722                                    + pa.mPref.mComponent);
6723                            pir.removeFilter(pa);
6724                            changed = true;
6725                            continue;
6726                        }
6727                        for (int j=0; j<N; j++) {
6728                            final ResolveInfo ri = query.get(j);
6729                            if (!ri.activityInfo.applicationInfo.packageName
6730                                    .equals(ai.applicationInfo.packageName)) {
6731                                continue;
6732                            }
6733                            if (!ri.activityInfo.name.equals(ai.name)) {
6734                                continue;
6735                            }
6736
6737                            if (removeMatches) {
6738                                pir.removeFilter(pa);
6739                                changed = true;
6740                                if (DEBUG_PREFERRED) {
6741                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6742                                }
6743                                break;
6744                            }
6745
6746                            // Okay we found a previously set preferred or last chosen app.
6747                            // If the result set is different from when this
6748                            // was created, we need to clear it and re-ask the
6749                            // user their preference, if we're looking for an "always" type entry.
6750                            if (always && !pa.mPref.sameSet(query)) {
6751                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6752                                        + intent + " type " + resolvedType);
6753                                if (DEBUG_PREFERRED) {
6754                                    Slog.v(TAG, "Removing preferred activity since set changed "
6755                                            + pa.mPref.mComponent);
6756                                }
6757                                pir.removeFilter(pa);
6758                                // Re-add the filter as a "last chosen" entry (!always)
6759                                PreferredActivity lastChosen = new PreferredActivity(
6760                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6761                                pir.addFilter(lastChosen);
6762                                changed = true;
6763                                return null;
6764                            }
6765
6766                            // Yay! Either the set matched or we're looking for the last chosen
6767                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6768                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6769                            return ri;
6770                        }
6771                    }
6772                } finally {
6773                    if (changed) {
6774                        if (DEBUG_PREFERRED) {
6775                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6776                        }
6777                        scheduleWritePackageRestrictionsLocked(userId);
6778                    }
6779                }
6780            }
6781        }
6782        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6783        return null;
6784    }
6785
6786    /*
6787     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6788     */
6789    @Override
6790    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6791            int targetUserId) {
6792        mContext.enforceCallingOrSelfPermission(
6793                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6794        List<CrossProfileIntentFilter> matches =
6795                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6796        if (matches != null) {
6797            int size = matches.size();
6798            for (int i = 0; i < size; i++) {
6799                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6800            }
6801        }
6802        if (hasWebURI(intent)) {
6803            // cross-profile app linking works only towards the parent.
6804            final int callingUid = Binder.getCallingUid();
6805            final UserInfo parent = getProfileParent(sourceUserId);
6806            synchronized(mPackages) {
6807                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6808                        false /*includeInstantApps*/);
6809                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6810                        intent, resolvedType, flags, sourceUserId, parent.id);
6811                return xpDomainInfo != null;
6812            }
6813        }
6814        return false;
6815    }
6816
6817    private UserInfo getProfileParent(int userId) {
6818        final long identity = Binder.clearCallingIdentity();
6819        try {
6820            return sUserManager.getProfileParent(userId);
6821        } finally {
6822            Binder.restoreCallingIdentity(identity);
6823        }
6824    }
6825
6826    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6827            String resolvedType, int userId) {
6828        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6829        if (resolver != null) {
6830            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6831        }
6832        return null;
6833    }
6834
6835    @Override
6836    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6837            String resolvedType, int flags, int userId) {
6838        try {
6839            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6840
6841            return new ParceledListSlice<>(
6842                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6843        } finally {
6844            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6845        }
6846    }
6847
6848    /**
6849     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6850     * instant, returns {@code null}.
6851     */
6852    private String getInstantAppPackageName(int callingUid) {
6853        synchronized (mPackages) {
6854            // If the caller is an isolated app use the owner's uid for the lookup.
6855            if (Process.isIsolated(callingUid)) {
6856                callingUid = mIsolatedOwners.get(callingUid);
6857            }
6858            final int appId = UserHandle.getAppId(callingUid);
6859            final Object obj = mSettings.getUserIdLPr(appId);
6860            if (obj instanceof PackageSetting) {
6861                final PackageSetting ps = (PackageSetting) obj;
6862                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6863                return isInstantApp ? ps.pkg.packageName : null;
6864            }
6865        }
6866        return null;
6867    }
6868
6869    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6870            String resolvedType, int flags, int userId) {
6871        return queryIntentActivitiesInternal(
6872                intent, resolvedType, flags, Binder.getCallingUid(), userId, false);
6873    }
6874
6875    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6876            String resolvedType, int flags, int filterCallingUid, int userId,
6877            boolean resolveForStart) {
6878        if (!sUserManager.exists(userId)) return Collections.emptyList();
6879        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6880        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6881                false /* requireFullPermission */, false /* checkShell */,
6882                "query intent activities");
6883        final String pkgName = intent.getPackage();
6884        ComponentName comp = intent.getComponent();
6885        if (comp == null) {
6886            if (intent.getSelector() != null) {
6887                intent = intent.getSelector();
6888                comp = intent.getComponent();
6889            }
6890        }
6891
6892        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6893                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6894        if (comp != null) {
6895            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6896            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6897            if (ai != null) {
6898                // When specifying an explicit component, we prevent the activity from being
6899                // used when either 1) the calling package is normal and the activity is within
6900                // an ephemeral application or 2) the calling package is ephemeral and the
6901                // activity is not visible to ephemeral applications.
6902                final boolean matchInstantApp =
6903                        (flags & PackageManager.MATCH_INSTANT) != 0;
6904                final boolean matchVisibleToInstantAppOnly =
6905                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6906                final boolean matchExplicitlyVisibleOnly =
6907                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6908                final boolean isCallerInstantApp =
6909                        instantAppPkgName != null;
6910                final boolean isTargetSameInstantApp =
6911                        comp.getPackageName().equals(instantAppPkgName);
6912                final boolean isTargetInstantApp =
6913                        (ai.applicationInfo.privateFlags
6914                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6915                final boolean isTargetVisibleToInstantApp =
6916                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6917                final boolean isTargetExplicitlyVisibleToInstantApp =
6918                        isTargetVisibleToInstantApp
6919                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6920                final boolean isTargetHiddenFromInstantApp =
6921                        !isTargetVisibleToInstantApp
6922                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6923                final boolean blockResolution =
6924                        !isTargetSameInstantApp
6925                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6926                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6927                                        && isTargetHiddenFromInstantApp));
6928                if (!blockResolution) {
6929                    final ResolveInfo ri = new ResolveInfo();
6930                    ri.activityInfo = ai;
6931                    list.add(ri);
6932                }
6933            }
6934            return applyPostResolutionFilter(list, instantAppPkgName);
6935        }
6936
6937        // reader
6938        boolean sortResult = false;
6939        boolean addEphemeral = false;
6940        List<ResolveInfo> result;
6941        final boolean ephemeralDisabled = isEphemeralDisabled();
6942        synchronized (mPackages) {
6943            if (pkgName == null) {
6944                List<CrossProfileIntentFilter> matchingFilters =
6945                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6946                // Check for results that need to skip the current profile.
6947                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6948                        resolvedType, flags, userId);
6949                if (xpResolveInfo != null) {
6950                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6951                    xpResult.add(xpResolveInfo);
6952                    return applyPostResolutionFilter(
6953                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6954                }
6955
6956                // Check for results in the current profile.
6957                result = filterIfNotSystemUser(mActivities.queryIntent(
6958                        intent, resolvedType, flags, userId), userId);
6959                addEphemeral = !ephemeralDisabled
6960                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6961                // Check for cross profile results.
6962                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6963                xpResolveInfo = queryCrossProfileIntents(
6964                        matchingFilters, intent, resolvedType, flags, userId,
6965                        hasNonNegativePriorityResult);
6966                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6967                    boolean isVisibleToUser = filterIfNotSystemUser(
6968                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6969                    if (isVisibleToUser) {
6970                        result.add(xpResolveInfo);
6971                        sortResult = true;
6972                    }
6973                }
6974                if (hasWebURI(intent)) {
6975                    CrossProfileDomainInfo xpDomainInfo = null;
6976                    final UserInfo parent = getProfileParent(userId);
6977                    if (parent != null) {
6978                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6979                                flags, userId, parent.id);
6980                    }
6981                    if (xpDomainInfo != null) {
6982                        if (xpResolveInfo != null) {
6983                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6984                            // in the result.
6985                            result.remove(xpResolveInfo);
6986                        }
6987                        if (result.size() == 0 && !addEphemeral) {
6988                            // No result in current profile, but found candidate in parent user.
6989                            // And we are not going to add emphemeral app, so we can return the
6990                            // result straight away.
6991                            result.add(xpDomainInfo.resolveInfo);
6992                            return applyPostResolutionFilter(result, instantAppPkgName);
6993                        }
6994                    } else if (result.size() <= 1 && !addEphemeral) {
6995                        // No result in parent user and <= 1 result in current profile, and we
6996                        // are not going to add emphemeral app, so we can return the result without
6997                        // further processing.
6998                        return applyPostResolutionFilter(result, instantAppPkgName);
6999                    }
7000                    // We have more than one candidate (combining results from current and parent
7001                    // profile), so we need filtering and sorting.
7002                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
7003                            intent, flags, result, xpDomainInfo, userId);
7004                    sortResult = true;
7005                }
7006            } else {
7007                final PackageParser.Package pkg = mPackages.get(pkgName);
7008                result = null;
7009                if (pkg != null) {
7010                    result = filterIfNotSystemUser(
7011                            mActivities.queryIntentForPackage(
7012                                    intent, resolvedType, flags, pkg.activities, userId),
7013                            userId);
7014                }
7015                if (result == null || result.size() == 0) {
7016                    // the caller wants to resolve for a particular package; however, there
7017                    // were no installed results, so, try to find an ephemeral result
7018                    addEphemeral = !ephemeralDisabled
7019                            && isInstantAppAllowed(
7020                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7021                    if (result == null) {
7022                        result = new ArrayList<>();
7023                    }
7024                }
7025            }
7026        }
7027        if (addEphemeral) {
7028            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
7029        }
7030        if (sortResult) {
7031            Collections.sort(result, mResolvePrioritySorter);
7032        }
7033        return applyPostResolutionFilter(result, instantAppPkgName);
7034    }
7035
7036    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7037            String resolvedType, int flags, int userId) {
7038        // first, check to see if we've got an instant app already installed
7039        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7040        ResolveInfo localInstantApp = null;
7041        boolean blockResolution = false;
7042        if (!alreadyResolvedLocally) {
7043            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7044                    flags
7045                        | PackageManager.GET_RESOLVED_FILTER
7046                        | PackageManager.MATCH_INSTANT
7047                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7048                    userId);
7049            for (int i = instantApps.size() - 1; i >= 0; --i) {
7050                final ResolveInfo info = instantApps.get(i);
7051                final String packageName = info.activityInfo.packageName;
7052                final PackageSetting ps = mSettings.mPackages.get(packageName);
7053                if (ps.getInstantApp(userId)) {
7054                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7055                    final int status = (int)(packedStatus >> 32);
7056                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7057                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7058                        // there's a local instant application installed, but, the user has
7059                        // chosen to never use it; skip resolution and don't acknowledge
7060                        // an instant application is even available
7061                        if (DEBUG_EPHEMERAL) {
7062                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7063                        }
7064                        blockResolution = true;
7065                        break;
7066                    } else {
7067                        // we have a locally installed instant application; skip resolution
7068                        // but acknowledge there's an instant application available
7069                        if (DEBUG_EPHEMERAL) {
7070                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7071                        }
7072                        localInstantApp = info;
7073                        break;
7074                    }
7075                }
7076            }
7077        }
7078        // no app installed, let's see if one's available
7079        AuxiliaryResolveInfo auxiliaryResponse = null;
7080        if (!blockResolution) {
7081            if (localInstantApp == null) {
7082                // we don't have an instant app locally, resolve externally
7083                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7084                final InstantAppRequest requestObject = new InstantAppRequest(
7085                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7086                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7087                auxiliaryResponse =
7088                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7089                                mContext, mInstantAppResolverConnection, requestObject);
7090                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7091            } else {
7092                // we have an instant application locally, but, we can't admit that since
7093                // callers shouldn't be able to determine prior browsing. create a dummy
7094                // auxiliary response so the downstream code behaves as if there's an
7095                // instant application available externally. when it comes time to start
7096                // the instant application, we'll do the right thing.
7097                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7098                auxiliaryResponse = new AuxiliaryResolveInfo(
7099                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
7100            }
7101        }
7102        if (auxiliaryResponse != null) {
7103            if (DEBUG_EPHEMERAL) {
7104                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7105            }
7106            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7107            final PackageSetting ps =
7108                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7109            if (ps != null) {
7110                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7111                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7112                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7113                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7114                // make sure this resolver is the default
7115                ephemeralInstaller.isDefault = true;
7116                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7117                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7118                // add a non-generic filter
7119                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7120                ephemeralInstaller.filter.addDataPath(
7121                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7122                ephemeralInstaller.isInstantAppAvailable = true;
7123                result.add(ephemeralInstaller);
7124            }
7125        }
7126        return result;
7127    }
7128
7129    private static class CrossProfileDomainInfo {
7130        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7131        ResolveInfo resolveInfo;
7132        /* Best domain verification status of the activities found in the other profile */
7133        int bestDomainVerificationStatus;
7134    }
7135
7136    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7137            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7138        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7139                sourceUserId)) {
7140            return null;
7141        }
7142        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7143                resolvedType, flags, parentUserId);
7144
7145        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7146            return null;
7147        }
7148        CrossProfileDomainInfo result = null;
7149        int size = resultTargetUser.size();
7150        for (int i = 0; i < size; i++) {
7151            ResolveInfo riTargetUser = resultTargetUser.get(i);
7152            // Intent filter verification is only for filters that specify a host. So don't return
7153            // those that handle all web uris.
7154            if (riTargetUser.handleAllWebDataURI) {
7155                continue;
7156            }
7157            String packageName = riTargetUser.activityInfo.packageName;
7158            PackageSetting ps = mSettings.mPackages.get(packageName);
7159            if (ps == null) {
7160                continue;
7161            }
7162            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7163            int status = (int)(verificationState >> 32);
7164            if (result == null) {
7165                result = new CrossProfileDomainInfo();
7166                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7167                        sourceUserId, parentUserId);
7168                result.bestDomainVerificationStatus = status;
7169            } else {
7170                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7171                        result.bestDomainVerificationStatus);
7172            }
7173        }
7174        // Don't consider matches with status NEVER across profiles.
7175        if (result != null && result.bestDomainVerificationStatus
7176                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7177            return null;
7178        }
7179        return result;
7180    }
7181
7182    /**
7183     * Verification statuses are ordered from the worse to the best, except for
7184     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7185     */
7186    private int bestDomainVerificationStatus(int status1, int status2) {
7187        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7188            return status2;
7189        }
7190        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7191            return status1;
7192        }
7193        return (int) MathUtils.max(status1, status2);
7194    }
7195
7196    private boolean isUserEnabled(int userId) {
7197        long callingId = Binder.clearCallingIdentity();
7198        try {
7199            UserInfo userInfo = sUserManager.getUserInfo(userId);
7200            return userInfo != null && userInfo.isEnabled();
7201        } finally {
7202            Binder.restoreCallingIdentity(callingId);
7203        }
7204    }
7205
7206    /**
7207     * Filter out activities with systemUserOnly flag set, when current user is not System.
7208     *
7209     * @return filtered list
7210     */
7211    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7212        if (userId == UserHandle.USER_SYSTEM) {
7213            return resolveInfos;
7214        }
7215        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7216            ResolveInfo info = resolveInfos.get(i);
7217            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7218                resolveInfos.remove(i);
7219            }
7220        }
7221        return resolveInfos;
7222    }
7223
7224    /**
7225     * Filters out ephemeral activities.
7226     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7227     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7228     *
7229     * @param resolveInfos The pre-filtered list of resolved activities
7230     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7231     *          is performed.
7232     * @return A filtered list of resolved activities.
7233     */
7234    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7235            String ephemeralPkgName) {
7236        // TODO: When adding on-demand split support for non-instant apps, remove this check
7237        // and always apply post filtering
7238        if (ephemeralPkgName == null) {
7239            return resolveInfos;
7240        }
7241        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7242            final ResolveInfo info = resolveInfos.get(i);
7243            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7244            // allow activities that are defined in the provided package
7245            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
7246                if (info.activityInfo.splitName != null
7247                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7248                                info.activityInfo.splitName)) {
7249                    // requested activity is defined in a split that hasn't been installed yet.
7250                    // add the installer to the resolve list
7251                    if (DEBUG_EPHEMERAL) {
7252                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7253                    }
7254                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7255                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7256                            info.activityInfo.packageName, info.activityInfo.splitName,
7257                            info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7258                    // make sure this resolver is the default
7259                    installerInfo.isDefault = true;
7260                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7261                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7262                    // add a non-generic filter
7263                    installerInfo.filter = new IntentFilter();
7264                    // load resources from the correct package
7265                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7266                    resolveInfos.set(i, installerInfo);
7267                }
7268                continue;
7269            }
7270            // allow activities that have been explicitly exposed to ephemeral apps
7271            if (!isEphemeralApp
7272                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7273                continue;
7274            }
7275            resolveInfos.remove(i);
7276        }
7277        return resolveInfos;
7278    }
7279
7280    /**
7281     * @param resolveInfos list of resolve infos in descending priority order
7282     * @return if the list contains a resolve info with non-negative priority
7283     */
7284    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7285        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7286    }
7287
7288    private static boolean hasWebURI(Intent intent) {
7289        if (intent.getData() == null) {
7290            return false;
7291        }
7292        final String scheme = intent.getScheme();
7293        if (TextUtils.isEmpty(scheme)) {
7294            return false;
7295        }
7296        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7297    }
7298
7299    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7300            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7301            int userId) {
7302        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7303
7304        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7305            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7306                    candidates.size());
7307        }
7308
7309        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7310        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7311        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7312        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7313        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7314        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7315
7316        synchronized (mPackages) {
7317            final int count = candidates.size();
7318            // First, try to use linked apps. Partition the candidates into four lists:
7319            // one for the final results, one for the "do not use ever", one for "undefined status"
7320            // and finally one for "browser app type".
7321            for (int n=0; n<count; n++) {
7322                ResolveInfo info = candidates.get(n);
7323                String packageName = info.activityInfo.packageName;
7324                PackageSetting ps = mSettings.mPackages.get(packageName);
7325                if (ps != null) {
7326                    // Add to the special match all list (Browser use case)
7327                    if (info.handleAllWebDataURI) {
7328                        matchAllList.add(info);
7329                        continue;
7330                    }
7331                    // Try to get the status from User settings first
7332                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7333                    int status = (int)(packedStatus >> 32);
7334                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7335                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7336                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7337                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7338                                    + " : linkgen=" + linkGeneration);
7339                        }
7340                        // Use link-enabled generation as preferredOrder, i.e.
7341                        // prefer newly-enabled over earlier-enabled.
7342                        info.preferredOrder = linkGeneration;
7343                        alwaysList.add(info);
7344                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7345                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7346                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7347                        }
7348                        neverList.add(info);
7349                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7350                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7351                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7352                        }
7353                        alwaysAskList.add(info);
7354                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7355                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7356                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7357                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7358                        }
7359                        undefinedList.add(info);
7360                    }
7361                }
7362            }
7363
7364            // We'll want to include browser possibilities in a few cases
7365            boolean includeBrowser = false;
7366
7367            // First try to add the "always" resolution(s) for the current user, if any
7368            if (alwaysList.size() > 0) {
7369                result.addAll(alwaysList);
7370            } else {
7371                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7372                result.addAll(undefinedList);
7373                // Maybe add one for the other profile.
7374                if (xpDomainInfo != null && (
7375                        xpDomainInfo.bestDomainVerificationStatus
7376                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7377                    result.add(xpDomainInfo.resolveInfo);
7378                }
7379                includeBrowser = true;
7380            }
7381
7382            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7383            // If there were 'always' entries their preferred order has been set, so we also
7384            // back that off to make the alternatives equivalent
7385            if (alwaysAskList.size() > 0) {
7386                for (ResolveInfo i : result) {
7387                    i.preferredOrder = 0;
7388                }
7389                result.addAll(alwaysAskList);
7390                includeBrowser = true;
7391            }
7392
7393            if (includeBrowser) {
7394                // Also add browsers (all of them or only the default one)
7395                if (DEBUG_DOMAIN_VERIFICATION) {
7396                    Slog.v(TAG, "   ...including browsers in candidate set");
7397                }
7398                if ((matchFlags & MATCH_ALL) != 0) {
7399                    result.addAll(matchAllList);
7400                } else {
7401                    // Browser/generic handling case.  If there's a default browser, go straight
7402                    // to that (but only if there is no other higher-priority match).
7403                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7404                    int maxMatchPrio = 0;
7405                    ResolveInfo defaultBrowserMatch = null;
7406                    final int numCandidates = matchAllList.size();
7407                    for (int n = 0; n < numCandidates; n++) {
7408                        ResolveInfo info = matchAllList.get(n);
7409                        // track the highest overall match priority...
7410                        if (info.priority > maxMatchPrio) {
7411                            maxMatchPrio = info.priority;
7412                        }
7413                        // ...and the highest-priority default browser match
7414                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7415                            if (defaultBrowserMatch == null
7416                                    || (defaultBrowserMatch.priority < info.priority)) {
7417                                if (debug) {
7418                                    Slog.v(TAG, "Considering default browser match " + info);
7419                                }
7420                                defaultBrowserMatch = info;
7421                            }
7422                        }
7423                    }
7424                    if (defaultBrowserMatch != null
7425                            && defaultBrowserMatch.priority >= maxMatchPrio
7426                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7427                    {
7428                        if (debug) {
7429                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7430                        }
7431                        result.add(defaultBrowserMatch);
7432                    } else {
7433                        result.addAll(matchAllList);
7434                    }
7435                }
7436
7437                // If there is nothing selected, add all candidates and remove the ones that the user
7438                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7439                if (result.size() == 0) {
7440                    result.addAll(candidates);
7441                    result.removeAll(neverList);
7442                }
7443            }
7444        }
7445        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7446            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7447                    result.size());
7448            for (ResolveInfo info : result) {
7449                Slog.v(TAG, "  + " + info.activityInfo);
7450            }
7451        }
7452        return result;
7453    }
7454
7455    // Returns a packed value as a long:
7456    //
7457    // high 'int'-sized word: link status: undefined/ask/never/always.
7458    // low 'int'-sized word: relative priority among 'always' results.
7459    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7460        long result = ps.getDomainVerificationStatusForUser(userId);
7461        // if none available, get the master status
7462        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7463            if (ps.getIntentFilterVerificationInfo() != null) {
7464                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7465            }
7466        }
7467        return result;
7468    }
7469
7470    private ResolveInfo querySkipCurrentProfileIntents(
7471            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7472            int flags, int sourceUserId) {
7473        if (matchingFilters != null) {
7474            int size = matchingFilters.size();
7475            for (int i = 0; i < size; i ++) {
7476                CrossProfileIntentFilter filter = matchingFilters.get(i);
7477                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7478                    // Checking if there are activities in the target user that can handle the
7479                    // intent.
7480                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7481                            resolvedType, flags, sourceUserId);
7482                    if (resolveInfo != null) {
7483                        return resolveInfo;
7484                    }
7485                }
7486            }
7487        }
7488        return null;
7489    }
7490
7491    // Return matching ResolveInfo in target user if any.
7492    private ResolveInfo queryCrossProfileIntents(
7493            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7494            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7495        if (matchingFilters != null) {
7496            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7497            // match the same intent. For performance reasons, it is better not to
7498            // run queryIntent twice for the same userId
7499            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7500            int size = matchingFilters.size();
7501            for (int i = 0; i < size; i++) {
7502                CrossProfileIntentFilter filter = matchingFilters.get(i);
7503                int targetUserId = filter.getTargetUserId();
7504                boolean skipCurrentProfile =
7505                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7506                boolean skipCurrentProfileIfNoMatchFound =
7507                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7508                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7509                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7510                    // Checking if there are activities in the target user that can handle the
7511                    // intent.
7512                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7513                            resolvedType, flags, sourceUserId);
7514                    if (resolveInfo != null) return resolveInfo;
7515                    alreadyTriedUserIds.put(targetUserId, true);
7516                }
7517            }
7518        }
7519        return null;
7520    }
7521
7522    /**
7523     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7524     * will forward the intent to the filter's target user.
7525     * Otherwise, returns null.
7526     */
7527    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7528            String resolvedType, int flags, int sourceUserId) {
7529        int targetUserId = filter.getTargetUserId();
7530        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7531                resolvedType, flags, targetUserId);
7532        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7533            // If all the matches in the target profile are suspended, return null.
7534            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7535                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7536                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7537                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7538                            targetUserId);
7539                }
7540            }
7541        }
7542        return null;
7543    }
7544
7545    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7546            int sourceUserId, int targetUserId) {
7547        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7548        long ident = Binder.clearCallingIdentity();
7549        boolean targetIsProfile;
7550        try {
7551            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7552        } finally {
7553            Binder.restoreCallingIdentity(ident);
7554        }
7555        String className;
7556        if (targetIsProfile) {
7557            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7558        } else {
7559            className = FORWARD_INTENT_TO_PARENT;
7560        }
7561        ComponentName forwardingActivityComponentName = new ComponentName(
7562                mAndroidApplication.packageName, className);
7563        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7564                sourceUserId);
7565        if (!targetIsProfile) {
7566            forwardingActivityInfo.showUserIcon = targetUserId;
7567            forwardingResolveInfo.noResourceId = true;
7568        }
7569        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7570        forwardingResolveInfo.priority = 0;
7571        forwardingResolveInfo.preferredOrder = 0;
7572        forwardingResolveInfo.match = 0;
7573        forwardingResolveInfo.isDefault = true;
7574        forwardingResolveInfo.filter = filter;
7575        forwardingResolveInfo.targetUserId = targetUserId;
7576        return forwardingResolveInfo;
7577    }
7578
7579    @Override
7580    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7581            Intent[] specifics, String[] specificTypes, Intent intent,
7582            String resolvedType, int flags, int userId) {
7583        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7584                specificTypes, intent, resolvedType, flags, userId));
7585    }
7586
7587    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7588            Intent[] specifics, String[] specificTypes, Intent intent,
7589            String resolvedType, int flags, int userId) {
7590        if (!sUserManager.exists(userId)) return Collections.emptyList();
7591        final int callingUid = Binder.getCallingUid();
7592        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7593                false /*includeInstantApps*/);
7594        enforceCrossUserPermission(callingUid, userId,
7595                false /*requireFullPermission*/, false /*checkShell*/,
7596                "query intent activity options");
7597        final String resultsAction = intent.getAction();
7598
7599        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7600                | PackageManager.GET_RESOLVED_FILTER, userId);
7601
7602        if (DEBUG_INTENT_MATCHING) {
7603            Log.v(TAG, "Query " + intent + ": " + results);
7604        }
7605
7606        int specificsPos = 0;
7607        int N;
7608
7609        // todo: note that the algorithm used here is O(N^2).  This
7610        // isn't a problem in our current environment, but if we start running
7611        // into situations where we have more than 5 or 10 matches then this
7612        // should probably be changed to something smarter...
7613
7614        // First we go through and resolve each of the specific items
7615        // that were supplied, taking care of removing any corresponding
7616        // duplicate items in the generic resolve list.
7617        if (specifics != null) {
7618            for (int i=0; i<specifics.length; i++) {
7619                final Intent sintent = specifics[i];
7620                if (sintent == null) {
7621                    continue;
7622                }
7623
7624                if (DEBUG_INTENT_MATCHING) {
7625                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7626                }
7627
7628                String action = sintent.getAction();
7629                if (resultsAction != null && resultsAction.equals(action)) {
7630                    // If this action was explicitly requested, then don't
7631                    // remove things that have it.
7632                    action = null;
7633                }
7634
7635                ResolveInfo ri = null;
7636                ActivityInfo ai = null;
7637
7638                ComponentName comp = sintent.getComponent();
7639                if (comp == null) {
7640                    ri = resolveIntent(
7641                        sintent,
7642                        specificTypes != null ? specificTypes[i] : null,
7643                            flags, userId);
7644                    if (ri == null) {
7645                        continue;
7646                    }
7647                    if (ri == mResolveInfo) {
7648                        // ACK!  Must do something better with this.
7649                    }
7650                    ai = ri.activityInfo;
7651                    comp = new ComponentName(ai.applicationInfo.packageName,
7652                            ai.name);
7653                } else {
7654                    ai = getActivityInfo(comp, flags, userId);
7655                    if (ai == null) {
7656                        continue;
7657                    }
7658                }
7659
7660                // Look for any generic query activities that are duplicates
7661                // of this specific one, and remove them from the results.
7662                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7663                N = results.size();
7664                int j;
7665                for (j=specificsPos; j<N; j++) {
7666                    ResolveInfo sri = results.get(j);
7667                    if ((sri.activityInfo.name.equals(comp.getClassName())
7668                            && sri.activityInfo.applicationInfo.packageName.equals(
7669                                    comp.getPackageName()))
7670                        || (action != null && sri.filter.matchAction(action))) {
7671                        results.remove(j);
7672                        if (DEBUG_INTENT_MATCHING) Log.v(
7673                            TAG, "Removing duplicate item from " + j
7674                            + " due to specific " + specificsPos);
7675                        if (ri == null) {
7676                            ri = sri;
7677                        }
7678                        j--;
7679                        N--;
7680                    }
7681                }
7682
7683                // Add this specific item to its proper place.
7684                if (ri == null) {
7685                    ri = new ResolveInfo();
7686                    ri.activityInfo = ai;
7687                }
7688                results.add(specificsPos, ri);
7689                ri.specificIndex = i;
7690                specificsPos++;
7691            }
7692        }
7693
7694        // Now we go through the remaining generic results and remove any
7695        // duplicate actions that are found here.
7696        N = results.size();
7697        for (int i=specificsPos; i<N-1; i++) {
7698            final ResolveInfo rii = results.get(i);
7699            if (rii.filter == null) {
7700                continue;
7701            }
7702
7703            // Iterate over all of the actions of this result's intent
7704            // filter...  typically this should be just one.
7705            final Iterator<String> it = rii.filter.actionsIterator();
7706            if (it == null) {
7707                continue;
7708            }
7709            while (it.hasNext()) {
7710                final String action = it.next();
7711                if (resultsAction != null && resultsAction.equals(action)) {
7712                    // If this action was explicitly requested, then don't
7713                    // remove things that have it.
7714                    continue;
7715                }
7716                for (int j=i+1; j<N; j++) {
7717                    final ResolveInfo rij = results.get(j);
7718                    if (rij.filter != null && rij.filter.hasAction(action)) {
7719                        results.remove(j);
7720                        if (DEBUG_INTENT_MATCHING) Log.v(
7721                            TAG, "Removing duplicate item from " + j
7722                            + " due to action " + action + " at " + i);
7723                        j--;
7724                        N--;
7725                    }
7726                }
7727            }
7728
7729            // If the caller didn't request filter information, drop it now
7730            // so we don't have to marshall/unmarshall it.
7731            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7732                rii.filter = null;
7733            }
7734        }
7735
7736        // Filter out the caller activity if so requested.
7737        if (caller != null) {
7738            N = results.size();
7739            for (int i=0; i<N; i++) {
7740                ActivityInfo ainfo = results.get(i).activityInfo;
7741                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7742                        && caller.getClassName().equals(ainfo.name)) {
7743                    results.remove(i);
7744                    break;
7745                }
7746            }
7747        }
7748
7749        // If the caller didn't request filter information,
7750        // drop them now so we don't have to
7751        // marshall/unmarshall it.
7752        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7753            N = results.size();
7754            for (int i=0; i<N; i++) {
7755                results.get(i).filter = null;
7756            }
7757        }
7758
7759        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7760        return results;
7761    }
7762
7763    @Override
7764    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7765            String resolvedType, int flags, int userId) {
7766        return new ParceledListSlice<>(
7767                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7768    }
7769
7770    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7771            String resolvedType, int flags, int userId) {
7772        if (!sUserManager.exists(userId)) return Collections.emptyList();
7773        final int callingUid = Binder.getCallingUid();
7774        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7775        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7776                false /*includeInstantApps*/);
7777        ComponentName comp = intent.getComponent();
7778        if (comp == null) {
7779            if (intent.getSelector() != null) {
7780                intent = intent.getSelector();
7781                comp = intent.getComponent();
7782            }
7783        }
7784        if (comp != null) {
7785            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7786            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7787            if (ai != null) {
7788                // When specifying an explicit component, we prevent the activity from being
7789                // used when either 1) the calling package is normal and the activity is within
7790                // an instant application or 2) the calling package is ephemeral and the
7791                // activity is not visible to instant applications.
7792                final boolean matchInstantApp =
7793                        (flags & PackageManager.MATCH_INSTANT) != 0;
7794                final boolean matchVisibleToInstantAppOnly =
7795                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7796                final boolean matchExplicitlyVisibleOnly =
7797                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7798                final boolean isCallerInstantApp =
7799                        instantAppPkgName != null;
7800                final boolean isTargetSameInstantApp =
7801                        comp.getPackageName().equals(instantAppPkgName);
7802                final boolean isTargetInstantApp =
7803                        (ai.applicationInfo.privateFlags
7804                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7805                final boolean isTargetVisibleToInstantApp =
7806                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7807                final boolean isTargetExplicitlyVisibleToInstantApp =
7808                        isTargetVisibleToInstantApp
7809                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7810                final boolean isTargetHiddenFromInstantApp =
7811                        !isTargetVisibleToInstantApp
7812                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7813                final boolean blockResolution =
7814                        !isTargetSameInstantApp
7815                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7816                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7817                                        && isTargetHiddenFromInstantApp));
7818                if (!blockResolution) {
7819                    ResolveInfo ri = new ResolveInfo();
7820                    ri.activityInfo = ai;
7821                    list.add(ri);
7822                }
7823            }
7824            return applyPostResolutionFilter(list, instantAppPkgName);
7825        }
7826
7827        // reader
7828        synchronized (mPackages) {
7829            String pkgName = intent.getPackage();
7830            if (pkgName == null) {
7831                final List<ResolveInfo> result =
7832                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7833                return applyPostResolutionFilter(result, instantAppPkgName);
7834            }
7835            final PackageParser.Package pkg = mPackages.get(pkgName);
7836            if (pkg != null) {
7837                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7838                        intent, resolvedType, flags, pkg.receivers, userId);
7839                return applyPostResolutionFilter(result, instantAppPkgName);
7840            }
7841            return Collections.emptyList();
7842        }
7843    }
7844
7845    @Override
7846    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7847        final int callingUid = Binder.getCallingUid();
7848        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7849    }
7850
7851    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7852            int userId, int callingUid) {
7853        if (!sUserManager.exists(userId)) return null;
7854        flags = updateFlagsForResolve(
7855                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7856        List<ResolveInfo> query = queryIntentServicesInternal(
7857                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7858        if (query != null) {
7859            if (query.size() >= 1) {
7860                // If there is more than one service with the same priority,
7861                // just arbitrarily pick the first one.
7862                return query.get(0);
7863            }
7864        }
7865        return null;
7866    }
7867
7868    @Override
7869    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7870            String resolvedType, int flags, int userId) {
7871        final int callingUid = Binder.getCallingUid();
7872        return new ParceledListSlice<>(queryIntentServicesInternal(
7873                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7874    }
7875
7876    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7877            String resolvedType, int flags, int userId, int callingUid,
7878            boolean includeInstantApps) {
7879        if (!sUserManager.exists(userId)) return Collections.emptyList();
7880        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7881        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7882        ComponentName comp = intent.getComponent();
7883        if (comp == null) {
7884            if (intent.getSelector() != null) {
7885                intent = intent.getSelector();
7886                comp = intent.getComponent();
7887            }
7888        }
7889        if (comp != null) {
7890            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7891            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7892            if (si != null) {
7893                // When specifying an explicit component, we prevent the service from being
7894                // used when either 1) the service is in an instant application and the
7895                // caller is not the same instant application or 2) the calling package is
7896                // ephemeral and the activity is not visible to ephemeral applications.
7897                final boolean matchInstantApp =
7898                        (flags & PackageManager.MATCH_INSTANT) != 0;
7899                final boolean matchVisibleToInstantAppOnly =
7900                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7901                final boolean isCallerInstantApp =
7902                        instantAppPkgName != null;
7903                final boolean isTargetSameInstantApp =
7904                        comp.getPackageName().equals(instantAppPkgName);
7905                final boolean isTargetInstantApp =
7906                        (si.applicationInfo.privateFlags
7907                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7908                final boolean isTargetHiddenFromInstantApp =
7909                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7910                final boolean blockResolution =
7911                        !isTargetSameInstantApp
7912                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7913                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7914                                        && isTargetHiddenFromInstantApp));
7915                if (!blockResolution) {
7916                    final ResolveInfo ri = new ResolveInfo();
7917                    ri.serviceInfo = si;
7918                    list.add(ri);
7919                }
7920            }
7921            return list;
7922        }
7923
7924        // reader
7925        synchronized (mPackages) {
7926            String pkgName = intent.getPackage();
7927            if (pkgName == null) {
7928                return applyPostServiceResolutionFilter(
7929                        mServices.queryIntent(intent, resolvedType, flags, userId),
7930                        instantAppPkgName);
7931            }
7932            final PackageParser.Package pkg = mPackages.get(pkgName);
7933            if (pkg != null) {
7934                return applyPostServiceResolutionFilter(
7935                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7936                                userId),
7937                        instantAppPkgName);
7938            }
7939            return Collections.emptyList();
7940        }
7941    }
7942
7943    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7944            String instantAppPkgName) {
7945        // TODO: When adding on-demand split support for non-instant apps, remove this check
7946        // and always apply post filtering
7947        if (instantAppPkgName == null) {
7948            return resolveInfos;
7949        }
7950        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7951            final ResolveInfo info = resolveInfos.get(i);
7952            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7953            // allow services that are defined in the provided package
7954            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7955                if (info.serviceInfo.splitName != null
7956                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7957                                info.serviceInfo.splitName)) {
7958                    // requested service is defined in a split that hasn't been installed yet.
7959                    // add the installer to the resolve list
7960                    if (DEBUG_EPHEMERAL) {
7961                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7962                    }
7963                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7964                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7965                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7966                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
7967                    // make sure this resolver is the default
7968                    installerInfo.isDefault = true;
7969                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7970                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7971                    // add a non-generic filter
7972                    installerInfo.filter = new IntentFilter();
7973                    // load resources from the correct package
7974                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7975                    resolveInfos.set(i, installerInfo);
7976                }
7977                continue;
7978            }
7979            // allow services that have been explicitly exposed to ephemeral apps
7980            if (!isEphemeralApp
7981                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7982                continue;
7983            }
7984            resolveInfos.remove(i);
7985        }
7986        return resolveInfos;
7987    }
7988
7989    @Override
7990    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7991            String resolvedType, int flags, int userId) {
7992        return new ParceledListSlice<>(
7993                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7994    }
7995
7996    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7997            Intent intent, String resolvedType, int flags, int userId) {
7998        if (!sUserManager.exists(userId)) return Collections.emptyList();
7999        final int callingUid = Binder.getCallingUid();
8000        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8001        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8002                false /*includeInstantApps*/);
8003        ComponentName comp = intent.getComponent();
8004        if (comp == null) {
8005            if (intent.getSelector() != null) {
8006                intent = intent.getSelector();
8007                comp = intent.getComponent();
8008            }
8009        }
8010        if (comp != null) {
8011            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8012            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8013            if (pi != null) {
8014                // When specifying an explicit component, we prevent the provider from being
8015                // used when either 1) the provider is in an instant application and the
8016                // caller is not the same instant application or 2) the calling package is an
8017                // instant application and the provider is not visible to instant applications.
8018                final boolean matchInstantApp =
8019                        (flags & PackageManager.MATCH_INSTANT) != 0;
8020                final boolean matchVisibleToInstantAppOnly =
8021                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8022                final boolean isCallerInstantApp =
8023                        instantAppPkgName != null;
8024                final boolean isTargetSameInstantApp =
8025                        comp.getPackageName().equals(instantAppPkgName);
8026                final boolean isTargetInstantApp =
8027                        (pi.applicationInfo.privateFlags
8028                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8029                final boolean isTargetHiddenFromInstantApp =
8030                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8031                final boolean blockResolution =
8032                        !isTargetSameInstantApp
8033                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8034                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8035                                        && isTargetHiddenFromInstantApp));
8036                if (!blockResolution) {
8037                    final ResolveInfo ri = new ResolveInfo();
8038                    ri.providerInfo = pi;
8039                    list.add(ri);
8040                }
8041            }
8042            return list;
8043        }
8044
8045        // reader
8046        synchronized (mPackages) {
8047            String pkgName = intent.getPackage();
8048            if (pkgName == null) {
8049                return applyPostContentProviderResolutionFilter(
8050                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8051                        instantAppPkgName);
8052            }
8053            final PackageParser.Package pkg = mPackages.get(pkgName);
8054            if (pkg != null) {
8055                return applyPostContentProviderResolutionFilter(
8056                        mProviders.queryIntentForPackage(
8057                        intent, resolvedType, flags, pkg.providers, userId),
8058                        instantAppPkgName);
8059            }
8060            return Collections.emptyList();
8061        }
8062    }
8063
8064    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8065            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8066        // TODO: When adding on-demand split support for non-instant applications, remove
8067        // this check and always apply post filtering
8068        if (instantAppPkgName == null) {
8069            return resolveInfos;
8070        }
8071        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8072            final ResolveInfo info = resolveInfos.get(i);
8073            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8074            // allow providers that are defined in the provided package
8075            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8076                if (info.providerInfo.splitName != null
8077                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8078                                info.providerInfo.splitName)) {
8079                    // requested provider is defined in a split that hasn't been installed yet.
8080                    // add the installer to the resolve list
8081                    if (DEBUG_EPHEMERAL) {
8082                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8083                    }
8084                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8085                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8086                            info.providerInfo.packageName, info.providerInfo.splitName,
8087                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
8088                    // make sure this resolver is the default
8089                    installerInfo.isDefault = true;
8090                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8091                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8092                    // add a non-generic filter
8093                    installerInfo.filter = new IntentFilter();
8094                    // load resources from the correct package
8095                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8096                    resolveInfos.set(i, installerInfo);
8097                }
8098                continue;
8099            }
8100            // allow providers that have been explicitly exposed to instant applications
8101            if (!isEphemeralApp
8102                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8103                continue;
8104            }
8105            resolveInfos.remove(i);
8106        }
8107        return resolveInfos;
8108    }
8109
8110    @Override
8111    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8112        final int callingUid = Binder.getCallingUid();
8113        if (getInstantAppPackageName(callingUid) != null) {
8114            return ParceledListSlice.emptyList();
8115        }
8116        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8117        flags = updateFlagsForPackage(flags, userId, null);
8118        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8119        enforceCrossUserPermission(callingUid, userId,
8120                true /* requireFullPermission */, false /* checkShell */,
8121                "get installed packages");
8122
8123        // writer
8124        synchronized (mPackages) {
8125            ArrayList<PackageInfo> list;
8126            if (listUninstalled) {
8127                list = new ArrayList<>(mSettings.mPackages.size());
8128                for (PackageSetting ps : mSettings.mPackages.values()) {
8129                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8130                        continue;
8131                    }
8132                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8133                        return null;
8134                    }
8135                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8136                    if (pi != null) {
8137                        list.add(pi);
8138                    }
8139                }
8140            } else {
8141                list = new ArrayList<>(mPackages.size());
8142                for (PackageParser.Package p : mPackages.values()) {
8143                    final PackageSetting ps = (PackageSetting) p.mExtras;
8144                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8145                        continue;
8146                    }
8147                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8148                        return null;
8149                    }
8150                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8151                            p.mExtras, flags, userId);
8152                    if (pi != null) {
8153                        list.add(pi);
8154                    }
8155                }
8156            }
8157
8158            return new ParceledListSlice<>(list);
8159        }
8160    }
8161
8162    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8163            String[] permissions, boolean[] tmp, int flags, int userId) {
8164        int numMatch = 0;
8165        final PermissionsState permissionsState = ps.getPermissionsState();
8166        for (int i=0; i<permissions.length; i++) {
8167            final String permission = permissions[i];
8168            if (permissionsState.hasPermission(permission, userId)) {
8169                tmp[i] = true;
8170                numMatch++;
8171            } else {
8172                tmp[i] = false;
8173            }
8174        }
8175        if (numMatch == 0) {
8176            return;
8177        }
8178        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8179
8180        // The above might return null in cases of uninstalled apps or install-state
8181        // skew across users/profiles.
8182        if (pi != null) {
8183            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8184                if (numMatch == permissions.length) {
8185                    pi.requestedPermissions = permissions;
8186                } else {
8187                    pi.requestedPermissions = new String[numMatch];
8188                    numMatch = 0;
8189                    for (int i=0; i<permissions.length; i++) {
8190                        if (tmp[i]) {
8191                            pi.requestedPermissions[numMatch] = permissions[i];
8192                            numMatch++;
8193                        }
8194                    }
8195                }
8196            }
8197            list.add(pi);
8198        }
8199    }
8200
8201    @Override
8202    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8203            String[] permissions, int flags, int userId) {
8204        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8205        flags = updateFlagsForPackage(flags, userId, permissions);
8206        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8207                true /* requireFullPermission */, false /* checkShell */,
8208                "get packages holding permissions");
8209        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8210
8211        // writer
8212        synchronized (mPackages) {
8213            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8214            boolean[] tmpBools = new boolean[permissions.length];
8215            if (listUninstalled) {
8216                for (PackageSetting ps : mSettings.mPackages.values()) {
8217                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8218                            userId);
8219                }
8220            } else {
8221                for (PackageParser.Package pkg : mPackages.values()) {
8222                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8223                    if (ps != null) {
8224                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8225                                userId);
8226                    }
8227                }
8228            }
8229
8230            return new ParceledListSlice<PackageInfo>(list);
8231        }
8232    }
8233
8234    @Override
8235    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8236        final int callingUid = Binder.getCallingUid();
8237        if (getInstantAppPackageName(callingUid) != null) {
8238            return ParceledListSlice.emptyList();
8239        }
8240        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8241        flags = updateFlagsForApplication(flags, userId, null);
8242        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8243
8244        // writer
8245        synchronized (mPackages) {
8246            ArrayList<ApplicationInfo> list;
8247            if (listUninstalled) {
8248                list = new ArrayList<>(mSettings.mPackages.size());
8249                for (PackageSetting ps : mSettings.mPackages.values()) {
8250                    ApplicationInfo ai;
8251                    int effectiveFlags = flags;
8252                    if (ps.isSystem()) {
8253                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8254                    }
8255                    if (ps.pkg != null) {
8256                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8257                            continue;
8258                        }
8259                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8260                            return null;
8261                        }
8262                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8263                                ps.readUserState(userId), userId);
8264                        if (ai != null) {
8265                            rebaseEnabledOverlays(ai, userId);
8266                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8267                        }
8268                    } else {
8269                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8270                        // and already converts to externally visible package name
8271                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8272                                callingUid, effectiveFlags, userId);
8273                    }
8274                    if (ai != null) {
8275                        list.add(ai);
8276                    }
8277                }
8278            } else {
8279                list = new ArrayList<>(mPackages.size());
8280                for (PackageParser.Package p : mPackages.values()) {
8281                    if (p.mExtras != null) {
8282                        PackageSetting ps = (PackageSetting) p.mExtras;
8283                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8284                            continue;
8285                        }
8286                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8287                            return null;
8288                        }
8289                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8290                                ps.readUserState(userId), userId);
8291                        if (ai != null) {
8292                            rebaseEnabledOverlays(ai, userId);
8293                            ai.packageName = resolveExternalPackageNameLPr(p);
8294                            list.add(ai);
8295                        }
8296                    }
8297                }
8298            }
8299
8300            return new ParceledListSlice<>(list);
8301        }
8302    }
8303
8304    @Override
8305    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8306        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8307            return null;
8308        }
8309        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8310                "getEphemeralApplications");
8311        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8312                true /* requireFullPermission */, false /* checkShell */,
8313                "getEphemeralApplications");
8314        synchronized (mPackages) {
8315            List<InstantAppInfo> instantApps = mInstantAppRegistry
8316                    .getInstantAppsLPr(userId);
8317            if (instantApps != null) {
8318                return new ParceledListSlice<>(instantApps);
8319            }
8320        }
8321        return null;
8322    }
8323
8324    @Override
8325    public boolean isInstantApp(String packageName, int userId) {
8326        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8327                true /* requireFullPermission */, false /* checkShell */,
8328                "isInstantApp");
8329        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8330            return false;
8331        }
8332        int callingUid = Binder.getCallingUid();
8333        if (Process.isIsolated(callingUid)) {
8334            callingUid = mIsolatedOwners.get(callingUid);
8335        }
8336
8337        synchronized (mPackages) {
8338            final PackageSetting ps = mSettings.mPackages.get(packageName);
8339            PackageParser.Package pkg = mPackages.get(packageName);
8340            final boolean returnAllowed =
8341                    ps != null
8342                    && (isCallerSameApp(packageName, callingUid)
8343                            || canViewInstantApps(callingUid, userId)
8344                            || mInstantAppRegistry.isInstantAccessGranted(
8345                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8346            if (returnAllowed) {
8347                return ps.getInstantApp(userId);
8348            }
8349        }
8350        return false;
8351    }
8352
8353    @Override
8354    public byte[] getInstantAppCookie(String packageName, int userId) {
8355        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8356            return null;
8357        }
8358
8359        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8360                true /* requireFullPermission */, false /* checkShell */,
8361                "getInstantAppCookie");
8362        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8363            return null;
8364        }
8365        synchronized (mPackages) {
8366            return mInstantAppRegistry.getInstantAppCookieLPw(
8367                    packageName, userId);
8368        }
8369    }
8370
8371    @Override
8372    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8373        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8374            return true;
8375        }
8376
8377        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8378                true /* requireFullPermission */, true /* checkShell */,
8379                "setInstantAppCookie");
8380        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8381            return false;
8382        }
8383        synchronized (mPackages) {
8384            return mInstantAppRegistry.setInstantAppCookieLPw(
8385                    packageName, cookie, userId);
8386        }
8387    }
8388
8389    @Override
8390    public Bitmap getInstantAppIcon(String packageName, int userId) {
8391        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8392            return null;
8393        }
8394
8395        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8396                "getInstantAppIcon");
8397
8398        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8399                true /* requireFullPermission */, false /* checkShell */,
8400                "getInstantAppIcon");
8401
8402        synchronized (mPackages) {
8403            return mInstantAppRegistry.getInstantAppIconLPw(
8404                    packageName, userId);
8405        }
8406    }
8407
8408    private boolean isCallerSameApp(String packageName, int uid) {
8409        PackageParser.Package pkg = mPackages.get(packageName);
8410        return pkg != null
8411                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8412    }
8413
8414    @Override
8415    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8416        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8417            return ParceledListSlice.emptyList();
8418        }
8419        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8420    }
8421
8422    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8423        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8424
8425        // reader
8426        synchronized (mPackages) {
8427            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8428            final int userId = UserHandle.getCallingUserId();
8429            while (i.hasNext()) {
8430                final PackageParser.Package p = i.next();
8431                if (p.applicationInfo == null) continue;
8432
8433                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8434                        && !p.applicationInfo.isDirectBootAware();
8435                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8436                        && p.applicationInfo.isDirectBootAware();
8437
8438                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8439                        && (!mSafeMode || isSystemApp(p))
8440                        && (matchesUnaware || matchesAware)) {
8441                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8442                    if (ps != null) {
8443                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8444                                ps.readUserState(userId), userId);
8445                        if (ai != null) {
8446                            rebaseEnabledOverlays(ai, userId);
8447                            finalList.add(ai);
8448                        }
8449                    }
8450                }
8451            }
8452        }
8453
8454        return finalList;
8455    }
8456
8457    @Override
8458    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8459        if (!sUserManager.exists(userId)) return null;
8460        flags = updateFlagsForComponent(flags, userId, name);
8461        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8462        // reader
8463        synchronized (mPackages) {
8464            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8465            PackageSetting ps = provider != null
8466                    ? mSettings.mPackages.get(provider.owner.packageName)
8467                    : null;
8468            if (ps != null) {
8469                final boolean isInstantApp = ps.getInstantApp(userId);
8470                // normal application; filter out instant application provider
8471                if (instantAppPkgName == null && isInstantApp) {
8472                    return null;
8473                }
8474                // instant application; filter out other instant applications
8475                if (instantAppPkgName != null
8476                        && isInstantApp
8477                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8478                    return null;
8479                }
8480                // instant application; filter out non-exposed provider
8481                if (instantAppPkgName != null
8482                        && !isInstantApp
8483                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8484                    return null;
8485                }
8486                // provider not enabled
8487                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8488                    return null;
8489                }
8490                return PackageParser.generateProviderInfo(
8491                        provider, flags, ps.readUserState(userId), userId);
8492            }
8493            return null;
8494        }
8495    }
8496
8497    /**
8498     * @deprecated
8499     */
8500    @Deprecated
8501    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8502        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8503            return;
8504        }
8505        // reader
8506        synchronized (mPackages) {
8507            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8508                    .entrySet().iterator();
8509            final int userId = UserHandle.getCallingUserId();
8510            while (i.hasNext()) {
8511                Map.Entry<String, PackageParser.Provider> entry = i.next();
8512                PackageParser.Provider p = entry.getValue();
8513                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8514
8515                if (ps != null && p.syncable
8516                        && (!mSafeMode || (p.info.applicationInfo.flags
8517                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8518                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8519                            ps.readUserState(userId), userId);
8520                    if (info != null) {
8521                        outNames.add(entry.getKey());
8522                        outInfo.add(info);
8523                    }
8524                }
8525            }
8526        }
8527    }
8528
8529    @Override
8530    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8531            int uid, int flags, String metaDataKey) {
8532        final int callingUid = Binder.getCallingUid();
8533        final int userId = processName != null ? UserHandle.getUserId(uid)
8534                : UserHandle.getCallingUserId();
8535        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8536        flags = updateFlagsForComponent(flags, userId, processName);
8537        ArrayList<ProviderInfo> finalList = null;
8538        // reader
8539        synchronized (mPackages) {
8540            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8541            while (i.hasNext()) {
8542                final PackageParser.Provider p = i.next();
8543                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8544                if (ps != null && p.info.authority != null
8545                        && (processName == null
8546                                || (p.info.processName.equals(processName)
8547                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8548                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8549
8550                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8551                    // parameter.
8552                    if (metaDataKey != null
8553                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8554                        continue;
8555                    }
8556                    final ComponentName component =
8557                            new ComponentName(p.info.packageName, p.info.name);
8558                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8559                        continue;
8560                    }
8561                    if (finalList == null) {
8562                        finalList = new ArrayList<ProviderInfo>(3);
8563                    }
8564                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8565                            ps.readUserState(userId), userId);
8566                    if (info != null) {
8567                        finalList.add(info);
8568                    }
8569                }
8570            }
8571        }
8572
8573        if (finalList != null) {
8574            Collections.sort(finalList, mProviderInitOrderSorter);
8575            return new ParceledListSlice<ProviderInfo>(finalList);
8576        }
8577
8578        return ParceledListSlice.emptyList();
8579    }
8580
8581    @Override
8582    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8583        // reader
8584        synchronized (mPackages) {
8585            final int callingUid = Binder.getCallingUid();
8586            final int callingUserId = UserHandle.getUserId(callingUid);
8587            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8588            if (ps == null) return null;
8589            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8590                return null;
8591            }
8592            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8593            return PackageParser.generateInstrumentationInfo(i, flags);
8594        }
8595    }
8596
8597    @Override
8598    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8599            String targetPackage, int flags) {
8600        final int callingUid = Binder.getCallingUid();
8601        final int callingUserId = UserHandle.getUserId(callingUid);
8602        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8603        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8604            return ParceledListSlice.emptyList();
8605        }
8606        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8607    }
8608
8609    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8610            int flags) {
8611        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8612
8613        // reader
8614        synchronized (mPackages) {
8615            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8616            while (i.hasNext()) {
8617                final PackageParser.Instrumentation p = i.next();
8618                if (targetPackage == null
8619                        || targetPackage.equals(p.info.targetPackage)) {
8620                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8621                            flags);
8622                    if (ii != null) {
8623                        finalList.add(ii);
8624                    }
8625                }
8626            }
8627        }
8628
8629        return finalList;
8630    }
8631
8632    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8633        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8634        try {
8635            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8636        } finally {
8637            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8638        }
8639    }
8640
8641    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8642        final File[] files = dir.listFiles();
8643        if (ArrayUtils.isEmpty(files)) {
8644            Log.d(TAG, "No files in app dir " + dir);
8645            return;
8646        }
8647
8648        if (DEBUG_PACKAGE_SCANNING) {
8649            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8650                    + " flags=0x" + Integer.toHexString(parseFlags));
8651        }
8652        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8653                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8654                mParallelPackageParserCallback);
8655
8656        // Submit files for parsing in parallel
8657        int fileCount = 0;
8658        for (File file : files) {
8659            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8660                    && !PackageInstallerService.isStageName(file.getName());
8661            if (!isPackage) {
8662                // Ignore entries which are not packages
8663                continue;
8664            }
8665            parallelPackageParser.submit(file, parseFlags);
8666            fileCount++;
8667        }
8668
8669        // Process results one by one
8670        for (; fileCount > 0; fileCount--) {
8671            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8672            Throwable throwable = parseResult.throwable;
8673            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8674
8675            if (throwable == null) {
8676                // Static shared libraries have synthetic package names
8677                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8678                    renameStaticSharedLibraryPackage(parseResult.pkg);
8679                }
8680                try {
8681                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8682                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8683                                currentTime, null);
8684                    }
8685                } catch (PackageManagerException e) {
8686                    errorCode = e.error;
8687                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8688                }
8689            } else if (throwable instanceof PackageParser.PackageParserException) {
8690                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8691                        throwable;
8692                errorCode = e.error;
8693                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8694            } else {
8695                throw new IllegalStateException("Unexpected exception occurred while parsing "
8696                        + parseResult.scanFile, throwable);
8697            }
8698
8699            // Delete invalid userdata apps
8700            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8701                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8702                logCriticalInfo(Log.WARN,
8703                        "Deleting invalid package at " + parseResult.scanFile);
8704                removeCodePathLI(parseResult.scanFile);
8705            }
8706        }
8707        parallelPackageParser.close();
8708    }
8709
8710    private static File getSettingsProblemFile() {
8711        File dataDir = Environment.getDataDirectory();
8712        File systemDir = new File(dataDir, "system");
8713        File fname = new File(systemDir, "uiderrors.txt");
8714        return fname;
8715    }
8716
8717    static void reportSettingsProblem(int priority, String msg) {
8718        logCriticalInfo(priority, msg);
8719    }
8720
8721    public static void logCriticalInfo(int priority, String msg) {
8722        Slog.println(priority, TAG, msg);
8723        EventLogTags.writePmCriticalInfo(msg);
8724        try {
8725            File fname = getSettingsProblemFile();
8726            FileOutputStream out = new FileOutputStream(fname, true);
8727            PrintWriter pw = new FastPrintWriter(out);
8728            SimpleDateFormat formatter = new SimpleDateFormat();
8729            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8730            pw.println(dateString + ": " + msg);
8731            pw.close();
8732            FileUtils.setPermissions(
8733                    fname.toString(),
8734                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8735                    -1, -1);
8736        } catch (java.io.IOException e) {
8737        }
8738    }
8739
8740    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8741        if (srcFile.isDirectory()) {
8742            final File baseFile = new File(pkg.baseCodePath);
8743            long maxModifiedTime = baseFile.lastModified();
8744            if (pkg.splitCodePaths != null) {
8745                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8746                    final File splitFile = new File(pkg.splitCodePaths[i]);
8747                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8748                }
8749            }
8750            return maxModifiedTime;
8751        }
8752        return srcFile.lastModified();
8753    }
8754
8755    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8756            final int policyFlags) throws PackageManagerException {
8757        // When upgrading from pre-N MR1, verify the package time stamp using the package
8758        // directory and not the APK file.
8759        final long lastModifiedTime = mIsPreNMR1Upgrade
8760                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8761        if (ps != null
8762                && ps.codePath.equals(srcFile)
8763                && ps.timeStamp == lastModifiedTime
8764                && !isCompatSignatureUpdateNeeded(pkg)
8765                && !isRecoverSignatureUpdateNeeded(pkg)) {
8766            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8767            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8768            ArraySet<PublicKey> signingKs;
8769            synchronized (mPackages) {
8770                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8771            }
8772            if (ps.signatures.mSignatures != null
8773                    && ps.signatures.mSignatures.length != 0
8774                    && signingKs != null) {
8775                // Optimization: reuse the existing cached certificates
8776                // if the package appears to be unchanged.
8777                pkg.mSignatures = ps.signatures.mSignatures;
8778                pkg.mSigningKeys = signingKs;
8779                return;
8780            }
8781
8782            Slog.w(TAG, "PackageSetting for " + ps.name
8783                    + " is missing signatures.  Collecting certs again to recover them.");
8784        } else {
8785            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8786        }
8787
8788        try {
8789            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8790            PackageParser.collectCertificates(pkg, policyFlags);
8791        } catch (PackageParserException e) {
8792            throw PackageManagerException.from(e);
8793        } finally {
8794            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8795        }
8796    }
8797
8798    /**
8799     *  Traces a package scan.
8800     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8801     */
8802    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8803            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8804        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8805        try {
8806            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8807        } finally {
8808            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8809        }
8810    }
8811
8812    /**
8813     *  Scans a package and returns the newly parsed package.
8814     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8815     */
8816    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8817            long currentTime, UserHandle user) throws PackageManagerException {
8818        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8819        PackageParser pp = new PackageParser();
8820        pp.setSeparateProcesses(mSeparateProcesses);
8821        pp.setOnlyCoreApps(mOnlyCore);
8822        pp.setDisplayMetrics(mMetrics);
8823        pp.setCallback(mPackageParserCallback);
8824
8825        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8826            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8827        }
8828
8829        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8830        final PackageParser.Package pkg;
8831        try {
8832            pkg = pp.parsePackage(scanFile, parseFlags);
8833        } catch (PackageParserException e) {
8834            throw PackageManagerException.from(e);
8835        } finally {
8836            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8837        }
8838
8839        // Static shared libraries have synthetic package names
8840        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8841            renameStaticSharedLibraryPackage(pkg);
8842        }
8843
8844        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8845    }
8846
8847    /**
8848     *  Scans a package and returns the newly parsed package.
8849     *  @throws PackageManagerException on a parse error.
8850     */
8851    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8852            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8853            throws PackageManagerException {
8854        // If the package has children and this is the first dive in the function
8855        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8856        // packages (parent and children) would be successfully scanned before the
8857        // actual scan since scanning mutates internal state and we want to atomically
8858        // install the package and its children.
8859        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8860            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8861                scanFlags |= SCAN_CHECK_ONLY;
8862            }
8863        } else {
8864            scanFlags &= ~SCAN_CHECK_ONLY;
8865        }
8866
8867        // Scan the parent
8868        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8869                scanFlags, currentTime, user);
8870
8871        // Scan the children
8872        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8873        for (int i = 0; i < childCount; i++) {
8874            PackageParser.Package childPackage = pkg.childPackages.get(i);
8875            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8876                    currentTime, user);
8877        }
8878
8879
8880        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8881            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8882        }
8883
8884        return scannedPkg;
8885    }
8886
8887    /**
8888     *  Scans a package and returns the newly parsed package.
8889     *  @throws PackageManagerException on a parse error.
8890     */
8891    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8892            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8893            throws PackageManagerException {
8894        PackageSetting ps = null;
8895        PackageSetting updatedPkg;
8896        // reader
8897        synchronized (mPackages) {
8898            // Look to see if we already know about this package.
8899            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8900            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8901                // This package has been renamed to its original name.  Let's
8902                // use that.
8903                ps = mSettings.getPackageLPr(oldName);
8904            }
8905            // If there was no original package, see one for the real package name.
8906            if (ps == null) {
8907                ps = mSettings.getPackageLPr(pkg.packageName);
8908            }
8909            // Check to see if this package could be hiding/updating a system
8910            // package.  Must look for it either under the original or real
8911            // package name depending on our state.
8912            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8913            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8914
8915            // If this is a package we don't know about on the system partition, we
8916            // may need to remove disabled child packages on the system partition
8917            // or may need to not add child packages if the parent apk is updated
8918            // on the data partition and no longer defines this child package.
8919            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8920                // If this is a parent package for an updated system app and this system
8921                // app got an OTA update which no longer defines some of the child packages
8922                // we have to prune them from the disabled system packages.
8923                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8924                if (disabledPs != null) {
8925                    final int scannedChildCount = (pkg.childPackages != null)
8926                            ? pkg.childPackages.size() : 0;
8927                    final int disabledChildCount = disabledPs.childPackageNames != null
8928                            ? disabledPs.childPackageNames.size() : 0;
8929                    for (int i = 0; i < disabledChildCount; i++) {
8930                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8931                        boolean disabledPackageAvailable = false;
8932                        for (int j = 0; j < scannedChildCount; j++) {
8933                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8934                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8935                                disabledPackageAvailable = true;
8936                                break;
8937                            }
8938                         }
8939                         if (!disabledPackageAvailable) {
8940                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8941                         }
8942                    }
8943                }
8944            }
8945        }
8946
8947        boolean updatedPkgBetter = false;
8948        // First check if this is a system package that may involve an update
8949        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8950            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8951            // it needs to drop FLAG_PRIVILEGED.
8952            if (locationIsPrivileged(scanFile)) {
8953                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8954            } else {
8955                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8956            }
8957
8958            if (ps != null && !ps.codePath.equals(scanFile)) {
8959                // The path has changed from what was last scanned...  check the
8960                // version of the new path against what we have stored to determine
8961                // what to do.
8962                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8963                if (pkg.mVersionCode <= ps.versionCode) {
8964                    // The system package has been updated and the code path does not match
8965                    // Ignore entry. Skip it.
8966                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8967                            + " ignored: updated version " + ps.versionCode
8968                            + " better than this " + pkg.mVersionCode);
8969                    if (!updatedPkg.codePath.equals(scanFile)) {
8970                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8971                                + ps.name + " changing from " + updatedPkg.codePathString
8972                                + " to " + scanFile);
8973                        updatedPkg.codePath = scanFile;
8974                        updatedPkg.codePathString = scanFile.toString();
8975                        updatedPkg.resourcePath = scanFile;
8976                        updatedPkg.resourcePathString = scanFile.toString();
8977                    }
8978                    updatedPkg.pkg = pkg;
8979                    updatedPkg.versionCode = pkg.mVersionCode;
8980
8981                    // Update the disabled system child packages to point to the package too.
8982                    final int childCount = updatedPkg.childPackageNames != null
8983                            ? updatedPkg.childPackageNames.size() : 0;
8984                    for (int i = 0; i < childCount; i++) {
8985                        String childPackageName = updatedPkg.childPackageNames.get(i);
8986                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8987                                childPackageName);
8988                        if (updatedChildPkg != null) {
8989                            updatedChildPkg.pkg = pkg;
8990                            updatedChildPkg.versionCode = pkg.mVersionCode;
8991                        }
8992                    }
8993
8994                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8995                            + scanFile + " ignored: updated version " + ps.versionCode
8996                            + " better than this " + pkg.mVersionCode);
8997                } else {
8998                    // The current app on the system partition is better than
8999                    // what we have updated to on the data partition; switch
9000                    // back to the system partition version.
9001                    // At this point, its safely assumed that package installation for
9002                    // apps in system partition will go through. If not there won't be a working
9003                    // version of the app
9004                    // writer
9005                    synchronized (mPackages) {
9006                        // Just remove the loaded entries from package lists.
9007                        mPackages.remove(ps.name);
9008                    }
9009
9010                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9011                            + " reverting from " + ps.codePathString
9012                            + ": new version " + pkg.mVersionCode
9013                            + " better than installed " + ps.versionCode);
9014
9015                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9016                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9017                    synchronized (mInstallLock) {
9018                        args.cleanUpResourcesLI();
9019                    }
9020                    synchronized (mPackages) {
9021                        mSettings.enableSystemPackageLPw(ps.name);
9022                    }
9023                    updatedPkgBetter = true;
9024                }
9025            }
9026        }
9027
9028        if (updatedPkg != null) {
9029            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9030            // initially
9031            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9032
9033            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9034            // flag set initially
9035            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9036                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9037            }
9038        }
9039
9040        // Verify certificates against what was last scanned
9041        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9042
9043        /*
9044         * A new system app appeared, but we already had a non-system one of the
9045         * same name installed earlier.
9046         */
9047        boolean shouldHideSystemApp = false;
9048        if (updatedPkg == null && ps != null
9049                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9050            /*
9051             * Check to make sure the signatures match first. If they don't,
9052             * wipe the installed application and its data.
9053             */
9054            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9055                    != PackageManager.SIGNATURE_MATCH) {
9056                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9057                        + " signatures don't match existing userdata copy; removing");
9058                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9059                        "scanPackageInternalLI")) {
9060                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9061                }
9062                ps = null;
9063            } else {
9064                /*
9065                 * If the newly-added system app is an older version than the
9066                 * already installed version, hide it. It will be scanned later
9067                 * and re-added like an update.
9068                 */
9069                if (pkg.mVersionCode <= ps.versionCode) {
9070                    shouldHideSystemApp = true;
9071                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9072                            + " but new version " + pkg.mVersionCode + " better than installed "
9073                            + ps.versionCode + "; hiding system");
9074                } else {
9075                    /*
9076                     * The newly found system app is a newer version that the
9077                     * one previously installed. Simply remove the
9078                     * already-installed application and replace it with our own
9079                     * while keeping the application data.
9080                     */
9081                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9082                            + " reverting from " + ps.codePathString + ": new version "
9083                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9084                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9085                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9086                    synchronized (mInstallLock) {
9087                        args.cleanUpResourcesLI();
9088                    }
9089                }
9090            }
9091        }
9092
9093        // The apk is forward locked (not public) if its code and resources
9094        // are kept in different files. (except for app in either system or
9095        // vendor path).
9096        // TODO grab this value from PackageSettings
9097        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9098            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9099                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9100            }
9101        }
9102
9103        // TODO: extend to support forward-locked splits
9104        String resourcePath = null;
9105        String baseResourcePath = null;
9106        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
9107            if (ps != null && ps.resourcePathString != null) {
9108                resourcePath = ps.resourcePathString;
9109                baseResourcePath = ps.resourcePathString;
9110            } else {
9111                // Should not happen at all. Just log an error.
9112                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9113            }
9114        } else {
9115            resourcePath = pkg.codePath;
9116            baseResourcePath = pkg.baseCodePath;
9117        }
9118
9119        // Set application objects path explicitly.
9120        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9121        pkg.setApplicationInfoCodePath(pkg.codePath);
9122        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9123        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9124        pkg.setApplicationInfoResourcePath(resourcePath);
9125        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9126        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9127
9128        final int userId = ((user == null) ? 0 : user.getIdentifier());
9129        if (ps != null && ps.getInstantApp(userId)) {
9130            scanFlags |= SCAN_AS_INSTANT_APP;
9131        }
9132
9133        // Note that we invoke the following method only if we are about to unpack an application
9134        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9135                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9136
9137        /*
9138         * If the system app should be overridden by a previously installed
9139         * data, hide the system app now and let the /data/app scan pick it up
9140         * again.
9141         */
9142        if (shouldHideSystemApp) {
9143            synchronized (mPackages) {
9144                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9145            }
9146        }
9147
9148        return scannedPkg;
9149    }
9150
9151    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9152        // Derive the new package synthetic package name
9153        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9154                + pkg.staticSharedLibVersion);
9155    }
9156
9157    private static String fixProcessName(String defProcessName,
9158            String processName) {
9159        if (processName == null) {
9160            return defProcessName;
9161        }
9162        return processName;
9163    }
9164
9165    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9166            throws PackageManagerException {
9167        if (pkgSetting.signatures.mSignatures != null) {
9168            // Already existing package. Make sure signatures match
9169            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9170                    == PackageManager.SIGNATURE_MATCH;
9171            if (!match) {
9172                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9173                        == PackageManager.SIGNATURE_MATCH;
9174            }
9175            if (!match) {
9176                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9177                        == PackageManager.SIGNATURE_MATCH;
9178            }
9179            if (!match) {
9180                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9181                        + pkg.packageName + " signatures do not match the "
9182                        + "previously installed version; ignoring!");
9183            }
9184        }
9185
9186        // Check for shared user signatures
9187        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9188            // Already existing package. Make sure signatures match
9189            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9190                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9191            if (!match) {
9192                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9193                        == PackageManager.SIGNATURE_MATCH;
9194            }
9195            if (!match) {
9196                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9197                        == PackageManager.SIGNATURE_MATCH;
9198            }
9199            if (!match) {
9200                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9201                        "Package " + pkg.packageName
9202                        + " has no signatures that match those in shared user "
9203                        + pkgSetting.sharedUser.name + "; ignoring!");
9204            }
9205        }
9206    }
9207
9208    /**
9209     * Enforces that only the system UID or root's UID can call a method exposed
9210     * via Binder.
9211     *
9212     * @param message used as message if SecurityException is thrown
9213     * @throws SecurityException if the caller is not system or root
9214     */
9215    private static final void enforceSystemOrRoot(String message) {
9216        final int uid = Binder.getCallingUid();
9217        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9218            throw new SecurityException(message);
9219        }
9220    }
9221
9222    @Override
9223    public void performFstrimIfNeeded() {
9224        enforceSystemOrRoot("Only the system can request fstrim");
9225
9226        // Before everything else, see whether we need to fstrim.
9227        try {
9228            IStorageManager sm = PackageHelper.getStorageManager();
9229            if (sm != null) {
9230                boolean doTrim = false;
9231                final long interval = android.provider.Settings.Global.getLong(
9232                        mContext.getContentResolver(),
9233                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9234                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9235                if (interval > 0) {
9236                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9237                    if (timeSinceLast > interval) {
9238                        doTrim = true;
9239                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9240                                + "; running immediately");
9241                    }
9242                }
9243                if (doTrim) {
9244                    final boolean dexOptDialogShown;
9245                    synchronized (mPackages) {
9246                        dexOptDialogShown = mDexOptDialogShown;
9247                    }
9248                    if (!isFirstBoot() && dexOptDialogShown) {
9249                        try {
9250                            ActivityManager.getService().showBootMessage(
9251                                    mContext.getResources().getString(
9252                                            R.string.android_upgrading_fstrim), true);
9253                        } catch (RemoteException e) {
9254                        }
9255                    }
9256                    sm.runMaintenance();
9257                }
9258            } else {
9259                Slog.e(TAG, "storageManager service unavailable!");
9260            }
9261        } catch (RemoteException e) {
9262            // Can't happen; StorageManagerService is local
9263        }
9264    }
9265
9266    @Override
9267    public void updatePackagesIfNeeded() {
9268        enforceSystemOrRoot("Only the system can request package update");
9269
9270        // We need to re-extract after an OTA.
9271        boolean causeUpgrade = isUpgrade();
9272
9273        // First boot or factory reset.
9274        // Note: we also handle devices that are upgrading to N right now as if it is their
9275        //       first boot, as they do not have profile data.
9276        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9277
9278        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9279        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9280
9281        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9282            return;
9283        }
9284
9285        List<PackageParser.Package> pkgs;
9286        synchronized (mPackages) {
9287            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9288        }
9289
9290        final long startTime = System.nanoTime();
9291        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9292                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT),
9293                    false /* bootComplete */);
9294
9295        final int elapsedTimeSeconds =
9296                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9297
9298        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9299        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9300        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9301        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9302        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9303    }
9304
9305    /*
9306     * Return the prebuilt profile path given a package base code path.
9307     */
9308    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9309        return pkg.baseCodePath + ".prof";
9310    }
9311
9312    /**
9313     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9314     * containing statistics about the invocation. The array consists of three elements,
9315     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9316     * and {@code numberOfPackagesFailed}.
9317     */
9318    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9319            String compilerFilter, boolean bootComplete) {
9320
9321        int numberOfPackagesVisited = 0;
9322        int numberOfPackagesOptimized = 0;
9323        int numberOfPackagesSkipped = 0;
9324        int numberOfPackagesFailed = 0;
9325        final int numberOfPackagesToDexopt = pkgs.size();
9326
9327        for (PackageParser.Package pkg : pkgs) {
9328            numberOfPackagesVisited++;
9329
9330            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9331                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9332                // that are already compiled.
9333                File profileFile = new File(getPrebuildProfilePath(pkg));
9334                // Copy profile if it exists.
9335                if (profileFile.exists()) {
9336                    try {
9337                        // We could also do this lazily before calling dexopt in
9338                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9339                        // is that we don't have a good way to say "do this only once".
9340                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9341                                pkg.applicationInfo.uid, pkg.packageName)) {
9342                            Log.e(TAG, "Installer failed to copy system profile!");
9343                        }
9344                    } catch (Exception e) {
9345                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9346                                e);
9347                    }
9348                }
9349            }
9350
9351            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9352                if (DEBUG_DEXOPT) {
9353                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9354                }
9355                numberOfPackagesSkipped++;
9356                continue;
9357            }
9358
9359            if (DEBUG_DEXOPT) {
9360                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9361                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9362            }
9363
9364            if (showDialog) {
9365                try {
9366                    ActivityManager.getService().showBootMessage(
9367                            mContext.getResources().getString(R.string.android_upgrading_apk,
9368                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9369                } catch (RemoteException e) {
9370                }
9371                synchronized (mPackages) {
9372                    mDexOptDialogShown = true;
9373                }
9374            }
9375
9376            // If the OTA updates a system app which was previously preopted to a non-preopted state
9377            // the app might end up being verified at runtime. That's because by default the apps
9378            // are verify-profile but for preopted apps there's no profile.
9379            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9380            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9381            // filter (by default 'quicken').
9382            // Note that at this stage unused apps are already filtered.
9383            if (isSystemApp(pkg) &&
9384                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9385                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9386                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9387            }
9388
9389            // checkProfiles is false to avoid merging profiles during boot which
9390            // might interfere with background compilation (b/28612421).
9391            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9392            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9393            // trade-off worth doing to save boot time work.
9394            int dexOptStatus = performDexOptTraced(pkg.packageName,
9395                    false /* checkProfiles */,
9396                    compilerFilter,
9397                    false /* force */,
9398                    bootComplete);
9399            switch (dexOptStatus) {
9400                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9401                    numberOfPackagesOptimized++;
9402                    break;
9403                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9404                    numberOfPackagesSkipped++;
9405                    break;
9406                case PackageDexOptimizer.DEX_OPT_FAILED:
9407                    numberOfPackagesFailed++;
9408                    break;
9409                default:
9410                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
9411                    break;
9412            }
9413        }
9414
9415        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9416                numberOfPackagesFailed };
9417    }
9418
9419    @Override
9420    public void notifyPackageUse(String packageName, int reason) {
9421        synchronized (mPackages) {
9422            final int callingUid = Binder.getCallingUid();
9423            final int callingUserId = UserHandle.getUserId(callingUid);
9424            if (getInstantAppPackageName(callingUid) != null) {
9425                if (!isCallerSameApp(packageName, callingUid)) {
9426                    return;
9427                }
9428            } else {
9429                if (isInstantApp(packageName, callingUserId)) {
9430                    return;
9431                }
9432            }
9433            final PackageParser.Package p = mPackages.get(packageName);
9434            if (p == null) {
9435                return;
9436            }
9437            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9438        }
9439    }
9440
9441    @Override
9442    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
9443        int userId = UserHandle.getCallingUserId();
9444        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9445        if (ai == null) {
9446            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9447                + loadingPackageName + ", user=" + userId);
9448            return;
9449        }
9450        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
9451    }
9452
9453    @Override
9454    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9455            IDexModuleRegisterCallback callback) {
9456        int userId = UserHandle.getCallingUserId();
9457        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9458        DexManager.RegisterDexModuleResult result;
9459        if (ai == null) {
9460            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9461                     " calling user. package=" + packageName + ", user=" + userId);
9462            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9463        } else {
9464            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9465        }
9466
9467        if (callback != null) {
9468            mHandler.post(() -> {
9469                try {
9470                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9471                } catch (RemoteException e) {
9472                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9473                }
9474            });
9475        }
9476    }
9477
9478    @Override
9479    public boolean performDexOpt(String packageName,
9480            boolean checkProfiles, int compileReason, boolean force, boolean bootComplete) {
9481        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9482            return false;
9483        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9484            return false;
9485        }
9486        int dexoptStatus = performDexOptWithStatus(
9487              packageName, checkProfiles, compileReason, force, bootComplete);
9488        return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9489    }
9490
9491    /**
9492     * Perform dexopt on the given package and return one of following result:
9493     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9494     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9495     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9496     */
9497    /* package */ int performDexOptWithStatus(String packageName,
9498            boolean checkProfiles, int compileReason, boolean force, boolean bootComplete) {
9499        return performDexOptTraced(packageName, checkProfiles,
9500                getCompilerFilterForReason(compileReason), force, bootComplete);
9501    }
9502
9503    @Override
9504    public boolean performDexOptMode(String packageName,
9505            boolean checkProfiles, String targetCompilerFilter, boolean force,
9506            boolean bootComplete) {
9507        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9508            return false;
9509        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9510            return false;
9511        }
9512        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
9513                targetCompilerFilter, force, bootComplete);
9514        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9515    }
9516
9517    private int performDexOptTraced(String packageName,
9518                boolean checkProfiles, String targetCompilerFilter, boolean force,
9519                boolean bootComplete) {
9520        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9521        try {
9522            return performDexOptInternal(packageName, checkProfiles,
9523                    targetCompilerFilter, force, bootComplete);
9524        } finally {
9525            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9526        }
9527    }
9528
9529    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9530    // if the package can now be considered up to date for the given filter.
9531    private int performDexOptInternal(String packageName,
9532                boolean checkProfiles, String targetCompilerFilter, boolean force,
9533                boolean bootComplete) {
9534        PackageParser.Package p;
9535        synchronized (mPackages) {
9536            p = mPackages.get(packageName);
9537            if (p == null) {
9538                // Package could not be found. Report failure.
9539                return PackageDexOptimizer.DEX_OPT_FAILED;
9540            }
9541            mPackageUsage.maybeWriteAsync(mPackages);
9542            mCompilerStats.maybeWriteAsync();
9543        }
9544        long callingId = Binder.clearCallingIdentity();
9545        try {
9546            synchronized (mInstallLock) {
9547                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
9548                        targetCompilerFilter, force, bootComplete);
9549            }
9550        } finally {
9551            Binder.restoreCallingIdentity(callingId);
9552        }
9553    }
9554
9555    public ArraySet<String> getOptimizablePackages() {
9556        ArraySet<String> pkgs = new ArraySet<String>();
9557        synchronized (mPackages) {
9558            for (PackageParser.Package p : mPackages.values()) {
9559                if (PackageDexOptimizer.canOptimizePackage(p)) {
9560                    pkgs.add(p.packageName);
9561                }
9562            }
9563        }
9564        return pkgs;
9565    }
9566
9567    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9568            boolean checkProfiles, String targetCompilerFilter,
9569            boolean force, boolean bootComplete) {
9570        // Select the dex optimizer based on the force parameter.
9571        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9572        //       allocate an object here.
9573        PackageDexOptimizer pdo = force
9574                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9575                : mPackageDexOptimizer;
9576
9577        // Dexopt all dependencies first. Note: we ignore the return value and march on
9578        // on errors.
9579        // Note that we are going to call performDexOpt on those libraries as many times as
9580        // they are referenced in packages. When we do a batch of performDexOpt (for example
9581        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9582        // and the first package that uses the library will dexopt it. The
9583        // others will see that the compiled code for the library is up to date.
9584        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9585        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9586        if (!deps.isEmpty()) {
9587            for (PackageParser.Package depPackage : deps) {
9588                // TODO: Analyze and investigate if we (should) profile libraries.
9589                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9590                        false /* checkProfiles */,
9591                        targetCompilerFilter,
9592                        getOrCreateCompilerPackageStats(depPackage),
9593                        true /* isUsedByOtherApps */,
9594                        bootComplete);
9595            }
9596        }
9597        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
9598                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
9599                mDexManager.isUsedByOtherApps(p.packageName), bootComplete);
9600    }
9601
9602    // Performs dexopt on the used secondary dex files belonging to the given package.
9603    // Returns true if all dex files were process successfully (which could mean either dexopt or
9604    // skip). Returns false if any of the files caused errors.
9605    @Override
9606    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9607            boolean force) {
9608        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9609            return false;
9610        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9611            return false;
9612        }
9613        mDexManager.reconcileSecondaryDexFiles(packageName);
9614        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
9615    }
9616
9617    public boolean performDexOptSecondary(String packageName, int compileReason,
9618            boolean force) {
9619        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
9620    }
9621
9622    /**
9623     * Reconcile the information we have about the secondary dex files belonging to
9624     * {@code packagName} and the actual dex files. For all dex files that were
9625     * deleted, update the internal records and delete the generated oat files.
9626     */
9627    @Override
9628    public void reconcileSecondaryDexFiles(String packageName) {
9629        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9630            return;
9631        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9632            return;
9633        }
9634        mDexManager.reconcileSecondaryDexFiles(packageName);
9635    }
9636
9637    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9638    // a reference there.
9639    /*package*/ DexManager getDexManager() {
9640        return mDexManager;
9641    }
9642
9643    /**
9644     * Execute the background dexopt job immediately.
9645     */
9646    @Override
9647    public boolean runBackgroundDexoptJob() {
9648        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9649            return false;
9650        }
9651        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9652    }
9653
9654    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9655        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9656                || p.usesStaticLibraries != null) {
9657            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9658            Set<String> collectedNames = new HashSet<>();
9659            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9660
9661            retValue.remove(p);
9662
9663            return retValue;
9664        } else {
9665            return Collections.emptyList();
9666        }
9667    }
9668
9669    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9670            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9671        if (!collectedNames.contains(p.packageName)) {
9672            collectedNames.add(p.packageName);
9673            collected.add(p);
9674
9675            if (p.usesLibraries != null) {
9676                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9677                        null, collected, collectedNames);
9678            }
9679            if (p.usesOptionalLibraries != null) {
9680                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9681                        null, collected, collectedNames);
9682            }
9683            if (p.usesStaticLibraries != null) {
9684                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9685                        p.usesStaticLibrariesVersions, collected, collectedNames);
9686            }
9687        }
9688    }
9689
9690    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9691            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9692        final int libNameCount = libs.size();
9693        for (int i = 0; i < libNameCount; i++) {
9694            String libName = libs.get(i);
9695            int version = (versions != null && versions.length == libNameCount)
9696                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9697            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9698            if (libPkg != null) {
9699                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9700            }
9701        }
9702    }
9703
9704    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9705        synchronized (mPackages) {
9706            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9707            if (libEntry != null) {
9708                return mPackages.get(libEntry.apk);
9709            }
9710            return null;
9711        }
9712    }
9713
9714    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9715        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9716        if (versionedLib == null) {
9717            return null;
9718        }
9719        return versionedLib.get(version);
9720    }
9721
9722    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9723        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9724                pkg.staticSharedLibName);
9725        if (versionedLib == null) {
9726            return null;
9727        }
9728        int previousLibVersion = -1;
9729        final int versionCount = versionedLib.size();
9730        for (int i = 0; i < versionCount; i++) {
9731            final int libVersion = versionedLib.keyAt(i);
9732            if (libVersion < pkg.staticSharedLibVersion) {
9733                previousLibVersion = Math.max(previousLibVersion, libVersion);
9734            }
9735        }
9736        if (previousLibVersion >= 0) {
9737            return versionedLib.get(previousLibVersion);
9738        }
9739        return null;
9740    }
9741
9742    public void shutdown() {
9743        mPackageUsage.writeNow(mPackages);
9744        mCompilerStats.writeNow();
9745    }
9746
9747    @Override
9748    public void dumpProfiles(String packageName) {
9749        PackageParser.Package pkg;
9750        synchronized (mPackages) {
9751            pkg = mPackages.get(packageName);
9752            if (pkg == null) {
9753                throw new IllegalArgumentException("Unknown package: " + packageName);
9754            }
9755        }
9756        /* Only the shell, root, or the app user should be able to dump profiles. */
9757        int callingUid = Binder.getCallingUid();
9758        if (callingUid != Process.SHELL_UID &&
9759            callingUid != Process.ROOT_UID &&
9760            callingUid != pkg.applicationInfo.uid) {
9761            throw new SecurityException("dumpProfiles");
9762        }
9763
9764        synchronized (mInstallLock) {
9765            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9766            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9767            try {
9768                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9769                String codePaths = TextUtils.join(";", allCodePaths);
9770                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9771            } catch (InstallerException e) {
9772                Slog.w(TAG, "Failed to dump profiles", e);
9773            }
9774            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9775        }
9776    }
9777
9778    @Override
9779    public void forceDexOpt(String packageName) {
9780        enforceSystemOrRoot("forceDexOpt");
9781
9782        PackageParser.Package pkg;
9783        synchronized (mPackages) {
9784            pkg = mPackages.get(packageName);
9785            if (pkg == null) {
9786                throw new IllegalArgumentException("Unknown package: " + packageName);
9787            }
9788        }
9789
9790        synchronized (mInstallLock) {
9791            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9792
9793            // Whoever is calling forceDexOpt wants a compiled package.
9794            // Don't use profiles since that may cause compilation to be skipped.
9795            final int res = performDexOptInternalWithDependenciesLI(pkg,
9796                    false /* checkProfiles */, getDefaultCompilerFilter(),
9797                    true /* force */,
9798                    true /* bootComplete */);
9799
9800            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9801            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9802                throw new IllegalStateException("Failed to dexopt: " + res);
9803            }
9804        }
9805    }
9806
9807    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9808        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9809            Slog.w(TAG, "Unable to update from " + oldPkg.name
9810                    + " to " + newPkg.packageName
9811                    + ": old package not in system partition");
9812            return false;
9813        } else if (mPackages.get(oldPkg.name) != null) {
9814            Slog.w(TAG, "Unable to update from " + oldPkg.name
9815                    + " to " + newPkg.packageName
9816                    + ": old package still exists");
9817            return false;
9818        }
9819        return true;
9820    }
9821
9822    void removeCodePathLI(File codePath) {
9823        if (codePath.isDirectory()) {
9824            try {
9825                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9826            } catch (InstallerException e) {
9827                Slog.w(TAG, "Failed to remove code path", e);
9828            }
9829        } else {
9830            codePath.delete();
9831        }
9832    }
9833
9834    private int[] resolveUserIds(int userId) {
9835        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9836    }
9837
9838    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9839        if (pkg == null) {
9840            Slog.wtf(TAG, "Package was null!", new Throwable());
9841            return;
9842        }
9843        clearAppDataLeafLIF(pkg, userId, flags);
9844        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9845        for (int i = 0; i < childCount; i++) {
9846            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9847        }
9848    }
9849
9850    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9851        final PackageSetting ps;
9852        synchronized (mPackages) {
9853            ps = mSettings.mPackages.get(pkg.packageName);
9854        }
9855        for (int realUserId : resolveUserIds(userId)) {
9856            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9857            try {
9858                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9859                        ceDataInode);
9860            } catch (InstallerException e) {
9861                Slog.w(TAG, String.valueOf(e));
9862            }
9863        }
9864    }
9865
9866    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9867        if (pkg == null) {
9868            Slog.wtf(TAG, "Package was null!", new Throwable());
9869            return;
9870        }
9871        destroyAppDataLeafLIF(pkg, userId, flags);
9872        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9873        for (int i = 0; i < childCount; i++) {
9874            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9875        }
9876    }
9877
9878    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9879        final PackageSetting ps;
9880        synchronized (mPackages) {
9881            ps = mSettings.mPackages.get(pkg.packageName);
9882        }
9883        for (int realUserId : resolveUserIds(userId)) {
9884            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9885            try {
9886                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9887                        ceDataInode);
9888            } catch (InstallerException e) {
9889                Slog.w(TAG, String.valueOf(e));
9890            }
9891            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9892        }
9893    }
9894
9895    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9896        if (pkg == null) {
9897            Slog.wtf(TAG, "Package was null!", new Throwable());
9898            return;
9899        }
9900        destroyAppProfilesLeafLIF(pkg);
9901        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9902        for (int i = 0; i < childCount; i++) {
9903            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9904        }
9905    }
9906
9907    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9908        try {
9909            mInstaller.destroyAppProfiles(pkg.packageName);
9910        } catch (InstallerException e) {
9911            Slog.w(TAG, String.valueOf(e));
9912        }
9913    }
9914
9915    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9916        if (pkg == null) {
9917            Slog.wtf(TAG, "Package was null!", new Throwable());
9918            return;
9919        }
9920        clearAppProfilesLeafLIF(pkg);
9921        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9922        for (int i = 0; i < childCount; i++) {
9923            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9924        }
9925    }
9926
9927    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9928        try {
9929            mInstaller.clearAppProfiles(pkg.packageName);
9930        } catch (InstallerException e) {
9931            Slog.w(TAG, String.valueOf(e));
9932        }
9933    }
9934
9935    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9936            long lastUpdateTime) {
9937        // Set parent install/update time
9938        PackageSetting ps = (PackageSetting) pkg.mExtras;
9939        if (ps != null) {
9940            ps.firstInstallTime = firstInstallTime;
9941            ps.lastUpdateTime = lastUpdateTime;
9942        }
9943        // Set children install/update time
9944        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9945        for (int i = 0; i < childCount; i++) {
9946            PackageParser.Package childPkg = pkg.childPackages.get(i);
9947            ps = (PackageSetting) childPkg.mExtras;
9948            if (ps != null) {
9949                ps.firstInstallTime = firstInstallTime;
9950                ps.lastUpdateTime = lastUpdateTime;
9951            }
9952        }
9953    }
9954
9955    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9956            PackageParser.Package changingLib) {
9957        if (file.path != null) {
9958            usesLibraryFiles.add(file.path);
9959            return;
9960        }
9961        PackageParser.Package p = mPackages.get(file.apk);
9962        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9963            // If we are doing this while in the middle of updating a library apk,
9964            // then we need to make sure to use that new apk for determining the
9965            // dependencies here.  (We haven't yet finished committing the new apk
9966            // to the package manager state.)
9967            if (p == null || p.packageName.equals(changingLib.packageName)) {
9968                p = changingLib;
9969            }
9970        }
9971        if (p != null) {
9972            usesLibraryFiles.addAll(p.getAllCodePaths());
9973            if (p.usesLibraryFiles != null) {
9974                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9975            }
9976        }
9977    }
9978
9979    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9980            PackageParser.Package changingLib) throws PackageManagerException {
9981        if (pkg == null) {
9982            return;
9983        }
9984        ArraySet<String> usesLibraryFiles = null;
9985        if (pkg.usesLibraries != null) {
9986            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9987                    null, null, pkg.packageName, changingLib, true, null);
9988        }
9989        if (pkg.usesStaticLibraries != null) {
9990            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9991                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9992                    pkg.packageName, changingLib, true, usesLibraryFiles);
9993        }
9994        if (pkg.usesOptionalLibraries != null) {
9995            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9996                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
9997        }
9998        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9999            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10000        } else {
10001            pkg.usesLibraryFiles = null;
10002        }
10003    }
10004
10005    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
10006            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
10007            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
10008            boolean required, @Nullable ArraySet<String> outUsedLibraries)
10009            throws PackageManagerException {
10010        final int libCount = requestedLibraries.size();
10011        for (int i = 0; i < libCount; i++) {
10012            final String libName = requestedLibraries.get(i);
10013            final int libVersion = requiredVersions != null ? requiredVersions[i]
10014                    : SharedLibraryInfo.VERSION_UNDEFINED;
10015            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
10016            if (libEntry == null) {
10017                if (required) {
10018                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10019                            "Package " + packageName + " requires unavailable shared library "
10020                                    + libName + "; failing!");
10021                } else if (DEBUG_SHARED_LIBRARIES) {
10022                    Slog.i(TAG, "Package " + packageName
10023                            + " desires unavailable shared library "
10024                            + libName + "; ignoring!");
10025                }
10026            } else {
10027                if (requiredVersions != null && requiredCertDigests != null) {
10028                    if (libEntry.info.getVersion() != requiredVersions[i]) {
10029                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10030                            "Package " + packageName + " requires unavailable static shared"
10031                                    + " library " + libName + " version "
10032                                    + libEntry.info.getVersion() + "; failing!");
10033                    }
10034
10035                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
10036                    if (libPkg == null) {
10037                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10038                                "Package " + packageName + " requires unavailable static shared"
10039                                        + " library; failing!");
10040                    }
10041
10042                    String expectedCertDigest = requiredCertDigests[i];
10043                    String libCertDigest = PackageUtils.computeCertSha256Digest(
10044                                libPkg.mSignatures[0]);
10045                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
10046                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10047                                "Package " + packageName + " requires differently signed" +
10048                                        " static shared library; failing!");
10049                    }
10050                }
10051
10052                if (outUsedLibraries == null) {
10053                    outUsedLibraries = new ArraySet<>();
10054                }
10055                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
10056            }
10057        }
10058        return outUsedLibraries;
10059    }
10060
10061    private static boolean hasString(List<String> list, List<String> which) {
10062        if (list == null) {
10063            return false;
10064        }
10065        for (int i=list.size()-1; i>=0; i--) {
10066            for (int j=which.size()-1; j>=0; j--) {
10067                if (which.get(j).equals(list.get(i))) {
10068                    return true;
10069                }
10070            }
10071        }
10072        return false;
10073    }
10074
10075    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10076            PackageParser.Package changingPkg) {
10077        ArrayList<PackageParser.Package> res = null;
10078        for (PackageParser.Package pkg : mPackages.values()) {
10079            if (changingPkg != null
10080                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10081                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10082                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10083                            changingPkg.staticSharedLibName)) {
10084                return null;
10085            }
10086            if (res == null) {
10087                res = new ArrayList<>();
10088            }
10089            res.add(pkg);
10090            try {
10091                updateSharedLibrariesLPr(pkg, changingPkg);
10092            } catch (PackageManagerException e) {
10093                // If a system app update or an app and a required lib missing we
10094                // delete the package and for updated system apps keep the data as
10095                // it is better for the user to reinstall than to be in an limbo
10096                // state. Also libs disappearing under an app should never happen
10097                // - just in case.
10098                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10099                    final int flags = pkg.isUpdatedSystemApp()
10100                            ? PackageManager.DELETE_KEEP_DATA : 0;
10101                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10102                            flags , null, true, null);
10103                }
10104                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10105            }
10106        }
10107        return res;
10108    }
10109
10110    /**
10111     * Derive the value of the {@code cpuAbiOverride} based on the provided
10112     * value and an optional stored value from the package settings.
10113     */
10114    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10115        String cpuAbiOverride = null;
10116
10117        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10118            cpuAbiOverride = null;
10119        } else if (abiOverride != null) {
10120            cpuAbiOverride = abiOverride;
10121        } else if (settings != null) {
10122            cpuAbiOverride = settings.cpuAbiOverrideString;
10123        }
10124
10125        return cpuAbiOverride;
10126    }
10127
10128    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10129            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10130                    throws PackageManagerException {
10131        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10132        // If the package has children and this is the first dive in the function
10133        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10134        // whether all packages (parent and children) would be successfully scanned
10135        // before the actual scan since scanning mutates internal state and we want
10136        // to atomically install the package and its children.
10137        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10138            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10139                scanFlags |= SCAN_CHECK_ONLY;
10140            }
10141        } else {
10142            scanFlags &= ~SCAN_CHECK_ONLY;
10143        }
10144
10145        final PackageParser.Package scannedPkg;
10146        try {
10147            // Scan the parent
10148            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10149            // Scan the children
10150            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10151            for (int i = 0; i < childCount; i++) {
10152                PackageParser.Package childPkg = pkg.childPackages.get(i);
10153                scanPackageLI(childPkg, policyFlags,
10154                        scanFlags, currentTime, user);
10155            }
10156        } finally {
10157            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10158        }
10159
10160        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10161            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10162        }
10163
10164        return scannedPkg;
10165    }
10166
10167    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10168            int scanFlags, long currentTime, @Nullable UserHandle user)
10169                    throws PackageManagerException {
10170        boolean success = false;
10171        try {
10172            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10173                    currentTime, user);
10174            success = true;
10175            return res;
10176        } finally {
10177            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10178                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10179                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10180                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10181                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10182            }
10183        }
10184    }
10185
10186    /**
10187     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10188     */
10189    private static boolean apkHasCode(String fileName) {
10190        StrictJarFile jarFile = null;
10191        try {
10192            jarFile = new StrictJarFile(fileName,
10193                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10194            return jarFile.findEntry("classes.dex") != null;
10195        } catch (IOException ignore) {
10196        } finally {
10197            try {
10198                if (jarFile != null) {
10199                    jarFile.close();
10200                }
10201            } catch (IOException ignore) {}
10202        }
10203        return false;
10204    }
10205
10206    /**
10207     * Enforces code policy for the package. This ensures that if an APK has
10208     * declared hasCode="true" in its manifest that the APK actually contains
10209     * code.
10210     *
10211     * @throws PackageManagerException If bytecode could not be found when it should exist
10212     */
10213    private static void assertCodePolicy(PackageParser.Package pkg)
10214            throws PackageManagerException {
10215        final boolean shouldHaveCode =
10216                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10217        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10218            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10219                    "Package " + pkg.baseCodePath + " code is missing");
10220        }
10221
10222        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10223            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10224                final boolean splitShouldHaveCode =
10225                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10226                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10227                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10228                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10229                }
10230            }
10231        }
10232    }
10233
10234    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10235            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10236                    throws PackageManagerException {
10237        if (DEBUG_PACKAGE_SCANNING) {
10238            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10239                Log.d(TAG, "Scanning package " + pkg.packageName);
10240        }
10241
10242        applyPolicy(pkg, policyFlags);
10243
10244        assertPackageIsValid(pkg, policyFlags, scanFlags);
10245
10246        // Initialize package source and resource directories
10247        final File scanFile = new File(pkg.codePath);
10248        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10249        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10250
10251        SharedUserSetting suid = null;
10252        PackageSetting pkgSetting = null;
10253
10254        // Getting the package setting may have a side-effect, so if we
10255        // are only checking if scan would succeed, stash a copy of the
10256        // old setting to restore at the end.
10257        PackageSetting nonMutatedPs = null;
10258
10259        // We keep references to the derived CPU Abis from settings in oder to reuse
10260        // them in the case where we're not upgrading or booting for the first time.
10261        String primaryCpuAbiFromSettings = null;
10262        String secondaryCpuAbiFromSettings = null;
10263
10264        // writer
10265        synchronized (mPackages) {
10266            if (pkg.mSharedUserId != null) {
10267                // SIDE EFFECTS; may potentially allocate a new shared user
10268                suid = mSettings.getSharedUserLPw(
10269                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10270                if (DEBUG_PACKAGE_SCANNING) {
10271                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10272                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10273                                + "): packages=" + suid.packages);
10274                }
10275            }
10276
10277            // Check if we are renaming from an original package name.
10278            PackageSetting origPackage = null;
10279            String realName = null;
10280            if (pkg.mOriginalPackages != null) {
10281                // This package may need to be renamed to a previously
10282                // installed name.  Let's check on that...
10283                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10284                if (pkg.mOriginalPackages.contains(renamed)) {
10285                    // This package had originally been installed as the
10286                    // original name, and we have already taken care of
10287                    // transitioning to the new one.  Just update the new
10288                    // one to continue using the old name.
10289                    realName = pkg.mRealPackage;
10290                    if (!pkg.packageName.equals(renamed)) {
10291                        // Callers into this function may have already taken
10292                        // care of renaming the package; only do it here if
10293                        // it is not already done.
10294                        pkg.setPackageName(renamed);
10295                    }
10296                } else {
10297                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10298                        if ((origPackage = mSettings.getPackageLPr(
10299                                pkg.mOriginalPackages.get(i))) != null) {
10300                            // We do have the package already installed under its
10301                            // original name...  should we use it?
10302                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10303                                // New package is not compatible with original.
10304                                origPackage = null;
10305                                continue;
10306                            } else if (origPackage.sharedUser != null) {
10307                                // Make sure uid is compatible between packages.
10308                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10309                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10310                                            + " to " + pkg.packageName + ": old uid "
10311                                            + origPackage.sharedUser.name
10312                                            + " differs from " + pkg.mSharedUserId);
10313                                    origPackage = null;
10314                                    continue;
10315                                }
10316                                // TODO: Add case when shared user id is added [b/28144775]
10317                            } else {
10318                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10319                                        + pkg.packageName + " to old name " + origPackage.name);
10320                            }
10321                            break;
10322                        }
10323                    }
10324                }
10325            }
10326
10327            if (mTransferedPackages.contains(pkg.packageName)) {
10328                Slog.w(TAG, "Package " + pkg.packageName
10329                        + " was transferred to another, but its .apk remains");
10330            }
10331
10332            // See comments in nonMutatedPs declaration
10333            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10334                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10335                if (foundPs != null) {
10336                    nonMutatedPs = new PackageSetting(foundPs);
10337                }
10338            }
10339
10340            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10341                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10342                if (foundPs != null) {
10343                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10344                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10345                }
10346            }
10347
10348            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10349            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10350                PackageManagerService.reportSettingsProblem(Log.WARN,
10351                        "Package " + pkg.packageName + " shared user changed from "
10352                                + (pkgSetting.sharedUser != null
10353                                        ? pkgSetting.sharedUser.name : "<nothing>")
10354                                + " to "
10355                                + (suid != null ? suid.name : "<nothing>")
10356                                + "; replacing with new");
10357                pkgSetting = null;
10358            }
10359            final PackageSetting oldPkgSetting =
10360                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10361            final PackageSetting disabledPkgSetting =
10362                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10363
10364            String[] usesStaticLibraries = null;
10365            if (pkg.usesStaticLibraries != null) {
10366                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10367                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10368            }
10369
10370            if (pkgSetting == null) {
10371                final String parentPackageName = (pkg.parentPackage != null)
10372                        ? pkg.parentPackage.packageName : null;
10373                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10374                // REMOVE SharedUserSetting from method; update in a separate call
10375                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10376                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10377                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10378                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10379                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10380                        true /*allowInstall*/, instantApp, parentPackageName,
10381                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
10382                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10383                // SIDE EFFECTS; updates system state; move elsewhere
10384                if (origPackage != null) {
10385                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10386                }
10387                mSettings.addUserToSettingLPw(pkgSetting);
10388            } else {
10389                // REMOVE SharedUserSetting from method; update in a separate call.
10390                //
10391                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10392                // secondaryCpuAbi are not known at this point so we always update them
10393                // to null here, only to reset them at a later point.
10394                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10395                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10396                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10397                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10398                        UserManagerService.getInstance(), usesStaticLibraries,
10399                        pkg.usesStaticLibrariesVersions);
10400            }
10401            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10402            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10403
10404            // SIDE EFFECTS; modifies system state; move elsewhere
10405            if (pkgSetting.origPackage != null) {
10406                // If we are first transitioning from an original package,
10407                // fix up the new package's name now.  We need to do this after
10408                // looking up the package under its new name, so getPackageLP
10409                // can take care of fiddling things correctly.
10410                pkg.setPackageName(origPackage.name);
10411
10412                // File a report about this.
10413                String msg = "New package " + pkgSetting.realName
10414                        + " renamed to replace old package " + pkgSetting.name;
10415                reportSettingsProblem(Log.WARN, msg);
10416
10417                // Make a note of it.
10418                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10419                    mTransferedPackages.add(origPackage.name);
10420                }
10421
10422                // No longer need to retain this.
10423                pkgSetting.origPackage = null;
10424            }
10425
10426            // SIDE EFFECTS; modifies system state; move elsewhere
10427            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10428                // Make a note of it.
10429                mTransferedPackages.add(pkg.packageName);
10430            }
10431
10432            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10433                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10434            }
10435
10436            if ((scanFlags & SCAN_BOOTING) == 0
10437                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10438                // Check all shared libraries and map to their actual file path.
10439                // We only do this here for apps not on a system dir, because those
10440                // are the only ones that can fail an install due to this.  We
10441                // will take care of the system apps by updating all of their
10442                // library paths after the scan is done. Also during the initial
10443                // scan don't update any libs as we do this wholesale after all
10444                // apps are scanned to avoid dependency based scanning.
10445                updateSharedLibrariesLPr(pkg, null);
10446            }
10447
10448            if (mFoundPolicyFile) {
10449                SELinuxMMAC.assignSeInfoValue(pkg);
10450            }
10451            pkg.applicationInfo.uid = pkgSetting.appId;
10452            pkg.mExtras = pkgSetting;
10453
10454
10455            // Static shared libs have same package with different versions where
10456            // we internally use a synthetic package name to allow multiple versions
10457            // of the same package, therefore we need to compare signatures against
10458            // the package setting for the latest library version.
10459            PackageSetting signatureCheckPs = pkgSetting;
10460            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10461                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10462                if (libraryEntry != null) {
10463                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10464                }
10465            }
10466
10467            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10468                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10469                    // We just determined the app is signed correctly, so bring
10470                    // over the latest parsed certs.
10471                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10472                } else {
10473                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10474                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10475                                "Package " + pkg.packageName + " upgrade keys do not match the "
10476                                + "previously installed version");
10477                    } else {
10478                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10479                        String msg = "System package " + pkg.packageName
10480                                + " signature changed; retaining data.";
10481                        reportSettingsProblem(Log.WARN, msg);
10482                    }
10483                }
10484            } else {
10485                try {
10486                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10487                    verifySignaturesLP(signatureCheckPs, pkg);
10488                    // We just determined the app is signed correctly, so bring
10489                    // over the latest parsed certs.
10490                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10491                } catch (PackageManagerException e) {
10492                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10493                        throw e;
10494                    }
10495                    // The signature has changed, but this package is in the system
10496                    // image...  let's recover!
10497                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10498                    // However...  if this package is part of a shared user, but it
10499                    // doesn't match the signature of the shared user, let's fail.
10500                    // What this means is that you can't change the signatures
10501                    // associated with an overall shared user, which doesn't seem all
10502                    // that unreasonable.
10503                    if (signatureCheckPs.sharedUser != null) {
10504                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10505                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10506                            throw new PackageManagerException(
10507                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10508                                    "Signature mismatch for shared user: "
10509                                            + pkgSetting.sharedUser);
10510                        }
10511                    }
10512                    // File a report about this.
10513                    String msg = "System package " + pkg.packageName
10514                            + " signature changed; retaining data.";
10515                    reportSettingsProblem(Log.WARN, msg);
10516                }
10517            }
10518
10519            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10520                // This package wants to adopt ownership of permissions from
10521                // another package.
10522                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10523                    final String origName = pkg.mAdoptPermissions.get(i);
10524                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10525                    if (orig != null) {
10526                        if (verifyPackageUpdateLPr(orig, pkg)) {
10527                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10528                                    + pkg.packageName);
10529                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10530                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10531                        }
10532                    }
10533                }
10534            }
10535        }
10536
10537        pkg.applicationInfo.processName = fixProcessName(
10538                pkg.applicationInfo.packageName,
10539                pkg.applicationInfo.processName);
10540
10541        if (pkg != mPlatformPackage) {
10542            // Get all of our default paths setup
10543            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10544        }
10545
10546        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10547
10548        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10549            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10550                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10551                derivePackageAbi(
10552                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
10553                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10554
10555                // Some system apps still use directory structure for native libraries
10556                // in which case we might end up not detecting abi solely based on apk
10557                // structure. Try to detect abi based on directory structure.
10558                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10559                        pkg.applicationInfo.primaryCpuAbi == null) {
10560                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10561                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10562                }
10563            } else {
10564                // This is not a first boot or an upgrade, don't bother deriving the
10565                // ABI during the scan. Instead, trust the value that was stored in the
10566                // package setting.
10567                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10568                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10569
10570                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10571
10572                if (DEBUG_ABI_SELECTION) {
10573                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10574                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10575                        pkg.applicationInfo.secondaryCpuAbi);
10576                }
10577            }
10578        } else {
10579            if ((scanFlags & SCAN_MOVE) != 0) {
10580                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10581                // but we already have this packages package info in the PackageSetting. We just
10582                // use that and derive the native library path based on the new codepath.
10583                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10584                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10585            }
10586
10587            // Set native library paths again. For moves, the path will be updated based on the
10588            // ABIs we've determined above. For non-moves, the path will be updated based on the
10589            // ABIs we determined during compilation, but the path will depend on the final
10590            // package path (after the rename away from the stage path).
10591            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10592        }
10593
10594        // This is a special case for the "system" package, where the ABI is
10595        // dictated by the zygote configuration (and init.rc). We should keep track
10596        // of this ABI so that we can deal with "normal" applications that run under
10597        // the same UID correctly.
10598        if (mPlatformPackage == pkg) {
10599            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10600                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10601        }
10602
10603        // If there's a mismatch between the abi-override in the package setting
10604        // and the abiOverride specified for the install. Warn about this because we
10605        // would've already compiled the app without taking the package setting into
10606        // account.
10607        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10608            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10609                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10610                        " for package " + pkg.packageName);
10611            }
10612        }
10613
10614        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10615        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10616        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10617
10618        // Copy the derived override back to the parsed package, so that we can
10619        // update the package settings accordingly.
10620        pkg.cpuAbiOverride = cpuAbiOverride;
10621
10622        if (DEBUG_ABI_SELECTION) {
10623            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10624                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10625                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10626        }
10627
10628        // Push the derived path down into PackageSettings so we know what to
10629        // clean up at uninstall time.
10630        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10631
10632        if (DEBUG_ABI_SELECTION) {
10633            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10634                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10635                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10636        }
10637
10638        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10639        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10640            // We don't do this here during boot because we can do it all
10641            // at once after scanning all existing packages.
10642            //
10643            // We also do this *before* we perform dexopt on this package, so that
10644            // we can avoid redundant dexopts, and also to make sure we've got the
10645            // code and package path correct.
10646            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10647        }
10648
10649        if (mFactoryTest && pkg.requestedPermissions.contains(
10650                android.Manifest.permission.FACTORY_TEST)) {
10651            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10652        }
10653
10654        if (isSystemApp(pkg)) {
10655            pkgSetting.isOrphaned = true;
10656        }
10657
10658        // Take care of first install / last update times.
10659        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10660        if (currentTime != 0) {
10661            if (pkgSetting.firstInstallTime == 0) {
10662                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10663            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10664                pkgSetting.lastUpdateTime = currentTime;
10665            }
10666        } else if (pkgSetting.firstInstallTime == 0) {
10667            // We need *something*.  Take time time stamp of the file.
10668            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10669        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10670            if (scanFileTime != pkgSetting.timeStamp) {
10671                // A package on the system image has changed; consider this
10672                // to be an update.
10673                pkgSetting.lastUpdateTime = scanFileTime;
10674            }
10675        }
10676        pkgSetting.setTimeStamp(scanFileTime);
10677
10678        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10679            if (nonMutatedPs != null) {
10680                synchronized (mPackages) {
10681                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10682                }
10683            }
10684        } else {
10685            final int userId = user == null ? 0 : user.getIdentifier();
10686            // Modify state for the given package setting
10687            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10688                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10689            if (pkgSetting.getInstantApp(userId)) {
10690                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10691            }
10692        }
10693        return pkg;
10694    }
10695
10696    /**
10697     * Applies policy to the parsed package based upon the given policy flags.
10698     * Ensures the package is in a good state.
10699     * <p>
10700     * Implementation detail: This method must NOT have any side effect. It would
10701     * ideally be static, but, it requires locks to read system state.
10702     */
10703    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10704        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10705            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10706            if (pkg.applicationInfo.isDirectBootAware()) {
10707                // we're direct boot aware; set for all components
10708                for (PackageParser.Service s : pkg.services) {
10709                    s.info.encryptionAware = s.info.directBootAware = true;
10710                }
10711                for (PackageParser.Provider p : pkg.providers) {
10712                    p.info.encryptionAware = p.info.directBootAware = true;
10713                }
10714                for (PackageParser.Activity a : pkg.activities) {
10715                    a.info.encryptionAware = a.info.directBootAware = true;
10716                }
10717                for (PackageParser.Activity r : pkg.receivers) {
10718                    r.info.encryptionAware = r.info.directBootAware = true;
10719                }
10720            }
10721        } else {
10722            // Only allow system apps to be flagged as core apps.
10723            pkg.coreApp = false;
10724            // clear flags not applicable to regular apps
10725            pkg.applicationInfo.privateFlags &=
10726                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10727            pkg.applicationInfo.privateFlags &=
10728                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10729        }
10730        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10731
10732        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10733            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10734        }
10735
10736        if (!isSystemApp(pkg)) {
10737            // Only system apps can use these features.
10738            pkg.mOriginalPackages = null;
10739            pkg.mRealPackage = null;
10740            pkg.mAdoptPermissions = null;
10741        }
10742    }
10743
10744    /**
10745     * Asserts the parsed package is valid according to the given policy. If the
10746     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10747     * <p>
10748     * Implementation detail: This method must NOT have any side effects. It would
10749     * ideally be static, but, it requires locks to read system state.
10750     *
10751     * @throws PackageManagerException If the package fails any of the validation checks
10752     */
10753    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10754            throws PackageManagerException {
10755        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10756            assertCodePolicy(pkg);
10757        }
10758
10759        if (pkg.applicationInfo.getCodePath() == null ||
10760                pkg.applicationInfo.getResourcePath() == null) {
10761            // Bail out. The resource and code paths haven't been set.
10762            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10763                    "Code and resource paths haven't been set correctly");
10764        }
10765
10766        // Make sure we're not adding any bogus keyset info
10767        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10768        ksms.assertScannedPackageValid(pkg);
10769
10770        synchronized (mPackages) {
10771            // The special "android" package can only be defined once
10772            if (pkg.packageName.equals("android")) {
10773                if (mAndroidApplication != null) {
10774                    Slog.w(TAG, "*************************************************");
10775                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10776                    Slog.w(TAG, " codePath=" + pkg.codePath);
10777                    Slog.w(TAG, "*************************************************");
10778                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10779                            "Core android package being redefined.  Skipping.");
10780                }
10781            }
10782
10783            // A package name must be unique; don't allow duplicates
10784            if (mPackages.containsKey(pkg.packageName)) {
10785                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10786                        "Application package " + pkg.packageName
10787                        + " already installed.  Skipping duplicate.");
10788            }
10789
10790            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10791                // Static libs have a synthetic package name containing the version
10792                // but we still want the base name to be unique.
10793                if (mPackages.containsKey(pkg.manifestPackageName)) {
10794                    throw new PackageManagerException(
10795                            "Duplicate static shared lib provider package");
10796                }
10797
10798                // Static shared libraries should have at least O target SDK
10799                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10800                    throw new PackageManagerException(
10801                            "Packages declaring static-shared libs must target O SDK or higher");
10802                }
10803
10804                // Package declaring static a shared lib cannot be instant apps
10805                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10806                    throw new PackageManagerException(
10807                            "Packages declaring static-shared libs cannot be instant apps");
10808                }
10809
10810                // Package declaring static a shared lib cannot be renamed since the package
10811                // name is synthetic and apps can't code around package manager internals.
10812                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10813                    throw new PackageManagerException(
10814                            "Packages declaring static-shared libs cannot be renamed");
10815                }
10816
10817                // Package declaring static a shared lib cannot declare child packages
10818                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10819                    throw new PackageManagerException(
10820                            "Packages declaring static-shared libs cannot have child packages");
10821                }
10822
10823                // Package declaring static a shared lib cannot declare dynamic libs
10824                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10825                    throw new PackageManagerException(
10826                            "Packages declaring static-shared libs cannot declare dynamic libs");
10827                }
10828
10829                // Package declaring static a shared lib cannot declare shared users
10830                if (pkg.mSharedUserId != null) {
10831                    throw new PackageManagerException(
10832                            "Packages declaring static-shared libs cannot declare shared users");
10833                }
10834
10835                // Static shared libs cannot declare activities
10836                if (!pkg.activities.isEmpty()) {
10837                    throw new PackageManagerException(
10838                            "Static shared libs cannot declare activities");
10839                }
10840
10841                // Static shared libs cannot declare services
10842                if (!pkg.services.isEmpty()) {
10843                    throw new PackageManagerException(
10844                            "Static shared libs cannot declare services");
10845                }
10846
10847                // Static shared libs cannot declare providers
10848                if (!pkg.providers.isEmpty()) {
10849                    throw new PackageManagerException(
10850                            "Static shared libs cannot declare content providers");
10851                }
10852
10853                // Static shared libs cannot declare receivers
10854                if (!pkg.receivers.isEmpty()) {
10855                    throw new PackageManagerException(
10856                            "Static shared libs cannot declare broadcast receivers");
10857                }
10858
10859                // Static shared libs cannot declare permission groups
10860                if (!pkg.permissionGroups.isEmpty()) {
10861                    throw new PackageManagerException(
10862                            "Static shared libs cannot declare permission groups");
10863                }
10864
10865                // Static shared libs cannot declare permissions
10866                if (!pkg.permissions.isEmpty()) {
10867                    throw new PackageManagerException(
10868                            "Static shared libs cannot declare permissions");
10869                }
10870
10871                // Static shared libs cannot declare protected broadcasts
10872                if (pkg.protectedBroadcasts != null) {
10873                    throw new PackageManagerException(
10874                            "Static shared libs cannot declare protected broadcasts");
10875                }
10876
10877                // Static shared libs cannot be overlay targets
10878                if (pkg.mOverlayTarget != null) {
10879                    throw new PackageManagerException(
10880                            "Static shared libs cannot be overlay targets");
10881                }
10882
10883                // The version codes must be ordered as lib versions
10884                int minVersionCode = Integer.MIN_VALUE;
10885                int maxVersionCode = Integer.MAX_VALUE;
10886
10887                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10888                        pkg.staticSharedLibName);
10889                if (versionedLib != null) {
10890                    final int versionCount = versionedLib.size();
10891                    for (int i = 0; i < versionCount; i++) {
10892                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10893                        final int libVersionCode = libInfo.getDeclaringPackage()
10894                                .getVersionCode();
10895                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10896                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10897                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10898                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10899                        } else {
10900                            minVersionCode = maxVersionCode = libVersionCode;
10901                            break;
10902                        }
10903                    }
10904                }
10905                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10906                    throw new PackageManagerException("Static shared"
10907                            + " lib version codes must be ordered as lib versions");
10908                }
10909            }
10910
10911            // Only privileged apps and updated privileged apps can add child packages.
10912            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10913                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10914                    throw new PackageManagerException("Only privileged apps can add child "
10915                            + "packages. Ignoring package " + pkg.packageName);
10916                }
10917                final int childCount = pkg.childPackages.size();
10918                for (int i = 0; i < childCount; i++) {
10919                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10920                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10921                            childPkg.packageName)) {
10922                        throw new PackageManagerException("Can't override child of "
10923                                + "another disabled app. Ignoring package " + pkg.packageName);
10924                    }
10925                }
10926            }
10927
10928            // If we're only installing presumed-existing packages, require that the
10929            // scanned APK is both already known and at the path previously established
10930            // for it.  Previously unknown packages we pick up normally, but if we have an
10931            // a priori expectation about this package's install presence, enforce it.
10932            // With a singular exception for new system packages. When an OTA contains
10933            // a new system package, we allow the codepath to change from a system location
10934            // to the user-installed location. If we don't allow this change, any newer,
10935            // user-installed version of the application will be ignored.
10936            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10937                if (mExpectingBetter.containsKey(pkg.packageName)) {
10938                    logCriticalInfo(Log.WARN,
10939                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10940                } else {
10941                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10942                    if (known != null) {
10943                        if (DEBUG_PACKAGE_SCANNING) {
10944                            Log.d(TAG, "Examining " + pkg.codePath
10945                                    + " and requiring known paths " + known.codePathString
10946                                    + " & " + known.resourcePathString);
10947                        }
10948                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10949                                || !pkg.applicationInfo.getResourcePath().equals(
10950                                        known.resourcePathString)) {
10951                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10952                                    "Application package " + pkg.packageName
10953                                    + " found at " + pkg.applicationInfo.getCodePath()
10954                                    + " but expected at " + known.codePathString
10955                                    + "; ignoring.");
10956                        }
10957                    }
10958                }
10959            }
10960
10961            // Verify that this new package doesn't have any content providers
10962            // that conflict with existing packages.  Only do this if the
10963            // package isn't already installed, since we don't want to break
10964            // things that are installed.
10965            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10966                final int N = pkg.providers.size();
10967                int i;
10968                for (i=0; i<N; i++) {
10969                    PackageParser.Provider p = pkg.providers.get(i);
10970                    if (p.info.authority != null) {
10971                        String names[] = p.info.authority.split(";");
10972                        for (int j = 0; j < names.length; j++) {
10973                            if (mProvidersByAuthority.containsKey(names[j])) {
10974                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10975                                final String otherPackageName =
10976                                        ((other != null && other.getComponentName() != null) ?
10977                                                other.getComponentName().getPackageName() : "?");
10978                                throw new PackageManagerException(
10979                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10980                                        "Can't install because provider name " + names[j]
10981                                                + " (in package " + pkg.applicationInfo.packageName
10982                                                + ") is already used by " + otherPackageName);
10983                            }
10984                        }
10985                    }
10986                }
10987            }
10988        }
10989    }
10990
10991    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10992            int type, String declaringPackageName, int declaringVersionCode) {
10993        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10994        if (versionedLib == null) {
10995            versionedLib = new SparseArray<>();
10996            mSharedLibraries.put(name, versionedLib);
10997            if (type == SharedLibraryInfo.TYPE_STATIC) {
10998                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10999            }
11000        } else if (versionedLib.indexOfKey(version) >= 0) {
11001            return false;
11002        }
11003        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11004                version, type, declaringPackageName, declaringVersionCode);
11005        versionedLib.put(version, libEntry);
11006        return true;
11007    }
11008
11009    private boolean removeSharedLibraryLPw(String name, int version) {
11010        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11011        if (versionedLib == null) {
11012            return false;
11013        }
11014        final int libIdx = versionedLib.indexOfKey(version);
11015        if (libIdx < 0) {
11016            return false;
11017        }
11018        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11019        versionedLib.remove(version);
11020        if (versionedLib.size() <= 0) {
11021            mSharedLibraries.remove(name);
11022            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11023                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11024                        .getPackageName());
11025            }
11026        }
11027        return true;
11028    }
11029
11030    /**
11031     * Adds a scanned package to the system. When this method is finished, the package will
11032     * be available for query, resolution, etc...
11033     */
11034    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11035            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
11036        final String pkgName = pkg.packageName;
11037        if (mCustomResolverComponentName != null &&
11038                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11039            setUpCustomResolverActivity(pkg);
11040        }
11041
11042        if (pkg.packageName.equals("android")) {
11043            synchronized (mPackages) {
11044                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11045                    // Set up information for our fall-back user intent resolution activity.
11046                    mPlatformPackage = pkg;
11047                    pkg.mVersionCode = mSdkVersion;
11048                    mAndroidApplication = pkg.applicationInfo;
11049                    if (!mResolverReplaced) {
11050                        mResolveActivity.applicationInfo = mAndroidApplication;
11051                        mResolveActivity.name = ResolverActivity.class.getName();
11052                        mResolveActivity.packageName = mAndroidApplication.packageName;
11053                        mResolveActivity.processName = "system:ui";
11054                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11055                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11056                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11057                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11058                        mResolveActivity.exported = true;
11059                        mResolveActivity.enabled = true;
11060                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11061                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11062                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11063                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11064                                | ActivityInfo.CONFIG_ORIENTATION
11065                                | ActivityInfo.CONFIG_KEYBOARD
11066                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11067                        mResolveInfo.activityInfo = mResolveActivity;
11068                        mResolveInfo.priority = 0;
11069                        mResolveInfo.preferredOrder = 0;
11070                        mResolveInfo.match = 0;
11071                        mResolveComponentName = new ComponentName(
11072                                mAndroidApplication.packageName, mResolveActivity.name);
11073                    }
11074                }
11075            }
11076        }
11077
11078        ArrayList<PackageParser.Package> clientLibPkgs = null;
11079        // writer
11080        synchronized (mPackages) {
11081            boolean hasStaticSharedLibs = false;
11082
11083            // Any app can add new static shared libraries
11084            if (pkg.staticSharedLibName != null) {
11085                // Static shared libs don't allow renaming as they have synthetic package
11086                // names to allow install of multiple versions, so use name from manifest.
11087                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11088                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11089                        pkg.manifestPackageName, pkg.mVersionCode)) {
11090                    hasStaticSharedLibs = true;
11091                } else {
11092                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11093                                + pkg.staticSharedLibName + " already exists; skipping");
11094                }
11095                // Static shared libs cannot be updated once installed since they
11096                // use synthetic package name which includes the version code, so
11097                // not need to update other packages's shared lib dependencies.
11098            }
11099
11100            if (!hasStaticSharedLibs
11101                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11102                // Only system apps can add new dynamic shared libraries.
11103                if (pkg.libraryNames != null) {
11104                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11105                        String name = pkg.libraryNames.get(i);
11106                        boolean allowed = false;
11107                        if (pkg.isUpdatedSystemApp()) {
11108                            // New library entries can only be added through the
11109                            // system image.  This is important to get rid of a lot
11110                            // of nasty edge cases: for example if we allowed a non-
11111                            // system update of the app to add a library, then uninstalling
11112                            // the update would make the library go away, and assumptions
11113                            // we made such as through app install filtering would now
11114                            // have allowed apps on the device which aren't compatible
11115                            // with it.  Better to just have the restriction here, be
11116                            // conservative, and create many fewer cases that can negatively
11117                            // impact the user experience.
11118                            final PackageSetting sysPs = mSettings
11119                                    .getDisabledSystemPkgLPr(pkg.packageName);
11120                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11121                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11122                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11123                                        allowed = true;
11124                                        break;
11125                                    }
11126                                }
11127                            }
11128                        } else {
11129                            allowed = true;
11130                        }
11131                        if (allowed) {
11132                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11133                                    SharedLibraryInfo.VERSION_UNDEFINED,
11134                                    SharedLibraryInfo.TYPE_DYNAMIC,
11135                                    pkg.packageName, pkg.mVersionCode)) {
11136                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11137                                        + name + " already exists; skipping");
11138                            }
11139                        } else {
11140                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11141                                    + name + " that is not declared on system image; skipping");
11142                        }
11143                    }
11144
11145                    if ((scanFlags & SCAN_BOOTING) == 0) {
11146                        // If we are not booting, we need to update any applications
11147                        // that are clients of our shared library.  If we are booting,
11148                        // this will all be done once the scan is complete.
11149                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11150                    }
11151                }
11152            }
11153        }
11154
11155        if ((scanFlags & SCAN_BOOTING) != 0) {
11156            // No apps can run during boot scan, so they don't need to be frozen
11157        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11158            // Caller asked to not kill app, so it's probably not frozen
11159        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11160            // Caller asked us to ignore frozen check for some reason; they
11161            // probably didn't know the package name
11162        } else {
11163            // We're doing major surgery on this package, so it better be frozen
11164            // right now to keep it from launching
11165            checkPackageFrozen(pkgName);
11166        }
11167
11168        // Also need to kill any apps that are dependent on the library.
11169        if (clientLibPkgs != null) {
11170            for (int i=0; i<clientLibPkgs.size(); i++) {
11171                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11172                killApplication(clientPkg.applicationInfo.packageName,
11173                        clientPkg.applicationInfo.uid, "update lib");
11174            }
11175        }
11176
11177        // writer
11178        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11179
11180        synchronized (mPackages) {
11181            // We don't expect installation to fail beyond this point
11182
11183            // Add the new setting to mSettings
11184            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11185            // Add the new setting to mPackages
11186            mPackages.put(pkg.applicationInfo.packageName, pkg);
11187            // Make sure we don't accidentally delete its data.
11188            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11189            while (iter.hasNext()) {
11190                PackageCleanItem item = iter.next();
11191                if (pkgName.equals(item.packageName)) {
11192                    iter.remove();
11193                }
11194            }
11195
11196            // Add the package's KeySets to the global KeySetManagerService
11197            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11198            ksms.addScannedPackageLPw(pkg);
11199
11200            int N = pkg.providers.size();
11201            StringBuilder r = null;
11202            int i;
11203            for (i=0; i<N; i++) {
11204                PackageParser.Provider p = pkg.providers.get(i);
11205                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11206                        p.info.processName);
11207                mProviders.addProvider(p);
11208                p.syncable = p.info.isSyncable;
11209                if (p.info.authority != null) {
11210                    String names[] = p.info.authority.split(";");
11211                    p.info.authority = null;
11212                    for (int j = 0; j < names.length; j++) {
11213                        if (j == 1 && p.syncable) {
11214                            // We only want the first authority for a provider to possibly be
11215                            // syncable, so if we already added this provider using a different
11216                            // authority clear the syncable flag. We copy the provider before
11217                            // changing it because the mProviders object contains a reference
11218                            // to a provider that we don't want to change.
11219                            // Only do this for the second authority since the resulting provider
11220                            // object can be the same for all future authorities for this provider.
11221                            p = new PackageParser.Provider(p);
11222                            p.syncable = false;
11223                        }
11224                        if (!mProvidersByAuthority.containsKey(names[j])) {
11225                            mProvidersByAuthority.put(names[j], p);
11226                            if (p.info.authority == null) {
11227                                p.info.authority = names[j];
11228                            } else {
11229                                p.info.authority = p.info.authority + ";" + names[j];
11230                            }
11231                            if (DEBUG_PACKAGE_SCANNING) {
11232                                if (chatty)
11233                                    Log.d(TAG, "Registered content provider: " + names[j]
11234                                            + ", className = " + p.info.name + ", isSyncable = "
11235                                            + p.info.isSyncable);
11236                            }
11237                        } else {
11238                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11239                            Slog.w(TAG, "Skipping provider name " + names[j] +
11240                                    " (in package " + pkg.applicationInfo.packageName +
11241                                    "): name already used by "
11242                                    + ((other != null && other.getComponentName() != null)
11243                                            ? other.getComponentName().getPackageName() : "?"));
11244                        }
11245                    }
11246                }
11247                if (chatty) {
11248                    if (r == null) {
11249                        r = new StringBuilder(256);
11250                    } else {
11251                        r.append(' ');
11252                    }
11253                    r.append(p.info.name);
11254                }
11255            }
11256            if (r != null) {
11257                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11258            }
11259
11260            N = pkg.services.size();
11261            r = null;
11262            for (i=0; i<N; i++) {
11263                PackageParser.Service s = pkg.services.get(i);
11264                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11265                        s.info.processName);
11266                mServices.addService(s);
11267                if (chatty) {
11268                    if (r == null) {
11269                        r = new StringBuilder(256);
11270                    } else {
11271                        r.append(' ');
11272                    }
11273                    r.append(s.info.name);
11274                }
11275            }
11276            if (r != null) {
11277                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11278            }
11279
11280            N = pkg.receivers.size();
11281            r = null;
11282            for (i=0; i<N; i++) {
11283                PackageParser.Activity a = pkg.receivers.get(i);
11284                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11285                        a.info.processName);
11286                mReceivers.addActivity(a, "receiver");
11287                if (chatty) {
11288                    if (r == null) {
11289                        r = new StringBuilder(256);
11290                    } else {
11291                        r.append(' ');
11292                    }
11293                    r.append(a.info.name);
11294                }
11295            }
11296            if (r != null) {
11297                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11298            }
11299
11300            N = pkg.activities.size();
11301            r = null;
11302            for (i=0; i<N; i++) {
11303                PackageParser.Activity a = pkg.activities.get(i);
11304                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11305                        a.info.processName);
11306                mActivities.addActivity(a, "activity");
11307                if (chatty) {
11308                    if (r == null) {
11309                        r = new StringBuilder(256);
11310                    } else {
11311                        r.append(' ');
11312                    }
11313                    r.append(a.info.name);
11314                }
11315            }
11316            if (r != null) {
11317                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11318            }
11319
11320            N = pkg.permissionGroups.size();
11321            r = null;
11322            for (i=0; i<N; i++) {
11323                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11324                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11325                final String curPackageName = cur == null ? null : cur.info.packageName;
11326                // Dont allow ephemeral apps to define new permission groups.
11327                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11328                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11329                            + pg.info.packageName
11330                            + " ignored: instant apps cannot define new permission groups.");
11331                    continue;
11332                }
11333                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11334                if (cur == null || isPackageUpdate) {
11335                    mPermissionGroups.put(pg.info.name, pg);
11336                    if (chatty) {
11337                        if (r == null) {
11338                            r = new StringBuilder(256);
11339                        } else {
11340                            r.append(' ');
11341                        }
11342                        if (isPackageUpdate) {
11343                            r.append("UPD:");
11344                        }
11345                        r.append(pg.info.name);
11346                    }
11347                } else {
11348                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11349                            + pg.info.packageName + " ignored: original from "
11350                            + cur.info.packageName);
11351                    if (chatty) {
11352                        if (r == null) {
11353                            r = new StringBuilder(256);
11354                        } else {
11355                            r.append(' ');
11356                        }
11357                        r.append("DUP:");
11358                        r.append(pg.info.name);
11359                    }
11360                }
11361            }
11362            if (r != null) {
11363                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11364            }
11365
11366            N = pkg.permissions.size();
11367            r = null;
11368            for (i=0; i<N; i++) {
11369                PackageParser.Permission p = pkg.permissions.get(i);
11370
11371                // Dont allow ephemeral apps to define new permissions.
11372                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11373                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11374                            + p.info.packageName
11375                            + " ignored: instant apps cannot define new permissions.");
11376                    continue;
11377                }
11378
11379                // Assume by default that we did not install this permission into the system.
11380                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11381
11382                // Now that permission groups have a special meaning, we ignore permission
11383                // groups for legacy apps to prevent unexpected behavior. In particular,
11384                // permissions for one app being granted to someone just because they happen
11385                // to be in a group defined by another app (before this had no implications).
11386                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11387                    p.group = mPermissionGroups.get(p.info.group);
11388                    // Warn for a permission in an unknown group.
11389                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11390                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11391                                + p.info.packageName + " in an unknown group " + p.info.group);
11392                    }
11393                }
11394
11395                ArrayMap<String, BasePermission> permissionMap =
11396                        p.tree ? mSettings.mPermissionTrees
11397                                : mSettings.mPermissions;
11398                BasePermission bp = permissionMap.get(p.info.name);
11399
11400                // Allow system apps to redefine non-system permissions
11401                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11402                    final boolean currentOwnerIsSystem = (bp.perm != null
11403                            && isSystemApp(bp.perm.owner));
11404                    if (isSystemApp(p.owner)) {
11405                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11406                            // It's a built-in permission and no owner, take ownership now
11407                            bp.packageSetting = pkgSetting;
11408                            bp.perm = p;
11409                            bp.uid = pkg.applicationInfo.uid;
11410                            bp.sourcePackage = p.info.packageName;
11411                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11412                        } else if (!currentOwnerIsSystem) {
11413                            String msg = "New decl " + p.owner + " of permission  "
11414                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11415                            reportSettingsProblem(Log.WARN, msg);
11416                            bp = null;
11417                        }
11418                    }
11419                }
11420
11421                if (bp == null) {
11422                    bp = new BasePermission(p.info.name, p.info.packageName,
11423                            BasePermission.TYPE_NORMAL);
11424                    permissionMap.put(p.info.name, bp);
11425                }
11426
11427                if (bp.perm == null) {
11428                    if (bp.sourcePackage == null
11429                            || bp.sourcePackage.equals(p.info.packageName)) {
11430                        BasePermission tree = findPermissionTreeLP(p.info.name);
11431                        if (tree == null
11432                                || tree.sourcePackage.equals(p.info.packageName)) {
11433                            bp.packageSetting = pkgSetting;
11434                            bp.perm = p;
11435                            bp.uid = pkg.applicationInfo.uid;
11436                            bp.sourcePackage = p.info.packageName;
11437                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11438                            if (chatty) {
11439                                if (r == null) {
11440                                    r = new StringBuilder(256);
11441                                } else {
11442                                    r.append(' ');
11443                                }
11444                                r.append(p.info.name);
11445                            }
11446                        } else {
11447                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11448                                    + p.info.packageName + " ignored: base tree "
11449                                    + tree.name + " is from package "
11450                                    + tree.sourcePackage);
11451                        }
11452                    } else {
11453                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11454                                + p.info.packageName + " ignored: original from "
11455                                + bp.sourcePackage);
11456                    }
11457                } else if (chatty) {
11458                    if (r == null) {
11459                        r = new StringBuilder(256);
11460                    } else {
11461                        r.append(' ');
11462                    }
11463                    r.append("DUP:");
11464                    r.append(p.info.name);
11465                }
11466                if (bp.perm == p) {
11467                    bp.protectionLevel = p.info.protectionLevel;
11468                }
11469            }
11470
11471            if (r != null) {
11472                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11473            }
11474
11475            N = pkg.instrumentation.size();
11476            r = null;
11477            for (i=0; i<N; i++) {
11478                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11479                a.info.packageName = pkg.applicationInfo.packageName;
11480                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11481                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11482                a.info.splitNames = pkg.splitNames;
11483                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11484                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11485                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11486                a.info.dataDir = pkg.applicationInfo.dataDir;
11487                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11488                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11489                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11490                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11491                mInstrumentation.put(a.getComponentName(), a);
11492                if (chatty) {
11493                    if (r == null) {
11494                        r = new StringBuilder(256);
11495                    } else {
11496                        r.append(' ');
11497                    }
11498                    r.append(a.info.name);
11499                }
11500            }
11501            if (r != null) {
11502                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11503            }
11504
11505            if (pkg.protectedBroadcasts != null) {
11506                N = pkg.protectedBroadcasts.size();
11507                for (i=0; i<N; i++) {
11508                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11509                }
11510            }
11511        }
11512
11513        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11514    }
11515
11516    /**
11517     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11518     * is derived purely on the basis of the contents of {@code scanFile} and
11519     * {@code cpuAbiOverride}.
11520     *
11521     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11522     */
11523    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11524                                 String cpuAbiOverride, boolean extractLibs,
11525                                 File appLib32InstallDir)
11526            throws PackageManagerException {
11527        // Give ourselves some initial paths; we'll come back for another
11528        // pass once we've determined ABI below.
11529        setNativeLibraryPaths(pkg, appLib32InstallDir);
11530
11531        // We would never need to extract libs for forward-locked and external packages,
11532        // since the container service will do it for us. We shouldn't attempt to
11533        // extract libs from system app when it was not updated.
11534        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11535                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11536            extractLibs = false;
11537        }
11538
11539        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11540        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11541
11542        NativeLibraryHelper.Handle handle = null;
11543        try {
11544            handle = NativeLibraryHelper.Handle.create(pkg);
11545            // TODO(multiArch): This can be null for apps that didn't go through the
11546            // usual installation process. We can calculate it again, like we
11547            // do during install time.
11548            //
11549            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11550            // unnecessary.
11551            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11552
11553            // Null out the abis so that they can be recalculated.
11554            pkg.applicationInfo.primaryCpuAbi = null;
11555            pkg.applicationInfo.secondaryCpuAbi = null;
11556            if (isMultiArch(pkg.applicationInfo)) {
11557                // Warn if we've set an abiOverride for multi-lib packages..
11558                // By definition, we need to copy both 32 and 64 bit libraries for
11559                // such packages.
11560                if (pkg.cpuAbiOverride != null
11561                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11562                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11563                }
11564
11565                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11566                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11567                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11568                    if (extractLibs) {
11569                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11570                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11571                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11572                                useIsaSpecificSubdirs);
11573                    } else {
11574                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11575                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11576                    }
11577                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11578                }
11579
11580                maybeThrowExceptionForMultiArchCopy(
11581                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11582
11583                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11584                    if (extractLibs) {
11585                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11586                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11587                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11588                                useIsaSpecificSubdirs);
11589                    } else {
11590                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11591                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11592                    }
11593                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11594                }
11595
11596                maybeThrowExceptionForMultiArchCopy(
11597                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11598
11599                if (abi64 >= 0) {
11600                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11601                }
11602
11603                if (abi32 >= 0) {
11604                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11605                    if (abi64 >= 0) {
11606                        if (pkg.use32bitAbi) {
11607                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11608                            pkg.applicationInfo.primaryCpuAbi = abi;
11609                        } else {
11610                            pkg.applicationInfo.secondaryCpuAbi = abi;
11611                        }
11612                    } else {
11613                        pkg.applicationInfo.primaryCpuAbi = abi;
11614                    }
11615                }
11616
11617            } else {
11618                String[] abiList = (cpuAbiOverride != null) ?
11619                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11620
11621                // Enable gross and lame hacks for apps that are built with old
11622                // SDK tools. We must scan their APKs for renderscript bitcode and
11623                // not launch them if it's present. Don't bother checking on devices
11624                // that don't have 64 bit support.
11625                boolean needsRenderScriptOverride = false;
11626                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11627                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11628                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11629                    needsRenderScriptOverride = true;
11630                }
11631
11632                final int copyRet;
11633                if (extractLibs) {
11634                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11635                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11636                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11637                } else {
11638                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11639                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11640                }
11641                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11642
11643                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11644                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11645                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11646                }
11647
11648                if (copyRet >= 0) {
11649                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11650                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11651                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11652                } else if (needsRenderScriptOverride) {
11653                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11654                }
11655            }
11656        } catch (IOException ioe) {
11657            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11658        } finally {
11659            IoUtils.closeQuietly(handle);
11660        }
11661
11662        // Now that we've calculated the ABIs and determined if it's an internal app,
11663        // we will go ahead and populate the nativeLibraryPath.
11664        setNativeLibraryPaths(pkg, appLib32InstallDir);
11665    }
11666
11667    /**
11668     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11669     * i.e, so that all packages can be run inside a single process if required.
11670     *
11671     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11672     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11673     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11674     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11675     * updating a package that belongs to a shared user.
11676     *
11677     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11678     * adds unnecessary complexity.
11679     */
11680    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11681            PackageParser.Package scannedPackage) {
11682        String requiredInstructionSet = null;
11683        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11684            requiredInstructionSet = VMRuntime.getInstructionSet(
11685                     scannedPackage.applicationInfo.primaryCpuAbi);
11686        }
11687
11688        PackageSetting requirer = null;
11689        for (PackageSetting ps : packagesForUser) {
11690            // If packagesForUser contains scannedPackage, we skip it. This will happen
11691            // when scannedPackage is an update of an existing package. Without this check,
11692            // we will never be able to change the ABI of any package belonging to a shared
11693            // user, even if it's compatible with other packages.
11694            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11695                if (ps.primaryCpuAbiString == null) {
11696                    continue;
11697                }
11698
11699                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11700                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11701                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11702                    // this but there's not much we can do.
11703                    String errorMessage = "Instruction set mismatch, "
11704                            + ((requirer == null) ? "[caller]" : requirer)
11705                            + " requires " + requiredInstructionSet + " whereas " + ps
11706                            + " requires " + instructionSet;
11707                    Slog.w(TAG, errorMessage);
11708                }
11709
11710                if (requiredInstructionSet == null) {
11711                    requiredInstructionSet = instructionSet;
11712                    requirer = ps;
11713                }
11714            }
11715        }
11716
11717        if (requiredInstructionSet != null) {
11718            String adjustedAbi;
11719            if (requirer != null) {
11720                // requirer != null implies that either scannedPackage was null or that scannedPackage
11721                // did not require an ABI, in which case we have to adjust scannedPackage to match
11722                // the ABI of the set (which is the same as requirer's ABI)
11723                adjustedAbi = requirer.primaryCpuAbiString;
11724                if (scannedPackage != null) {
11725                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11726                }
11727            } else {
11728                // requirer == null implies that we're updating all ABIs in the set to
11729                // match scannedPackage.
11730                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11731            }
11732
11733            for (PackageSetting ps : packagesForUser) {
11734                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11735                    if (ps.primaryCpuAbiString != null) {
11736                        continue;
11737                    }
11738
11739                    ps.primaryCpuAbiString = adjustedAbi;
11740                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11741                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11742                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11743                        if (DEBUG_ABI_SELECTION) {
11744                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11745                                    + " (requirer="
11746                                    + (requirer != null ? requirer.pkg : "null")
11747                                    + ", scannedPackage="
11748                                    + (scannedPackage != null ? scannedPackage : "null")
11749                                    + ")");
11750                        }
11751                        try {
11752                            mInstaller.rmdex(ps.codePathString,
11753                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11754                        } catch (InstallerException ignored) {
11755                        }
11756                    }
11757                }
11758            }
11759        }
11760    }
11761
11762    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11763        synchronized (mPackages) {
11764            mResolverReplaced = true;
11765            // Set up information for custom user intent resolution activity.
11766            mResolveActivity.applicationInfo = pkg.applicationInfo;
11767            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11768            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11769            mResolveActivity.processName = pkg.applicationInfo.packageName;
11770            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11771            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11772                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11773            mResolveActivity.theme = 0;
11774            mResolveActivity.exported = true;
11775            mResolveActivity.enabled = true;
11776            mResolveInfo.activityInfo = mResolveActivity;
11777            mResolveInfo.priority = 0;
11778            mResolveInfo.preferredOrder = 0;
11779            mResolveInfo.match = 0;
11780            mResolveComponentName = mCustomResolverComponentName;
11781            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11782                    mResolveComponentName);
11783        }
11784    }
11785
11786    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11787        if (installerActivity == null) {
11788            if (DEBUG_EPHEMERAL) {
11789                Slog.d(TAG, "Clear ephemeral installer activity");
11790            }
11791            mInstantAppInstallerActivity = null;
11792            return;
11793        }
11794
11795        if (DEBUG_EPHEMERAL) {
11796            Slog.d(TAG, "Set ephemeral installer activity: "
11797                    + installerActivity.getComponentName());
11798        }
11799        // Set up information for ephemeral installer activity
11800        mInstantAppInstallerActivity = installerActivity;
11801        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11802                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11803        mInstantAppInstallerActivity.exported = true;
11804        mInstantAppInstallerActivity.enabled = true;
11805        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11806        mInstantAppInstallerInfo.priority = 0;
11807        mInstantAppInstallerInfo.preferredOrder = 1;
11808        mInstantAppInstallerInfo.isDefault = true;
11809        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11810                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11811    }
11812
11813    private static String calculateBundledApkRoot(final String codePathString) {
11814        final File codePath = new File(codePathString);
11815        final File codeRoot;
11816        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11817            codeRoot = Environment.getRootDirectory();
11818        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11819            codeRoot = Environment.getOemDirectory();
11820        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11821            codeRoot = Environment.getVendorDirectory();
11822        } else {
11823            // Unrecognized code path; take its top real segment as the apk root:
11824            // e.g. /something/app/blah.apk => /something
11825            try {
11826                File f = codePath.getCanonicalFile();
11827                File parent = f.getParentFile();    // non-null because codePath is a file
11828                File tmp;
11829                while ((tmp = parent.getParentFile()) != null) {
11830                    f = parent;
11831                    parent = tmp;
11832                }
11833                codeRoot = f;
11834                Slog.w(TAG, "Unrecognized code path "
11835                        + codePath + " - using " + codeRoot);
11836            } catch (IOException e) {
11837                // Can't canonicalize the code path -- shenanigans?
11838                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11839                return Environment.getRootDirectory().getPath();
11840            }
11841        }
11842        return codeRoot.getPath();
11843    }
11844
11845    /**
11846     * Derive and set the location of native libraries for the given package,
11847     * which varies depending on where and how the package was installed.
11848     */
11849    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11850        final ApplicationInfo info = pkg.applicationInfo;
11851        final String codePath = pkg.codePath;
11852        final File codeFile = new File(codePath);
11853        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11854        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11855
11856        info.nativeLibraryRootDir = null;
11857        info.nativeLibraryRootRequiresIsa = false;
11858        info.nativeLibraryDir = null;
11859        info.secondaryNativeLibraryDir = null;
11860
11861        if (isApkFile(codeFile)) {
11862            // Monolithic install
11863            if (bundledApp) {
11864                // If "/system/lib64/apkname" exists, assume that is the per-package
11865                // native library directory to use; otherwise use "/system/lib/apkname".
11866                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11867                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11868                        getPrimaryInstructionSet(info));
11869
11870                // This is a bundled system app so choose the path based on the ABI.
11871                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11872                // is just the default path.
11873                final String apkName = deriveCodePathName(codePath);
11874                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11875                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11876                        apkName).getAbsolutePath();
11877
11878                if (info.secondaryCpuAbi != null) {
11879                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11880                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11881                            secondaryLibDir, apkName).getAbsolutePath();
11882                }
11883            } else if (asecApp) {
11884                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11885                        .getAbsolutePath();
11886            } else {
11887                final String apkName = deriveCodePathName(codePath);
11888                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11889                        .getAbsolutePath();
11890            }
11891
11892            info.nativeLibraryRootRequiresIsa = false;
11893            info.nativeLibraryDir = info.nativeLibraryRootDir;
11894        } else {
11895            // Cluster install
11896            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11897            info.nativeLibraryRootRequiresIsa = true;
11898
11899            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11900                    getPrimaryInstructionSet(info)).getAbsolutePath();
11901
11902            if (info.secondaryCpuAbi != null) {
11903                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11904                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11905            }
11906        }
11907    }
11908
11909    /**
11910     * Calculate the abis and roots for a bundled app. These can uniquely
11911     * be determined from the contents of the system partition, i.e whether
11912     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11913     * of this information, and instead assume that the system was built
11914     * sensibly.
11915     */
11916    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11917                                           PackageSetting pkgSetting) {
11918        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11919
11920        // If "/system/lib64/apkname" exists, assume that is the per-package
11921        // native library directory to use; otherwise use "/system/lib/apkname".
11922        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11923        setBundledAppAbi(pkg, apkRoot, apkName);
11924        // pkgSetting might be null during rescan following uninstall of updates
11925        // to a bundled app, so accommodate that possibility.  The settings in
11926        // that case will be established later from the parsed package.
11927        //
11928        // If the settings aren't null, sync them up with what we've just derived.
11929        // note that apkRoot isn't stored in the package settings.
11930        if (pkgSetting != null) {
11931            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11932            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11933        }
11934    }
11935
11936    /**
11937     * Deduces the ABI of a bundled app and sets the relevant fields on the
11938     * parsed pkg object.
11939     *
11940     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11941     *        under which system libraries are installed.
11942     * @param apkName the name of the installed package.
11943     */
11944    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11945        final File codeFile = new File(pkg.codePath);
11946
11947        final boolean has64BitLibs;
11948        final boolean has32BitLibs;
11949        if (isApkFile(codeFile)) {
11950            // Monolithic install
11951            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11952            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11953        } else {
11954            // Cluster install
11955            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11956            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11957                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11958                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11959                has64BitLibs = (new File(rootDir, isa)).exists();
11960            } else {
11961                has64BitLibs = false;
11962            }
11963            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11964                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11965                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11966                has32BitLibs = (new File(rootDir, isa)).exists();
11967            } else {
11968                has32BitLibs = false;
11969            }
11970        }
11971
11972        if (has64BitLibs && !has32BitLibs) {
11973            // The package has 64 bit libs, but not 32 bit libs. Its primary
11974            // ABI should be 64 bit. We can safely assume here that the bundled
11975            // native libraries correspond to the most preferred ABI in the list.
11976
11977            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11978            pkg.applicationInfo.secondaryCpuAbi = null;
11979        } else if (has32BitLibs && !has64BitLibs) {
11980            // The package has 32 bit libs but not 64 bit libs. Its primary
11981            // ABI should be 32 bit.
11982
11983            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11984            pkg.applicationInfo.secondaryCpuAbi = null;
11985        } else if (has32BitLibs && has64BitLibs) {
11986            // The application has both 64 and 32 bit bundled libraries. We check
11987            // here that the app declares multiArch support, and warn if it doesn't.
11988            //
11989            // We will be lenient here and record both ABIs. The primary will be the
11990            // ABI that's higher on the list, i.e, a device that's configured to prefer
11991            // 64 bit apps will see a 64 bit primary ABI,
11992
11993            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11994                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11995            }
11996
11997            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11998                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11999                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12000            } else {
12001                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12002                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12003            }
12004        } else {
12005            pkg.applicationInfo.primaryCpuAbi = null;
12006            pkg.applicationInfo.secondaryCpuAbi = null;
12007        }
12008    }
12009
12010    private void killApplication(String pkgName, int appId, String reason) {
12011        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12012    }
12013
12014    private void killApplication(String pkgName, int appId, int userId, String reason) {
12015        // Request the ActivityManager to kill the process(only for existing packages)
12016        // so that we do not end up in a confused state while the user is still using the older
12017        // version of the application while the new one gets installed.
12018        final long token = Binder.clearCallingIdentity();
12019        try {
12020            IActivityManager am = ActivityManager.getService();
12021            if (am != null) {
12022                try {
12023                    am.killApplication(pkgName, appId, userId, reason);
12024                } catch (RemoteException e) {
12025                }
12026            }
12027        } finally {
12028            Binder.restoreCallingIdentity(token);
12029        }
12030    }
12031
12032    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12033        // Remove the parent package setting
12034        PackageSetting ps = (PackageSetting) pkg.mExtras;
12035        if (ps != null) {
12036            removePackageLI(ps, chatty);
12037        }
12038        // Remove the child package setting
12039        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12040        for (int i = 0; i < childCount; i++) {
12041            PackageParser.Package childPkg = pkg.childPackages.get(i);
12042            ps = (PackageSetting) childPkg.mExtras;
12043            if (ps != null) {
12044                removePackageLI(ps, chatty);
12045            }
12046        }
12047    }
12048
12049    void removePackageLI(PackageSetting ps, boolean chatty) {
12050        if (DEBUG_INSTALL) {
12051            if (chatty)
12052                Log.d(TAG, "Removing package " + ps.name);
12053        }
12054
12055        // writer
12056        synchronized (mPackages) {
12057            mPackages.remove(ps.name);
12058            final PackageParser.Package pkg = ps.pkg;
12059            if (pkg != null) {
12060                cleanPackageDataStructuresLILPw(pkg, chatty);
12061            }
12062        }
12063    }
12064
12065    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12066        if (DEBUG_INSTALL) {
12067            if (chatty)
12068                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12069        }
12070
12071        // writer
12072        synchronized (mPackages) {
12073            // Remove the parent package
12074            mPackages.remove(pkg.applicationInfo.packageName);
12075            cleanPackageDataStructuresLILPw(pkg, chatty);
12076
12077            // Remove the child packages
12078            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12079            for (int i = 0; i < childCount; i++) {
12080                PackageParser.Package childPkg = pkg.childPackages.get(i);
12081                mPackages.remove(childPkg.applicationInfo.packageName);
12082                cleanPackageDataStructuresLILPw(childPkg, chatty);
12083            }
12084        }
12085    }
12086
12087    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12088        int N = pkg.providers.size();
12089        StringBuilder r = null;
12090        int i;
12091        for (i=0; i<N; i++) {
12092            PackageParser.Provider p = pkg.providers.get(i);
12093            mProviders.removeProvider(p);
12094            if (p.info.authority == null) {
12095
12096                /* There was another ContentProvider with this authority when
12097                 * this app was installed so this authority is null,
12098                 * Ignore it as we don't have to unregister the provider.
12099                 */
12100                continue;
12101            }
12102            String names[] = p.info.authority.split(";");
12103            for (int j = 0; j < names.length; j++) {
12104                if (mProvidersByAuthority.get(names[j]) == p) {
12105                    mProvidersByAuthority.remove(names[j]);
12106                    if (DEBUG_REMOVE) {
12107                        if (chatty)
12108                            Log.d(TAG, "Unregistered content provider: " + names[j]
12109                                    + ", className = " + p.info.name + ", isSyncable = "
12110                                    + p.info.isSyncable);
12111                    }
12112                }
12113            }
12114            if (DEBUG_REMOVE && chatty) {
12115                if (r == null) {
12116                    r = new StringBuilder(256);
12117                } else {
12118                    r.append(' ');
12119                }
12120                r.append(p.info.name);
12121            }
12122        }
12123        if (r != null) {
12124            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12125        }
12126
12127        N = pkg.services.size();
12128        r = null;
12129        for (i=0; i<N; i++) {
12130            PackageParser.Service s = pkg.services.get(i);
12131            mServices.removeService(s);
12132            if (chatty) {
12133                if (r == null) {
12134                    r = new StringBuilder(256);
12135                } else {
12136                    r.append(' ');
12137                }
12138                r.append(s.info.name);
12139            }
12140        }
12141        if (r != null) {
12142            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12143        }
12144
12145        N = pkg.receivers.size();
12146        r = null;
12147        for (i=0; i<N; i++) {
12148            PackageParser.Activity a = pkg.receivers.get(i);
12149            mReceivers.removeActivity(a, "receiver");
12150            if (DEBUG_REMOVE && chatty) {
12151                if (r == null) {
12152                    r = new StringBuilder(256);
12153                } else {
12154                    r.append(' ');
12155                }
12156                r.append(a.info.name);
12157            }
12158        }
12159        if (r != null) {
12160            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12161        }
12162
12163        N = pkg.activities.size();
12164        r = null;
12165        for (i=0; i<N; i++) {
12166            PackageParser.Activity a = pkg.activities.get(i);
12167            mActivities.removeActivity(a, "activity");
12168            if (DEBUG_REMOVE && chatty) {
12169                if (r == null) {
12170                    r = new StringBuilder(256);
12171                } else {
12172                    r.append(' ');
12173                }
12174                r.append(a.info.name);
12175            }
12176        }
12177        if (r != null) {
12178            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12179        }
12180
12181        N = pkg.permissions.size();
12182        r = null;
12183        for (i=0; i<N; i++) {
12184            PackageParser.Permission p = pkg.permissions.get(i);
12185            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12186            if (bp == null) {
12187                bp = mSettings.mPermissionTrees.get(p.info.name);
12188            }
12189            if (bp != null && bp.perm == p) {
12190                bp.perm = null;
12191                if (DEBUG_REMOVE && chatty) {
12192                    if (r == null) {
12193                        r = new StringBuilder(256);
12194                    } else {
12195                        r.append(' ');
12196                    }
12197                    r.append(p.info.name);
12198                }
12199            }
12200            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12201                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12202                if (appOpPkgs != null) {
12203                    appOpPkgs.remove(pkg.packageName);
12204                }
12205            }
12206        }
12207        if (r != null) {
12208            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12209        }
12210
12211        N = pkg.requestedPermissions.size();
12212        r = null;
12213        for (i=0; i<N; i++) {
12214            String perm = pkg.requestedPermissions.get(i);
12215            BasePermission bp = mSettings.mPermissions.get(perm);
12216            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12217                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12218                if (appOpPkgs != null) {
12219                    appOpPkgs.remove(pkg.packageName);
12220                    if (appOpPkgs.isEmpty()) {
12221                        mAppOpPermissionPackages.remove(perm);
12222                    }
12223                }
12224            }
12225        }
12226        if (r != null) {
12227            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12228        }
12229
12230        N = pkg.instrumentation.size();
12231        r = null;
12232        for (i=0; i<N; i++) {
12233            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12234            mInstrumentation.remove(a.getComponentName());
12235            if (DEBUG_REMOVE && chatty) {
12236                if (r == null) {
12237                    r = new StringBuilder(256);
12238                } else {
12239                    r.append(' ');
12240                }
12241                r.append(a.info.name);
12242            }
12243        }
12244        if (r != null) {
12245            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12246        }
12247
12248        r = null;
12249        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12250            // Only system apps can hold shared libraries.
12251            if (pkg.libraryNames != null) {
12252                for (i = 0; i < pkg.libraryNames.size(); i++) {
12253                    String name = pkg.libraryNames.get(i);
12254                    if (removeSharedLibraryLPw(name, 0)) {
12255                        if (DEBUG_REMOVE && chatty) {
12256                            if (r == null) {
12257                                r = new StringBuilder(256);
12258                            } else {
12259                                r.append(' ');
12260                            }
12261                            r.append(name);
12262                        }
12263                    }
12264                }
12265            }
12266        }
12267
12268        r = null;
12269
12270        // Any package can hold static shared libraries.
12271        if (pkg.staticSharedLibName != null) {
12272            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12273                if (DEBUG_REMOVE && chatty) {
12274                    if (r == null) {
12275                        r = new StringBuilder(256);
12276                    } else {
12277                        r.append(' ');
12278                    }
12279                    r.append(pkg.staticSharedLibName);
12280                }
12281            }
12282        }
12283
12284        if (r != null) {
12285            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12286        }
12287    }
12288
12289    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12290        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12291            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12292                return true;
12293            }
12294        }
12295        return false;
12296    }
12297
12298    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12299    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12300    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12301
12302    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12303        // Update the parent permissions
12304        updatePermissionsLPw(pkg.packageName, pkg, flags);
12305        // Update the child permissions
12306        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12307        for (int i = 0; i < childCount; i++) {
12308            PackageParser.Package childPkg = pkg.childPackages.get(i);
12309            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12310        }
12311    }
12312
12313    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12314            int flags) {
12315        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12316        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12317    }
12318
12319    private void updatePermissionsLPw(String changingPkg,
12320            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12321        // Make sure there are no dangling permission trees.
12322        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12323        while (it.hasNext()) {
12324            final BasePermission bp = it.next();
12325            if (bp.packageSetting == null) {
12326                // We may not yet have parsed the package, so just see if
12327                // we still know about its settings.
12328                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12329            }
12330            if (bp.packageSetting == null) {
12331                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12332                        + " from package " + bp.sourcePackage);
12333                it.remove();
12334            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12335                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12336                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12337                            + " from package " + bp.sourcePackage);
12338                    flags |= UPDATE_PERMISSIONS_ALL;
12339                    it.remove();
12340                }
12341            }
12342        }
12343
12344        // Make sure all dynamic permissions have been assigned to a package,
12345        // and make sure there are no dangling permissions.
12346        it = mSettings.mPermissions.values().iterator();
12347        while (it.hasNext()) {
12348            final BasePermission bp = it.next();
12349            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12350                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12351                        + bp.name + " pkg=" + bp.sourcePackage
12352                        + " info=" + bp.pendingInfo);
12353                if (bp.packageSetting == null && bp.pendingInfo != null) {
12354                    final BasePermission tree = findPermissionTreeLP(bp.name);
12355                    if (tree != null && tree.perm != null) {
12356                        bp.packageSetting = tree.packageSetting;
12357                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12358                                new PermissionInfo(bp.pendingInfo));
12359                        bp.perm.info.packageName = tree.perm.info.packageName;
12360                        bp.perm.info.name = bp.name;
12361                        bp.uid = tree.uid;
12362                    }
12363                }
12364            }
12365            if (bp.packageSetting == null) {
12366                // We may not yet have parsed the package, so just see if
12367                // we still know about its settings.
12368                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12369            }
12370            if (bp.packageSetting == null) {
12371                Slog.w(TAG, "Removing dangling permission: " + bp.name
12372                        + " from package " + bp.sourcePackage);
12373                it.remove();
12374            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12375                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12376                    Slog.i(TAG, "Removing old permission: " + bp.name
12377                            + " from package " + bp.sourcePackage);
12378                    flags |= UPDATE_PERMISSIONS_ALL;
12379                    it.remove();
12380                }
12381            }
12382        }
12383
12384        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12385        // Now update the permissions for all packages, in particular
12386        // replace the granted permissions of the system packages.
12387        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12388            for (PackageParser.Package pkg : mPackages.values()) {
12389                if (pkg != pkgInfo) {
12390                    // Only replace for packages on requested volume
12391                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12392                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12393                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12394                    grantPermissionsLPw(pkg, replace, changingPkg);
12395                }
12396            }
12397        }
12398
12399        if (pkgInfo != null) {
12400            // Only replace for packages on requested volume
12401            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12402            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12403                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12404            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12405        }
12406        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12407    }
12408
12409    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12410            String packageOfInterest) {
12411        // IMPORTANT: There are two types of permissions: install and runtime.
12412        // Install time permissions are granted when the app is installed to
12413        // all device users and users added in the future. Runtime permissions
12414        // are granted at runtime explicitly to specific users. Normal and signature
12415        // protected permissions are install time permissions. Dangerous permissions
12416        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12417        // otherwise they are runtime permissions. This function does not manage
12418        // runtime permissions except for the case an app targeting Lollipop MR1
12419        // being upgraded to target a newer SDK, in which case dangerous permissions
12420        // are transformed from install time to runtime ones.
12421
12422        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12423        if (ps == null) {
12424            return;
12425        }
12426
12427        PermissionsState permissionsState = ps.getPermissionsState();
12428        PermissionsState origPermissions = permissionsState;
12429
12430        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12431
12432        boolean runtimePermissionsRevoked = false;
12433        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12434
12435        boolean changedInstallPermission = false;
12436
12437        if (replace) {
12438            ps.installPermissionsFixed = false;
12439            if (!ps.isSharedUser()) {
12440                origPermissions = new PermissionsState(permissionsState);
12441                permissionsState.reset();
12442            } else {
12443                // We need to know only about runtime permission changes since the
12444                // calling code always writes the install permissions state but
12445                // the runtime ones are written only if changed. The only cases of
12446                // changed runtime permissions here are promotion of an install to
12447                // runtime and revocation of a runtime from a shared user.
12448                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12449                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12450                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12451                    runtimePermissionsRevoked = true;
12452                }
12453            }
12454        }
12455
12456        permissionsState.setGlobalGids(mGlobalGids);
12457
12458        final int N = pkg.requestedPermissions.size();
12459        for (int i=0; i<N; i++) {
12460            final String name = pkg.requestedPermissions.get(i);
12461            final BasePermission bp = mSettings.mPermissions.get(name);
12462            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12463                    >= Build.VERSION_CODES.M;
12464
12465            if (DEBUG_INSTALL) {
12466                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12467            }
12468
12469            if (bp == null || bp.packageSetting == null) {
12470                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12471                    if (DEBUG_PERMISSIONS) {
12472                        Slog.i(TAG, "Unknown permission " + name
12473                                + " in package " + pkg.packageName);
12474                    }
12475                }
12476                continue;
12477            }
12478
12479
12480            // Limit ephemeral apps to ephemeral allowed permissions.
12481            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12482                if (DEBUG_PERMISSIONS) {
12483                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12484                            + pkg.packageName);
12485                }
12486                continue;
12487            }
12488
12489            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12490                if (DEBUG_PERMISSIONS) {
12491                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12492                            + pkg.packageName);
12493                }
12494                continue;
12495            }
12496
12497            final String perm = bp.name;
12498            boolean allowedSig = false;
12499            int grant = GRANT_DENIED;
12500
12501            // Keep track of app op permissions.
12502            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12503                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12504                if (pkgs == null) {
12505                    pkgs = new ArraySet<>();
12506                    mAppOpPermissionPackages.put(bp.name, pkgs);
12507                }
12508                pkgs.add(pkg.packageName);
12509            }
12510
12511            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12512            switch (level) {
12513                case PermissionInfo.PROTECTION_NORMAL: {
12514                    // For all apps normal permissions are install time ones.
12515                    grant = GRANT_INSTALL;
12516                } break;
12517
12518                case PermissionInfo.PROTECTION_DANGEROUS: {
12519                    // If a permission review is required for legacy apps we represent
12520                    // their permissions as always granted runtime ones since we need
12521                    // to keep the review required permission flag per user while an
12522                    // install permission's state is shared across all users.
12523                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12524                        // For legacy apps dangerous permissions are install time ones.
12525                        grant = GRANT_INSTALL;
12526                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12527                        // For legacy apps that became modern, install becomes runtime.
12528                        grant = GRANT_UPGRADE;
12529                    } else if (mPromoteSystemApps
12530                            && isSystemApp(ps)
12531                            && mExistingSystemPackages.contains(ps.name)) {
12532                        // For legacy system apps, install becomes runtime.
12533                        // We cannot check hasInstallPermission() for system apps since those
12534                        // permissions were granted implicitly and not persisted pre-M.
12535                        grant = GRANT_UPGRADE;
12536                    } else {
12537                        // For modern apps keep runtime permissions unchanged.
12538                        grant = GRANT_RUNTIME;
12539                    }
12540                } break;
12541
12542                case PermissionInfo.PROTECTION_SIGNATURE: {
12543                    // For all apps signature permissions are install time ones.
12544                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12545                    if (allowedSig) {
12546                        grant = GRANT_INSTALL;
12547                    }
12548                } break;
12549            }
12550
12551            if (DEBUG_PERMISSIONS) {
12552                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12553            }
12554
12555            if (grant != GRANT_DENIED) {
12556                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12557                    // If this is an existing, non-system package, then
12558                    // we can't add any new permissions to it.
12559                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12560                        // Except...  if this is a permission that was added
12561                        // to the platform (note: need to only do this when
12562                        // updating the platform).
12563                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12564                            grant = GRANT_DENIED;
12565                        }
12566                    }
12567                }
12568
12569                switch (grant) {
12570                    case GRANT_INSTALL: {
12571                        // Revoke this as runtime permission to handle the case of
12572                        // a runtime permission being downgraded to an install one.
12573                        // Also in permission review mode we keep dangerous permissions
12574                        // for legacy apps
12575                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12576                            if (origPermissions.getRuntimePermissionState(
12577                                    bp.name, userId) != null) {
12578                                // Revoke the runtime permission and clear the flags.
12579                                origPermissions.revokeRuntimePermission(bp, userId);
12580                                origPermissions.updatePermissionFlags(bp, userId,
12581                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12582                                // If we revoked a permission permission, we have to write.
12583                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12584                                        changedRuntimePermissionUserIds, userId);
12585                            }
12586                        }
12587                        // Grant an install permission.
12588                        if (permissionsState.grantInstallPermission(bp) !=
12589                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12590                            changedInstallPermission = true;
12591                        }
12592                    } break;
12593
12594                    case GRANT_RUNTIME: {
12595                        // Grant previously granted runtime permissions.
12596                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12597                            PermissionState permissionState = origPermissions
12598                                    .getRuntimePermissionState(bp.name, userId);
12599                            int flags = permissionState != null
12600                                    ? permissionState.getFlags() : 0;
12601                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12602                                // Don't propagate the permission in a permission review mode if
12603                                // the former was revoked, i.e. marked to not propagate on upgrade.
12604                                // Note that in a permission review mode install permissions are
12605                                // represented as constantly granted runtime ones since we need to
12606                                // keep a per user state associated with the permission. Also the
12607                                // revoke on upgrade flag is no longer applicable and is reset.
12608                                final boolean revokeOnUpgrade = (flags & PackageManager
12609                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12610                                if (revokeOnUpgrade) {
12611                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12612                                    // Since we changed the flags, we have to write.
12613                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12614                                            changedRuntimePermissionUserIds, userId);
12615                                }
12616                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12617                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12618                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12619                                        // If we cannot put the permission as it was,
12620                                        // we have to write.
12621                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12622                                                changedRuntimePermissionUserIds, userId);
12623                                    }
12624                                }
12625
12626                                // If the app supports runtime permissions no need for a review.
12627                                if (mPermissionReviewRequired
12628                                        && appSupportsRuntimePermissions
12629                                        && (flags & PackageManager
12630                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12631                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12632                                    // Since we changed the flags, we have to write.
12633                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12634                                            changedRuntimePermissionUserIds, userId);
12635                                }
12636                            } else if (mPermissionReviewRequired
12637                                    && !appSupportsRuntimePermissions) {
12638                                // For legacy apps that need a permission review, every new
12639                                // runtime permission is granted but it is pending a review.
12640                                // We also need to review only platform defined runtime
12641                                // permissions as these are the only ones the platform knows
12642                                // how to disable the API to simulate revocation as legacy
12643                                // apps don't expect to run with revoked permissions.
12644                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12645                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12646                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12647                                        // We changed the flags, hence have to write.
12648                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12649                                                changedRuntimePermissionUserIds, userId);
12650                                    }
12651                                }
12652                                if (permissionsState.grantRuntimePermission(bp, userId)
12653                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12654                                    // We changed the permission, hence have to write.
12655                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12656                                            changedRuntimePermissionUserIds, userId);
12657                                }
12658                            }
12659                            // Propagate the permission flags.
12660                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12661                        }
12662                    } break;
12663
12664                    case GRANT_UPGRADE: {
12665                        // Grant runtime permissions for a previously held install permission.
12666                        PermissionState permissionState = origPermissions
12667                                .getInstallPermissionState(bp.name);
12668                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12669
12670                        if (origPermissions.revokeInstallPermission(bp)
12671                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12672                            // We will be transferring the permission flags, so clear them.
12673                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12674                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12675                            changedInstallPermission = true;
12676                        }
12677
12678                        // If the permission is not to be promoted to runtime we ignore it and
12679                        // also its other flags as they are not applicable to install permissions.
12680                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12681                            for (int userId : currentUserIds) {
12682                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12683                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12684                                    // Transfer the permission flags.
12685                                    permissionsState.updatePermissionFlags(bp, userId,
12686                                            flags, flags);
12687                                    // If we granted the permission, we have to write.
12688                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12689                                            changedRuntimePermissionUserIds, userId);
12690                                }
12691                            }
12692                        }
12693                    } break;
12694
12695                    default: {
12696                        if (packageOfInterest == null
12697                                || packageOfInterest.equals(pkg.packageName)) {
12698                            if (DEBUG_PERMISSIONS) {
12699                                Slog.i(TAG, "Not granting permission " + perm
12700                                        + " to package " + pkg.packageName
12701                                        + " because it was previously installed without");
12702                            }
12703                        }
12704                    } break;
12705                }
12706            } else {
12707                if (permissionsState.revokeInstallPermission(bp) !=
12708                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12709                    // Also drop the permission flags.
12710                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12711                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12712                    changedInstallPermission = true;
12713                    Slog.i(TAG, "Un-granting permission " + perm
12714                            + " from package " + pkg.packageName
12715                            + " (protectionLevel=" + bp.protectionLevel
12716                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12717                            + ")");
12718                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12719                    // Don't print warning for app op permissions, since it is fine for them
12720                    // not to be granted, there is a UI for the user to decide.
12721                    if (DEBUG_PERMISSIONS
12722                            && (packageOfInterest == null
12723                                    || packageOfInterest.equals(pkg.packageName))) {
12724                        Slog.i(TAG, "Not granting permission " + perm
12725                                + " to package " + pkg.packageName
12726                                + " (protectionLevel=" + bp.protectionLevel
12727                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12728                                + ")");
12729                    }
12730                }
12731            }
12732        }
12733
12734        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12735                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12736            // This is the first that we have heard about this package, so the
12737            // permissions we have now selected are fixed until explicitly
12738            // changed.
12739            ps.installPermissionsFixed = true;
12740        }
12741
12742        // Persist the runtime permissions state for users with changes. If permissions
12743        // were revoked because no app in the shared user declares them we have to
12744        // write synchronously to avoid losing runtime permissions state.
12745        for (int userId : changedRuntimePermissionUserIds) {
12746            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12747        }
12748    }
12749
12750    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12751        boolean allowed = false;
12752        final int NP = PackageParser.NEW_PERMISSIONS.length;
12753        for (int ip=0; ip<NP; ip++) {
12754            final PackageParser.NewPermissionInfo npi
12755                    = PackageParser.NEW_PERMISSIONS[ip];
12756            if (npi.name.equals(perm)
12757                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12758                allowed = true;
12759                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12760                        + pkg.packageName);
12761                break;
12762            }
12763        }
12764        return allowed;
12765    }
12766
12767    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12768            BasePermission bp, PermissionsState origPermissions) {
12769        boolean privilegedPermission = (bp.protectionLevel
12770                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12771        boolean privappPermissionsDisable =
12772                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12773        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12774        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12775        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12776                && !platformPackage && platformPermission) {
12777            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12778                    .getPrivAppPermissions(pkg.packageName);
12779            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12780            if (!whitelisted) {
12781                Slog.w(TAG, "Privileged permission " + perm + " for package "
12782                        + pkg.packageName + " - not in privapp-permissions whitelist");
12783                // Only report violations for apps on system image
12784                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12785                    if (mPrivappPermissionsViolations == null) {
12786                        mPrivappPermissionsViolations = new ArraySet<>();
12787                    }
12788                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12789                }
12790                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12791                    return false;
12792                }
12793            }
12794        }
12795        boolean allowed = (compareSignatures(
12796                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12797                        == PackageManager.SIGNATURE_MATCH)
12798                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12799                        == PackageManager.SIGNATURE_MATCH);
12800        if (!allowed && privilegedPermission) {
12801            if (isSystemApp(pkg)) {
12802                // For updated system applications, a system permission
12803                // is granted only if it had been defined by the original application.
12804                if (pkg.isUpdatedSystemApp()) {
12805                    final PackageSetting sysPs = mSettings
12806                            .getDisabledSystemPkgLPr(pkg.packageName);
12807                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12808                        // If the original was granted this permission, we take
12809                        // that grant decision as read and propagate it to the
12810                        // update.
12811                        if (sysPs.isPrivileged()) {
12812                            allowed = true;
12813                        }
12814                    } else {
12815                        // The system apk may have been updated with an older
12816                        // version of the one on the data partition, but which
12817                        // granted a new system permission that it didn't have
12818                        // before.  In this case we do want to allow the app to
12819                        // now get the new permission if the ancestral apk is
12820                        // privileged to get it.
12821                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12822                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12823                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12824                                    allowed = true;
12825                                    break;
12826                                }
12827                            }
12828                        }
12829                        // Also if a privileged parent package on the system image or any of
12830                        // its children requested a privileged permission, the updated child
12831                        // packages can also get the permission.
12832                        if (pkg.parentPackage != null) {
12833                            final PackageSetting disabledSysParentPs = mSettings
12834                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12835                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12836                                    && disabledSysParentPs.isPrivileged()) {
12837                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12838                                    allowed = true;
12839                                } else if (disabledSysParentPs.pkg.childPackages != null) {
12840                                    final int count = disabledSysParentPs.pkg.childPackages.size();
12841                                    for (int i = 0; i < count; i++) {
12842                                        PackageParser.Package disabledSysChildPkg =
12843                                                disabledSysParentPs.pkg.childPackages.get(i);
12844                                        if (isPackageRequestingPermission(disabledSysChildPkg,
12845                                                perm)) {
12846                                            allowed = true;
12847                                            break;
12848                                        }
12849                                    }
12850                                }
12851                            }
12852                        }
12853                    }
12854                } else {
12855                    allowed = isPrivilegedApp(pkg);
12856                }
12857            }
12858        }
12859        if (!allowed) {
12860            if (!allowed && (bp.protectionLevel
12861                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12862                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12863                // If this was a previously normal/dangerous permission that got moved
12864                // to a system permission as part of the runtime permission redesign, then
12865                // we still want to blindly grant it to old apps.
12866                allowed = true;
12867            }
12868            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12869                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12870                // If this permission is to be granted to the system installer and
12871                // this app is an installer, then it gets the permission.
12872                allowed = true;
12873            }
12874            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12875                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12876                // If this permission is to be granted to the system verifier and
12877                // this app is a verifier, then it gets the permission.
12878                allowed = true;
12879            }
12880            if (!allowed && (bp.protectionLevel
12881                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12882                    && isSystemApp(pkg)) {
12883                // Any pre-installed system app is allowed to get this permission.
12884                allowed = true;
12885            }
12886            if (!allowed && (bp.protectionLevel
12887                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12888                // For development permissions, a development permission
12889                // is granted only if it was already granted.
12890                allowed = origPermissions.hasInstallPermission(perm);
12891            }
12892            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12893                    && pkg.packageName.equals(mSetupWizardPackage)) {
12894                // If this permission is to be granted to the system setup wizard and
12895                // this app is a setup wizard, then it gets the permission.
12896                allowed = true;
12897            }
12898        }
12899        return allowed;
12900    }
12901
12902    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12903        final int permCount = pkg.requestedPermissions.size();
12904        for (int j = 0; j < permCount; j++) {
12905            String requestedPermission = pkg.requestedPermissions.get(j);
12906            if (permission.equals(requestedPermission)) {
12907                return true;
12908            }
12909        }
12910        return false;
12911    }
12912
12913    final class ActivityIntentResolver
12914            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12915        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12916                boolean defaultOnly, int userId) {
12917            if (!sUserManager.exists(userId)) return null;
12918            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12919            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12920        }
12921
12922        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12923                int userId) {
12924            if (!sUserManager.exists(userId)) return null;
12925            mFlags = flags;
12926            return super.queryIntent(intent, resolvedType,
12927                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12928                    userId);
12929        }
12930
12931        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12932                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12933            if (!sUserManager.exists(userId)) return null;
12934            if (packageActivities == null) {
12935                return null;
12936            }
12937            mFlags = flags;
12938            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12939            final int N = packageActivities.size();
12940            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12941                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12942
12943            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12944            for (int i = 0; i < N; ++i) {
12945                intentFilters = packageActivities.get(i).intents;
12946                if (intentFilters != null && intentFilters.size() > 0) {
12947                    PackageParser.ActivityIntentInfo[] array =
12948                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12949                    intentFilters.toArray(array);
12950                    listCut.add(array);
12951                }
12952            }
12953            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12954        }
12955
12956        /**
12957         * Finds a privileged activity that matches the specified activity names.
12958         */
12959        private PackageParser.Activity findMatchingActivity(
12960                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12961            for (PackageParser.Activity sysActivity : activityList) {
12962                if (sysActivity.info.name.equals(activityInfo.name)) {
12963                    return sysActivity;
12964                }
12965                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12966                    return sysActivity;
12967                }
12968                if (sysActivity.info.targetActivity != null) {
12969                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12970                        return sysActivity;
12971                    }
12972                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12973                        return sysActivity;
12974                    }
12975                }
12976            }
12977            return null;
12978        }
12979
12980        public class IterGenerator<E> {
12981            public Iterator<E> generate(ActivityIntentInfo info) {
12982                return null;
12983            }
12984        }
12985
12986        public class ActionIterGenerator extends IterGenerator<String> {
12987            @Override
12988            public Iterator<String> generate(ActivityIntentInfo info) {
12989                return info.actionsIterator();
12990            }
12991        }
12992
12993        public class CategoriesIterGenerator extends IterGenerator<String> {
12994            @Override
12995            public Iterator<String> generate(ActivityIntentInfo info) {
12996                return info.categoriesIterator();
12997            }
12998        }
12999
13000        public class SchemesIterGenerator extends IterGenerator<String> {
13001            @Override
13002            public Iterator<String> generate(ActivityIntentInfo info) {
13003                return info.schemesIterator();
13004            }
13005        }
13006
13007        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
13008            @Override
13009            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
13010                return info.authoritiesIterator();
13011            }
13012        }
13013
13014        /**
13015         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
13016         * MODIFIED. Do not pass in a list that should not be changed.
13017         */
13018        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
13019                IterGenerator<T> generator, Iterator<T> searchIterator) {
13020            // loop through the set of actions; every one must be found in the intent filter
13021            while (searchIterator.hasNext()) {
13022                // we must have at least one filter in the list to consider a match
13023                if (intentList.size() == 0) {
13024                    break;
13025                }
13026
13027                final T searchAction = searchIterator.next();
13028
13029                // loop through the set of intent filters
13030                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
13031                while (intentIter.hasNext()) {
13032                    final ActivityIntentInfo intentInfo = intentIter.next();
13033                    boolean selectionFound = false;
13034
13035                    // loop through the intent filter's selection criteria; at least one
13036                    // of them must match the searched criteria
13037                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
13038                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
13039                        final T intentSelection = intentSelectionIter.next();
13040                        if (intentSelection != null && intentSelection.equals(searchAction)) {
13041                            selectionFound = true;
13042                            break;
13043                        }
13044                    }
13045
13046                    // the selection criteria wasn't found in this filter's set; this filter
13047                    // is not a potential match
13048                    if (!selectionFound) {
13049                        intentIter.remove();
13050                    }
13051                }
13052            }
13053        }
13054
13055        private boolean isProtectedAction(ActivityIntentInfo filter) {
13056            final Iterator<String> actionsIter = filter.actionsIterator();
13057            while (actionsIter != null && actionsIter.hasNext()) {
13058                final String filterAction = actionsIter.next();
13059                if (PROTECTED_ACTIONS.contains(filterAction)) {
13060                    return true;
13061                }
13062            }
13063            return false;
13064        }
13065
13066        /**
13067         * Adjusts the priority of the given intent filter according to policy.
13068         * <p>
13069         * <ul>
13070         * <li>The priority for non privileged applications is capped to '0'</li>
13071         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13072         * <li>The priority for unbundled updates to privileged applications is capped to the
13073         *      priority defined on the system partition</li>
13074         * </ul>
13075         * <p>
13076         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13077         * allowed to obtain any priority on any action.
13078         */
13079        private void adjustPriority(
13080                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13081            // nothing to do; priority is fine as-is
13082            if (intent.getPriority() <= 0) {
13083                return;
13084            }
13085
13086            final ActivityInfo activityInfo = intent.activity.info;
13087            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13088
13089            final boolean privilegedApp =
13090                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13091            if (!privilegedApp) {
13092                // non-privileged applications can never define a priority >0
13093                if (DEBUG_FILTERS) {
13094                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13095                            + " package: " + applicationInfo.packageName
13096                            + " activity: " + intent.activity.className
13097                            + " origPrio: " + intent.getPriority());
13098                }
13099                intent.setPriority(0);
13100                return;
13101            }
13102
13103            if (systemActivities == null) {
13104                // the system package is not disabled; we're parsing the system partition
13105                if (isProtectedAction(intent)) {
13106                    if (mDeferProtectedFilters) {
13107                        // We can't deal with these just yet. No component should ever obtain a
13108                        // >0 priority for a protected actions, with ONE exception -- the setup
13109                        // wizard. The setup wizard, however, cannot be known until we're able to
13110                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13111                        // until all intent filters have been processed. Chicken, meet egg.
13112                        // Let the filter temporarily have a high priority and rectify the
13113                        // priorities after all system packages have been scanned.
13114                        mProtectedFilters.add(intent);
13115                        if (DEBUG_FILTERS) {
13116                            Slog.i(TAG, "Protected action; save for later;"
13117                                    + " package: " + applicationInfo.packageName
13118                                    + " activity: " + intent.activity.className
13119                                    + " origPrio: " + intent.getPriority());
13120                        }
13121                        return;
13122                    } else {
13123                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13124                            Slog.i(TAG, "No setup wizard;"
13125                                + " All protected intents capped to priority 0");
13126                        }
13127                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13128                            if (DEBUG_FILTERS) {
13129                                Slog.i(TAG, "Found setup wizard;"
13130                                    + " allow priority " + intent.getPriority() + ";"
13131                                    + " package: " + intent.activity.info.packageName
13132                                    + " activity: " + intent.activity.className
13133                                    + " priority: " + intent.getPriority());
13134                            }
13135                            // setup wizard gets whatever it wants
13136                            return;
13137                        }
13138                        if (DEBUG_FILTERS) {
13139                            Slog.i(TAG, "Protected action; cap priority to 0;"
13140                                    + " package: " + intent.activity.info.packageName
13141                                    + " activity: " + intent.activity.className
13142                                    + " origPrio: " + intent.getPriority());
13143                        }
13144                        intent.setPriority(0);
13145                        return;
13146                    }
13147                }
13148                // privileged apps on the system image get whatever priority they request
13149                return;
13150            }
13151
13152            // privileged app unbundled update ... try to find the same activity
13153            final PackageParser.Activity foundActivity =
13154                    findMatchingActivity(systemActivities, activityInfo);
13155            if (foundActivity == null) {
13156                // this is a new activity; it cannot obtain >0 priority
13157                if (DEBUG_FILTERS) {
13158                    Slog.i(TAG, "New activity; cap priority to 0;"
13159                            + " package: " + applicationInfo.packageName
13160                            + " activity: " + intent.activity.className
13161                            + " origPrio: " + intent.getPriority());
13162                }
13163                intent.setPriority(0);
13164                return;
13165            }
13166
13167            // found activity, now check for filter equivalence
13168
13169            // a shallow copy is enough; we modify the list, not its contents
13170            final List<ActivityIntentInfo> intentListCopy =
13171                    new ArrayList<>(foundActivity.intents);
13172            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13173
13174            // find matching action subsets
13175            final Iterator<String> actionsIterator = intent.actionsIterator();
13176            if (actionsIterator != null) {
13177                getIntentListSubset(
13178                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13179                if (intentListCopy.size() == 0) {
13180                    // no more intents to match; we're not equivalent
13181                    if (DEBUG_FILTERS) {
13182                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13183                                + " package: " + applicationInfo.packageName
13184                                + " activity: " + intent.activity.className
13185                                + " origPrio: " + intent.getPriority());
13186                    }
13187                    intent.setPriority(0);
13188                    return;
13189                }
13190            }
13191
13192            // find matching category subsets
13193            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13194            if (categoriesIterator != null) {
13195                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13196                        categoriesIterator);
13197                if (intentListCopy.size() == 0) {
13198                    // no more intents to match; we're not equivalent
13199                    if (DEBUG_FILTERS) {
13200                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13201                                + " package: " + applicationInfo.packageName
13202                                + " activity: " + intent.activity.className
13203                                + " origPrio: " + intent.getPriority());
13204                    }
13205                    intent.setPriority(0);
13206                    return;
13207                }
13208            }
13209
13210            // find matching schemes subsets
13211            final Iterator<String> schemesIterator = intent.schemesIterator();
13212            if (schemesIterator != null) {
13213                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13214                        schemesIterator);
13215                if (intentListCopy.size() == 0) {
13216                    // no more intents to match; we're not equivalent
13217                    if (DEBUG_FILTERS) {
13218                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13219                                + " package: " + applicationInfo.packageName
13220                                + " activity: " + intent.activity.className
13221                                + " origPrio: " + intent.getPriority());
13222                    }
13223                    intent.setPriority(0);
13224                    return;
13225                }
13226            }
13227
13228            // find matching authorities subsets
13229            final Iterator<IntentFilter.AuthorityEntry>
13230                    authoritiesIterator = intent.authoritiesIterator();
13231            if (authoritiesIterator != null) {
13232                getIntentListSubset(intentListCopy,
13233                        new AuthoritiesIterGenerator(),
13234                        authoritiesIterator);
13235                if (intentListCopy.size() == 0) {
13236                    // no more intents to match; we're not equivalent
13237                    if (DEBUG_FILTERS) {
13238                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13239                                + " package: " + applicationInfo.packageName
13240                                + " activity: " + intent.activity.className
13241                                + " origPrio: " + intent.getPriority());
13242                    }
13243                    intent.setPriority(0);
13244                    return;
13245                }
13246            }
13247
13248            // we found matching filter(s); app gets the max priority of all intents
13249            int cappedPriority = 0;
13250            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13251                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13252            }
13253            if (intent.getPriority() > cappedPriority) {
13254                if (DEBUG_FILTERS) {
13255                    Slog.i(TAG, "Found matching filter(s);"
13256                            + " cap priority to " + cappedPriority + ";"
13257                            + " package: " + applicationInfo.packageName
13258                            + " activity: " + intent.activity.className
13259                            + " origPrio: " + intent.getPriority());
13260                }
13261                intent.setPriority(cappedPriority);
13262                return;
13263            }
13264            // all this for nothing; the requested priority was <= what was on the system
13265        }
13266
13267        public final void addActivity(PackageParser.Activity a, String type) {
13268            mActivities.put(a.getComponentName(), a);
13269            if (DEBUG_SHOW_INFO)
13270                Log.v(
13271                TAG, "  " + type + " " +
13272                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13273            if (DEBUG_SHOW_INFO)
13274                Log.v(TAG, "    Class=" + a.info.name);
13275            final int NI = a.intents.size();
13276            for (int j=0; j<NI; j++) {
13277                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13278                if ("activity".equals(type)) {
13279                    final PackageSetting ps =
13280                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13281                    final List<PackageParser.Activity> systemActivities =
13282                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13283                    adjustPriority(systemActivities, intent);
13284                }
13285                if (DEBUG_SHOW_INFO) {
13286                    Log.v(TAG, "    IntentFilter:");
13287                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13288                }
13289                if (!intent.debugCheck()) {
13290                    Log.w(TAG, "==> For Activity " + a.info.name);
13291                }
13292                addFilter(intent);
13293            }
13294        }
13295
13296        public final void removeActivity(PackageParser.Activity a, String type) {
13297            mActivities.remove(a.getComponentName());
13298            if (DEBUG_SHOW_INFO) {
13299                Log.v(TAG, "  " + type + " "
13300                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13301                                : a.info.name) + ":");
13302                Log.v(TAG, "    Class=" + a.info.name);
13303            }
13304            final int NI = a.intents.size();
13305            for (int j=0; j<NI; j++) {
13306                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13307                if (DEBUG_SHOW_INFO) {
13308                    Log.v(TAG, "    IntentFilter:");
13309                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13310                }
13311                removeFilter(intent);
13312            }
13313        }
13314
13315        @Override
13316        protected boolean allowFilterResult(
13317                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13318            ActivityInfo filterAi = filter.activity.info;
13319            for (int i=dest.size()-1; i>=0; i--) {
13320                ActivityInfo destAi = dest.get(i).activityInfo;
13321                if (destAi.name == filterAi.name
13322                        && destAi.packageName == filterAi.packageName) {
13323                    return false;
13324                }
13325            }
13326            return true;
13327        }
13328
13329        @Override
13330        protected ActivityIntentInfo[] newArray(int size) {
13331            return new ActivityIntentInfo[size];
13332        }
13333
13334        @Override
13335        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13336            if (!sUserManager.exists(userId)) return true;
13337            PackageParser.Package p = filter.activity.owner;
13338            if (p != null) {
13339                PackageSetting ps = (PackageSetting)p.mExtras;
13340                if (ps != null) {
13341                    // System apps are never considered stopped for purposes of
13342                    // filtering, because there may be no way for the user to
13343                    // actually re-launch them.
13344                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13345                            && ps.getStopped(userId);
13346                }
13347            }
13348            return false;
13349        }
13350
13351        @Override
13352        protected boolean isPackageForFilter(String packageName,
13353                PackageParser.ActivityIntentInfo info) {
13354            return packageName.equals(info.activity.owner.packageName);
13355        }
13356
13357        @Override
13358        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13359                int match, int userId) {
13360            if (!sUserManager.exists(userId)) return null;
13361            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13362                return null;
13363            }
13364            final PackageParser.Activity activity = info.activity;
13365            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13366            if (ps == null) {
13367                return null;
13368            }
13369            final PackageUserState userState = ps.readUserState(userId);
13370            ActivityInfo ai = generateActivityInfo(activity, mFlags, userState, userId);
13371            if (ai == null) {
13372                return null;
13373            }
13374            final boolean matchExplicitlyVisibleOnly =
13375                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13376            final boolean matchVisibleToInstantApp =
13377                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13378            final boolean componentVisible =
13379                    matchVisibleToInstantApp
13380                    && info.isVisibleToInstantApp()
13381                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13382            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13383            // throw out filters that aren't visible to ephemeral apps
13384            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13385                return null;
13386            }
13387            // throw out instant app filters if we're not explicitly requesting them
13388            if (!matchInstantApp && userState.instantApp) {
13389                return null;
13390            }
13391            // throw out instant app filters if updates are available; will trigger
13392            // instant app resolution
13393            if (userState.instantApp && ps.isUpdateAvailable()) {
13394                return null;
13395            }
13396            final ResolveInfo res = new ResolveInfo();
13397            res.activityInfo = ai;
13398            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13399                res.filter = info;
13400            }
13401            if (info != null) {
13402                res.handleAllWebDataURI = info.handleAllWebDataURI();
13403            }
13404            res.priority = info.getPriority();
13405            res.preferredOrder = activity.owner.mPreferredOrder;
13406            //System.out.println("Result: " + res.activityInfo.className +
13407            //                   " = " + res.priority);
13408            res.match = match;
13409            res.isDefault = info.hasDefault;
13410            res.labelRes = info.labelRes;
13411            res.nonLocalizedLabel = info.nonLocalizedLabel;
13412            if (userNeedsBadging(userId)) {
13413                res.noResourceId = true;
13414            } else {
13415                res.icon = info.icon;
13416            }
13417            res.iconResourceId = info.icon;
13418            res.system = res.activityInfo.applicationInfo.isSystemApp();
13419            res.isInstantAppAvailable = userState.instantApp;
13420            return res;
13421        }
13422
13423        @Override
13424        protected void sortResults(List<ResolveInfo> results) {
13425            Collections.sort(results, mResolvePrioritySorter);
13426        }
13427
13428        @Override
13429        protected void dumpFilter(PrintWriter out, String prefix,
13430                PackageParser.ActivityIntentInfo filter) {
13431            out.print(prefix); out.print(
13432                    Integer.toHexString(System.identityHashCode(filter.activity)));
13433                    out.print(' ');
13434                    filter.activity.printComponentShortName(out);
13435                    out.print(" filter ");
13436                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13437        }
13438
13439        @Override
13440        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13441            return filter.activity;
13442        }
13443
13444        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13445            PackageParser.Activity activity = (PackageParser.Activity)label;
13446            out.print(prefix); out.print(
13447                    Integer.toHexString(System.identityHashCode(activity)));
13448                    out.print(' ');
13449                    activity.printComponentShortName(out);
13450            if (count > 1) {
13451                out.print(" ("); out.print(count); out.print(" filters)");
13452            }
13453            out.println();
13454        }
13455
13456        // Keys are String (activity class name), values are Activity.
13457        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13458                = new ArrayMap<ComponentName, PackageParser.Activity>();
13459        private int mFlags;
13460    }
13461
13462    private final class ServiceIntentResolver
13463            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13464        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13465                boolean defaultOnly, int userId) {
13466            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13467            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13468        }
13469
13470        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13471                int userId) {
13472            if (!sUserManager.exists(userId)) return null;
13473            mFlags = flags;
13474            return super.queryIntent(intent, resolvedType,
13475                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13476                    userId);
13477        }
13478
13479        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13480                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13481            if (!sUserManager.exists(userId)) return null;
13482            if (packageServices == null) {
13483                return null;
13484            }
13485            mFlags = flags;
13486            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13487            final int N = packageServices.size();
13488            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13489                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13490
13491            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13492            for (int i = 0; i < N; ++i) {
13493                intentFilters = packageServices.get(i).intents;
13494                if (intentFilters != null && intentFilters.size() > 0) {
13495                    PackageParser.ServiceIntentInfo[] array =
13496                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13497                    intentFilters.toArray(array);
13498                    listCut.add(array);
13499                }
13500            }
13501            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13502        }
13503
13504        public final void addService(PackageParser.Service s) {
13505            mServices.put(s.getComponentName(), s);
13506            if (DEBUG_SHOW_INFO) {
13507                Log.v(TAG, "  "
13508                        + (s.info.nonLocalizedLabel != null
13509                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13510                Log.v(TAG, "    Class=" + s.info.name);
13511            }
13512            final int NI = s.intents.size();
13513            int j;
13514            for (j=0; j<NI; j++) {
13515                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13516                if (DEBUG_SHOW_INFO) {
13517                    Log.v(TAG, "    IntentFilter:");
13518                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13519                }
13520                if (!intent.debugCheck()) {
13521                    Log.w(TAG, "==> For Service " + s.info.name);
13522                }
13523                addFilter(intent);
13524            }
13525        }
13526
13527        public final void removeService(PackageParser.Service s) {
13528            mServices.remove(s.getComponentName());
13529            if (DEBUG_SHOW_INFO) {
13530                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13531                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13532                Log.v(TAG, "    Class=" + s.info.name);
13533            }
13534            final int NI = s.intents.size();
13535            int j;
13536            for (j=0; j<NI; j++) {
13537                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13538                if (DEBUG_SHOW_INFO) {
13539                    Log.v(TAG, "    IntentFilter:");
13540                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13541                }
13542                removeFilter(intent);
13543            }
13544        }
13545
13546        @Override
13547        protected boolean allowFilterResult(
13548                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13549            ServiceInfo filterSi = filter.service.info;
13550            for (int i=dest.size()-1; i>=0; i--) {
13551                ServiceInfo destAi = dest.get(i).serviceInfo;
13552                if (destAi.name == filterSi.name
13553                        && destAi.packageName == filterSi.packageName) {
13554                    return false;
13555                }
13556            }
13557            return true;
13558        }
13559
13560        @Override
13561        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13562            return new PackageParser.ServiceIntentInfo[size];
13563        }
13564
13565        @Override
13566        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13567            if (!sUserManager.exists(userId)) return true;
13568            PackageParser.Package p = filter.service.owner;
13569            if (p != null) {
13570                PackageSetting ps = (PackageSetting)p.mExtras;
13571                if (ps != null) {
13572                    // System apps are never considered stopped for purposes of
13573                    // filtering, because there may be no way for the user to
13574                    // actually re-launch them.
13575                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13576                            && ps.getStopped(userId);
13577                }
13578            }
13579            return false;
13580        }
13581
13582        @Override
13583        protected boolean isPackageForFilter(String packageName,
13584                PackageParser.ServiceIntentInfo info) {
13585            return packageName.equals(info.service.owner.packageName);
13586        }
13587
13588        @Override
13589        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13590                int match, int userId) {
13591            if (!sUserManager.exists(userId)) return null;
13592            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13593            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13594                return null;
13595            }
13596            final PackageParser.Service service = info.service;
13597            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13598            if (ps == null) {
13599                return null;
13600            }
13601            final PackageUserState userState = ps.readUserState(userId);
13602            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13603                    userState, userId);
13604            if (si == null) {
13605                return null;
13606            }
13607            final boolean matchVisibleToInstantApp =
13608                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13609            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13610            // throw out filters that aren't visible to ephemeral apps
13611            if (matchVisibleToInstantApp
13612                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13613                return null;
13614            }
13615            // throw out ephemeral filters if we're not explicitly requesting them
13616            if (!isInstantApp && userState.instantApp) {
13617                return null;
13618            }
13619            // throw out instant app filters if updates are available; will trigger
13620            // instant app resolution
13621            if (userState.instantApp && ps.isUpdateAvailable()) {
13622                return null;
13623            }
13624            final ResolveInfo res = new ResolveInfo();
13625            res.serviceInfo = si;
13626            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13627                res.filter = filter;
13628            }
13629            res.priority = info.getPriority();
13630            res.preferredOrder = service.owner.mPreferredOrder;
13631            res.match = match;
13632            res.isDefault = info.hasDefault;
13633            res.labelRes = info.labelRes;
13634            res.nonLocalizedLabel = info.nonLocalizedLabel;
13635            res.icon = info.icon;
13636            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13637            return res;
13638        }
13639
13640        @Override
13641        protected void sortResults(List<ResolveInfo> results) {
13642            Collections.sort(results, mResolvePrioritySorter);
13643        }
13644
13645        @Override
13646        protected void dumpFilter(PrintWriter out, String prefix,
13647                PackageParser.ServiceIntentInfo filter) {
13648            out.print(prefix); out.print(
13649                    Integer.toHexString(System.identityHashCode(filter.service)));
13650                    out.print(' ');
13651                    filter.service.printComponentShortName(out);
13652                    out.print(" filter ");
13653                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13654        }
13655
13656        @Override
13657        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13658            return filter.service;
13659        }
13660
13661        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13662            PackageParser.Service service = (PackageParser.Service)label;
13663            out.print(prefix); out.print(
13664                    Integer.toHexString(System.identityHashCode(service)));
13665                    out.print(' ');
13666                    service.printComponentShortName(out);
13667            if (count > 1) {
13668                out.print(" ("); out.print(count); out.print(" filters)");
13669            }
13670            out.println();
13671        }
13672
13673//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13674//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13675//            final List<ResolveInfo> retList = Lists.newArrayList();
13676//            while (i.hasNext()) {
13677//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13678//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13679//                    retList.add(resolveInfo);
13680//                }
13681//            }
13682//            return retList;
13683//        }
13684
13685        // Keys are String (activity class name), values are Activity.
13686        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13687                = new ArrayMap<ComponentName, PackageParser.Service>();
13688        private int mFlags;
13689    }
13690
13691    private final class ProviderIntentResolver
13692            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13693        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13694                boolean defaultOnly, int userId) {
13695            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13696            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13697        }
13698
13699        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13700                int userId) {
13701            if (!sUserManager.exists(userId))
13702                return null;
13703            mFlags = flags;
13704            return super.queryIntent(intent, resolvedType,
13705                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13706                    userId);
13707        }
13708
13709        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13710                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13711            if (!sUserManager.exists(userId))
13712                return null;
13713            if (packageProviders == null) {
13714                return null;
13715            }
13716            mFlags = flags;
13717            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13718            final int N = packageProviders.size();
13719            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13720                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13721
13722            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13723            for (int i = 0; i < N; ++i) {
13724                intentFilters = packageProviders.get(i).intents;
13725                if (intentFilters != null && intentFilters.size() > 0) {
13726                    PackageParser.ProviderIntentInfo[] array =
13727                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13728                    intentFilters.toArray(array);
13729                    listCut.add(array);
13730                }
13731            }
13732            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13733        }
13734
13735        public final void addProvider(PackageParser.Provider p) {
13736            if (mProviders.containsKey(p.getComponentName())) {
13737                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13738                return;
13739            }
13740
13741            mProviders.put(p.getComponentName(), p);
13742            if (DEBUG_SHOW_INFO) {
13743                Log.v(TAG, "  "
13744                        + (p.info.nonLocalizedLabel != null
13745                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13746                Log.v(TAG, "    Class=" + p.info.name);
13747            }
13748            final int NI = p.intents.size();
13749            int j;
13750            for (j = 0; j < NI; j++) {
13751                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13752                if (DEBUG_SHOW_INFO) {
13753                    Log.v(TAG, "    IntentFilter:");
13754                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13755                }
13756                if (!intent.debugCheck()) {
13757                    Log.w(TAG, "==> For Provider " + p.info.name);
13758                }
13759                addFilter(intent);
13760            }
13761        }
13762
13763        public final void removeProvider(PackageParser.Provider p) {
13764            mProviders.remove(p.getComponentName());
13765            if (DEBUG_SHOW_INFO) {
13766                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13767                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13768                Log.v(TAG, "    Class=" + p.info.name);
13769            }
13770            final int NI = p.intents.size();
13771            int j;
13772            for (j = 0; j < NI; j++) {
13773                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13774                if (DEBUG_SHOW_INFO) {
13775                    Log.v(TAG, "    IntentFilter:");
13776                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13777                }
13778                removeFilter(intent);
13779            }
13780        }
13781
13782        @Override
13783        protected boolean allowFilterResult(
13784                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13785            ProviderInfo filterPi = filter.provider.info;
13786            for (int i = dest.size() - 1; i >= 0; i--) {
13787                ProviderInfo destPi = dest.get(i).providerInfo;
13788                if (destPi.name == filterPi.name
13789                        && destPi.packageName == filterPi.packageName) {
13790                    return false;
13791                }
13792            }
13793            return true;
13794        }
13795
13796        @Override
13797        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13798            return new PackageParser.ProviderIntentInfo[size];
13799        }
13800
13801        @Override
13802        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13803            if (!sUserManager.exists(userId))
13804                return true;
13805            PackageParser.Package p = filter.provider.owner;
13806            if (p != null) {
13807                PackageSetting ps = (PackageSetting) p.mExtras;
13808                if (ps != null) {
13809                    // System apps are never considered stopped for purposes of
13810                    // filtering, because there may be no way for the user to
13811                    // actually re-launch them.
13812                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13813                            && ps.getStopped(userId);
13814                }
13815            }
13816            return false;
13817        }
13818
13819        @Override
13820        protected boolean isPackageForFilter(String packageName,
13821                PackageParser.ProviderIntentInfo info) {
13822            return packageName.equals(info.provider.owner.packageName);
13823        }
13824
13825        @Override
13826        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13827                int match, int userId) {
13828            if (!sUserManager.exists(userId))
13829                return null;
13830            final PackageParser.ProviderIntentInfo info = filter;
13831            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13832                return null;
13833            }
13834            final PackageParser.Provider provider = info.provider;
13835            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13836            if (ps == null) {
13837                return null;
13838            }
13839            final PackageUserState userState = ps.readUserState(userId);
13840            final boolean matchVisibleToInstantApp =
13841                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13842            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13843            // throw out filters that aren't visible to instant applications
13844            if (matchVisibleToInstantApp
13845                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13846                return null;
13847            }
13848            // throw out instant application filters if we're not explicitly requesting them
13849            if (!isInstantApp && userState.instantApp) {
13850                return null;
13851            }
13852            // throw out instant application filters if updates are available; will trigger
13853            // instant application resolution
13854            if (userState.instantApp && ps.isUpdateAvailable()) {
13855                return null;
13856            }
13857            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13858                    userState, userId);
13859            if (pi == null) {
13860                return null;
13861            }
13862            final ResolveInfo res = new ResolveInfo();
13863            res.providerInfo = pi;
13864            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13865                res.filter = filter;
13866            }
13867            res.priority = info.getPriority();
13868            res.preferredOrder = provider.owner.mPreferredOrder;
13869            res.match = match;
13870            res.isDefault = info.hasDefault;
13871            res.labelRes = info.labelRes;
13872            res.nonLocalizedLabel = info.nonLocalizedLabel;
13873            res.icon = info.icon;
13874            res.system = res.providerInfo.applicationInfo.isSystemApp();
13875            return res;
13876        }
13877
13878        @Override
13879        protected void sortResults(List<ResolveInfo> results) {
13880            Collections.sort(results, mResolvePrioritySorter);
13881        }
13882
13883        @Override
13884        protected void dumpFilter(PrintWriter out, String prefix,
13885                PackageParser.ProviderIntentInfo filter) {
13886            out.print(prefix);
13887            out.print(
13888                    Integer.toHexString(System.identityHashCode(filter.provider)));
13889            out.print(' ');
13890            filter.provider.printComponentShortName(out);
13891            out.print(" filter ");
13892            out.println(Integer.toHexString(System.identityHashCode(filter)));
13893        }
13894
13895        @Override
13896        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13897            return filter.provider;
13898        }
13899
13900        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13901            PackageParser.Provider provider = (PackageParser.Provider)label;
13902            out.print(prefix); out.print(
13903                    Integer.toHexString(System.identityHashCode(provider)));
13904                    out.print(' ');
13905                    provider.printComponentShortName(out);
13906            if (count > 1) {
13907                out.print(" ("); out.print(count); out.print(" filters)");
13908            }
13909            out.println();
13910        }
13911
13912        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13913                = new ArrayMap<ComponentName, PackageParser.Provider>();
13914        private int mFlags;
13915    }
13916
13917    static final class EphemeralIntentResolver
13918            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13919        /**
13920         * The result that has the highest defined order. Ordering applies on a
13921         * per-package basis. Mapping is from package name to Pair of order and
13922         * EphemeralResolveInfo.
13923         * <p>
13924         * NOTE: This is implemented as a field variable for convenience and efficiency.
13925         * By having a field variable, we're able to track filter ordering as soon as
13926         * a non-zero order is defined. Otherwise, multiple loops across the result set
13927         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13928         * this needs to be contained entirely within {@link #filterResults}.
13929         */
13930        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13931
13932        @Override
13933        protected AuxiliaryResolveInfo[] newArray(int size) {
13934            return new AuxiliaryResolveInfo[size];
13935        }
13936
13937        @Override
13938        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13939            return true;
13940        }
13941
13942        @Override
13943        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13944                int userId) {
13945            if (!sUserManager.exists(userId)) {
13946                return null;
13947            }
13948            final String packageName = responseObj.resolveInfo.getPackageName();
13949            final Integer order = responseObj.getOrder();
13950            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13951                    mOrderResult.get(packageName);
13952            // ordering is enabled and this item's order isn't high enough
13953            if (lastOrderResult != null && lastOrderResult.first >= order) {
13954                return null;
13955            }
13956            final InstantAppResolveInfo res = responseObj.resolveInfo;
13957            if (order > 0) {
13958                // non-zero order, enable ordering
13959                mOrderResult.put(packageName, new Pair<>(order, res));
13960            }
13961            return responseObj;
13962        }
13963
13964        @Override
13965        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13966            // only do work if ordering is enabled [most of the time it won't be]
13967            if (mOrderResult.size() == 0) {
13968                return;
13969            }
13970            int resultSize = results.size();
13971            for (int i = 0; i < resultSize; i++) {
13972                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13973                final String packageName = info.getPackageName();
13974                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13975                if (savedInfo == null) {
13976                    // package doesn't having ordering
13977                    continue;
13978                }
13979                if (savedInfo.second == info) {
13980                    // circled back to the highest ordered item; remove from order list
13981                    mOrderResult.remove(savedInfo);
13982                    if (mOrderResult.size() == 0) {
13983                        // no more ordered items
13984                        break;
13985                    }
13986                    continue;
13987                }
13988                // item has a worse order, remove it from the result list
13989                results.remove(i);
13990                resultSize--;
13991                i--;
13992            }
13993        }
13994    }
13995
13996    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13997            new Comparator<ResolveInfo>() {
13998        public int compare(ResolveInfo r1, ResolveInfo r2) {
13999            int v1 = r1.priority;
14000            int v2 = r2.priority;
14001            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
14002            if (v1 != v2) {
14003                return (v1 > v2) ? -1 : 1;
14004            }
14005            v1 = r1.preferredOrder;
14006            v2 = r2.preferredOrder;
14007            if (v1 != v2) {
14008                return (v1 > v2) ? -1 : 1;
14009            }
14010            if (r1.isDefault != r2.isDefault) {
14011                return r1.isDefault ? -1 : 1;
14012            }
14013            v1 = r1.match;
14014            v2 = r2.match;
14015            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
14016            if (v1 != v2) {
14017                return (v1 > v2) ? -1 : 1;
14018            }
14019            if (r1.system != r2.system) {
14020                return r1.system ? -1 : 1;
14021            }
14022            if (r1.activityInfo != null) {
14023                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
14024            }
14025            if (r1.serviceInfo != null) {
14026                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
14027            }
14028            if (r1.providerInfo != null) {
14029                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
14030            }
14031            return 0;
14032        }
14033    };
14034
14035    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
14036            new Comparator<ProviderInfo>() {
14037        public int compare(ProviderInfo p1, ProviderInfo p2) {
14038            final int v1 = p1.initOrder;
14039            final int v2 = p2.initOrder;
14040            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
14041        }
14042    };
14043
14044    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
14045            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
14046            final int[] userIds) {
14047        mHandler.post(new Runnable() {
14048            @Override
14049            public void run() {
14050                try {
14051                    final IActivityManager am = ActivityManager.getService();
14052                    if (am == null) return;
14053                    final int[] resolvedUserIds;
14054                    if (userIds == null) {
14055                        resolvedUserIds = am.getRunningUserIds();
14056                    } else {
14057                        resolvedUserIds = userIds;
14058                    }
14059                    for (int id : resolvedUserIds) {
14060                        final Intent intent = new Intent(action,
14061                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14062                        if (extras != null) {
14063                            intent.putExtras(extras);
14064                        }
14065                        if (targetPkg != null) {
14066                            intent.setPackage(targetPkg);
14067                        }
14068                        // Modify the UID when posting to other users
14069                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14070                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14071                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14072                            intent.putExtra(Intent.EXTRA_UID, uid);
14073                        }
14074                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14075                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14076                        if (DEBUG_BROADCASTS) {
14077                            RuntimeException here = new RuntimeException("here");
14078                            here.fillInStackTrace();
14079                            Slog.d(TAG, "Sending to user " + id + ": "
14080                                    + intent.toShortString(false, true, false, false)
14081                                    + " " + intent.getExtras(), here);
14082                        }
14083                        am.broadcastIntent(null, intent, null, finishedReceiver,
14084                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14085                                null, finishedReceiver != null, false, id);
14086                    }
14087                } catch (RemoteException ex) {
14088                }
14089            }
14090        });
14091    }
14092
14093    /**
14094     * Check if the external storage media is available. This is true if there
14095     * is a mounted external storage medium or if the external storage is
14096     * emulated.
14097     */
14098    private boolean isExternalMediaAvailable() {
14099        return mMediaMounted || Environment.isExternalStorageEmulated();
14100    }
14101
14102    @Override
14103    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14104        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14105            return null;
14106        }
14107        // writer
14108        synchronized (mPackages) {
14109            if (!isExternalMediaAvailable()) {
14110                // If the external storage is no longer mounted at this point,
14111                // the caller may not have been able to delete all of this
14112                // packages files and can not delete any more.  Bail.
14113                return null;
14114            }
14115            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14116            if (lastPackage != null) {
14117                pkgs.remove(lastPackage);
14118            }
14119            if (pkgs.size() > 0) {
14120                return pkgs.get(0);
14121            }
14122        }
14123        return null;
14124    }
14125
14126    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14127        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14128                userId, andCode ? 1 : 0, packageName);
14129        if (mSystemReady) {
14130            msg.sendToTarget();
14131        } else {
14132            if (mPostSystemReadyMessages == null) {
14133                mPostSystemReadyMessages = new ArrayList<>();
14134            }
14135            mPostSystemReadyMessages.add(msg);
14136        }
14137    }
14138
14139    void startCleaningPackages() {
14140        // reader
14141        if (!isExternalMediaAvailable()) {
14142            return;
14143        }
14144        synchronized (mPackages) {
14145            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14146                return;
14147            }
14148        }
14149        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14150        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14151        IActivityManager am = ActivityManager.getService();
14152        if (am != null) {
14153            int dcsUid = -1;
14154            synchronized (mPackages) {
14155                if (!mDefaultContainerWhitelisted) {
14156                    mDefaultContainerWhitelisted = true;
14157                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14158                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14159                }
14160            }
14161            try {
14162                if (dcsUid > 0) {
14163                    am.backgroundWhitelistUid(dcsUid);
14164                }
14165                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14166                        UserHandle.USER_SYSTEM);
14167            } catch (RemoteException e) {
14168            }
14169        }
14170    }
14171
14172    @Override
14173    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14174            int installFlags, String installerPackageName, int userId) {
14175        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14176
14177        final int callingUid = Binder.getCallingUid();
14178        enforceCrossUserPermission(callingUid, userId,
14179                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14180
14181        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14182            try {
14183                if (observer != null) {
14184                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14185                }
14186            } catch (RemoteException re) {
14187            }
14188            return;
14189        }
14190
14191        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14192            installFlags |= PackageManager.INSTALL_FROM_ADB;
14193
14194        } else {
14195            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14196            // about installerPackageName.
14197
14198            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14199            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14200        }
14201
14202        UserHandle user;
14203        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14204            user = UserHandle.ALL;
14205        } else {
14206            user = new UserHandle(userId);
14207        }
14208
14209        // Only system components can circumvent runtime permissions when installing.
14210        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14211                && mContext.checkCallingOrSelfPermission(Manifest.permission
14212                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14213            throw new SecurityException("You need the "
14214                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14215                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14216        }
14217
14218        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14219                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14220            throw new IllegalArgumentException(
14221                    "New installs into ASEC containers no longer supported");
14222        }
14223
14224        final File originFile = new File(originPath);
14225        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14226
14227        final Message msg = mHandler.obtainMessage(INIT_COPY);
14228        final VerificationInfo verificationInfo = new VerificationInfo(
14229                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14230        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14231                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14232                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14233                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14234        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14235        msg.obj = params;
14236
14237        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14238                System.identityHashCode(msg.obj));
14239        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14240                System.identityHashCode(msg.obj));
14241
14242        mHandler.sendMessage(msg);
14243    }
14244
14245
14246    /**
14247     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14248     * it is acting on behalf on an enterprise or the user).
14249     *
14250     * Note that the ordering of the conditionals in this method is important. The checks we perform
14251     * are as follows, in this order:
14252     *
14253     * 1) If the install is being performed by a system app, we can trust the app to have set the
14254     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14255     *    what it is.
14256     * 2) If the install is being performed by a device or profile owner app, the install reason
14257     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14258     *    set the install reason correctly. If the app targets an older SDK version where install
14259     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14260     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14261     * 3) In all other cases, the install is being performed by a regular app that is neither part
14262     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14263     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14264     *    set to enterprise policy and if so, change it to unknown instead.
14265     */
14266    private int fixUpInstallReason(String installerPackageName, int installerUid,
14267            int installReason) {
14268        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14269                == PERMISSION_GRANTED) {
14270            // If the install is being performed by a system app, we trust that app to have set the
14271            // install reason correctly.
14272            return installReason;
14273        }
14274
14275        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14276            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14277        if (dpm != null) {
14278            ComponentName owner = null;
14279            try {
14280                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14281                if (owner == null) {
14282                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14283                }
14284            } catch (RemoteException e) {
14285            }
14286            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14287                // If the install is being performed by a device or profile owner, the install
14288                // reason should be enterprise policy.
14289                return PackageManager.INSTALL_REASON_POLICY;
14290            }
14291        }
14292
14293        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14294            // If the install is being performed by a regular app (i.e. neither system app nor
14295            // device or profile owner), we have no reason to believe that the app is acting on
14296            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14297            // change it to unknown instead.
14298            return PackageManager.INSTALL_REASON_UNKNOWN;
14299        }
14300
14301        // If the install is being performed by a regular app and the install reason was set to any
14302        // value but enterprise policy, leave the install reason unchanged.
14303        return installReason;
14304    }
14305
14306    void installStage(String packageName, File stagedDir, String stagedCid,
14307            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14308            String installerPackageName, int installerUid, UserHandle user,
14309            Certificate[][] certificates) {
14310        if (DEBUG_EPHEMERAL) {
14311            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14312                Slog.d(TAG, "Ephemeral install of " + packageName);
14313            }
14314        }
14315        final VerificationInfo verificationInfo = new VerificationInfo(
14316                sessionParams.originatingUri, sessionParams.referrerUri,
14317                sessionParams.originatingUid, installerUid);
14318
14319        final OriginInfo origin;
14320        if (stagedDir != null) {
14321            origin = OriginInfo.fromStagedFile(stagedDir);
14322        } else {
14323            origin = OriginInfo.fromStagedContainer(stagedCid);
14324        }
14325
14326        final Message msg = mHandler.obtainMessage(INIT_COPY);
14327        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14328                sessionParams.installReason);
14329        final InstallParams params = new InstallParams(origin, null, observer,
14330                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14331                verificationInfo, user, sessionParams.abiOverride,
14332                sessionParams.grantedRuntimePermissions, certificates, installReason);
14333        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14334        msg.obj = params;
14335
14336        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14337                System.identityHashCode(msg.obj));
14338        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14339                System.identityHashCode(msg.obj));
14340
14341        mHandler.sendMessage(msg);
14342    }
14343
14344    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14345            int userId) {
14346        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14347        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
14348
14349        // Send a session commit broadcast
14350        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14351        info.installReason = pkgSetting.getInstallReason(userId);
14352        info.appPackageName = packageName;
14353        sendSessionCommitBroadcast(info, userId);
14354    }
14355
14356    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
14357        if (ArrayUtils.isEmpty(userIds)) {
14358            return;
14359        }
14360        Bundle extras = new Bundle(1);
14361        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14362        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14363
14364        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14365                packageName, extras, 0, null, null, userIds);
14366        if (isSystem) {
14367            mHandler.post(() -> {
14368                        for (int userId : userIds) {
14369                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
14370                        }
14371                    }
14372            );
14373        }
14374    }
14375
14376    /**
14377     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14378     * automatically without needing an explicit launch.
14379     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14380     */
14381    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
14382        // If user is not running, the app didn't miss any broadcast
14383        if (!mUserManagerInternal.isUserRunning(userId)) {
14384            return;
14385        }
14386        final IActivityManager am = ActivityManager.getService();
14387        try {
14388            // Deliver LOCKED_BOOT_COMPLETED first
14389            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14390                    .setPackage(packageName);
14391            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14392            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14393                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14394
14395            // Deliver BOOT_COMPLETED only if user is unlocked
14396            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14397                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14398                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14399                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14400            }
14401        } catch (RemoteException e) {
14402            throw e.rethrowFromSystemServer();
14403        }
14404    }
14405
14406    @Override
14407    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14408            int userId) {
14409        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14410        PackageSetting pkgSetting;
14411        final int callingUid = Binder.getCallingUid();
14412        enforceCrossUserPermission(callingUid, userId,
14413                true /* requireFullPermission */, true /* checkShell */,
14414                "setApplicationHiddenSetting for user " + userId);
14415
14416        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14417            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14418            return false;
14419        }
14420
14421        long callingId = Binder.clearCallingIdentity();
14422        try {
14423            boolean sendAdded = false;
14424            boolean sendRemoved = false;
14425            // writer
14426            synchronized (mPackages) {
14427                pkgSetting = mSettings.mPackages.get(packageName);
14428                if (pkgSetting == null) {
14429                    return false;
14430                }
14431                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14432                    return false;
14433                }
14434                // Do not allow "android" is being disabled
14435                if ("android".equals(packageName)) {
14436                    Slog.w(TAG, "Cannot hide package: android");
14437                    return false;
14438                }
14439                // Cannot hide static shared libs as they are considered
14440                // a part of the using app (emulating static linking). Also
14441                // static libs are installed always on internal storage.
14442                PackageParser.Package pkg = mPackages.get(packageName);
14443                if (pkg != null && pkg.staticSharedLibName != null) {
14444                    Slog.w(TAG, "Cannot hide package: " + packageName
14445                            + " providing static shared library: "
14446                            + pkg.staticSharedLibName);
14447                    return false;
14448                }
14449                // Only allow protected packages to hide themselves.
14450                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
14451                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14452                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14453                    return false;
14454                }
14455
14456                if (pkgSetting.getHidden(userId) != hidden) {
14457                    pkgSetting.setHidden(hidden, userId);
14458                    mSettings.writePackageRestrictionsLPr(userId);
14459                    if (hidden) {
14460                        sendRemoved = true;
14461                    } else {
14462                        sendAdded = true;
14463                    }
14464                }
14465            }
14466            if (sendAdded) {
14467                sendPackageAddedForUser(packageName, pkgSetting, userId);
14468                return true;
14469            }
14470            if (sendRemoved) {
14471                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14472                        "hiding pkg");
14473                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14474                return true;
14475            }
14476        } finally {
14477            Binder.restoreCallingIdentity(callingId);
14478        }
14479        return false;
14480    }
14481
14482    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14483            int userId) {
14484        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14485        info.removedPackage = packageName;
14486        info.installerPackageName = pkgSetting.installerPackageName;
14487        info.removedUsers = new int[] {userId};
14488        info.broadcastUsers = new int[] {userId};
14489        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14490        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14491    }
14492
14493    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14494        if (pkgList.length > 0) {
14495            Bundle extras = new Bundle(1);
14496            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14497
14498            sendPackageBroadcast(
14499                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14500                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14501                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14502                    new int[] {userId});
14503        }
14504    }
14505
14506    /**
14507     * Returns true if application is not found or there was an error. Otherwise it returns
14508     * the hidden state of the package for the given user.
14509     */
14510    @Override
14511    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14512        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14513        final int callingUid = Binder.getCallingUid();
14514        enforceCrossUserPermission(callingUid, userId,
14515                true /* requireFullPermission */, false /* checkShell */,
14516                "getApplicationHidden for user " + userId);
14517        PackageSetting ps;
14518        long callingId = Binder.clearCallingIdentity();
14519        try {
14520            // writer
14521            synchronized (mPackages) {
14522                ps = mSettings.mPackages.get(packageName);
14523                if (ps == null) {
14524                    return true;
14525                }
14526                if (filterAppAccessLPr(ps, callingUid, userId)) {
14527                    return true;
14528                }
14529                return ps.getHidden(userId);
14530            }
14531        } finally {
14532            Binder.restoreCallingIdentity(callingId);
14533        }
14534    }
14535
14536    /**
14537     * @hide
14538     */
14539    @Override
14540    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14541            int installReason) {
14542        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14543                null);
14544        PackageSetting pkgSetting;
14545        final int callingUid = Binder.getCallingUid();
14546        enforceCrossUserPermission(callingUid, userId,
14547                true /* requireFullPermission */, true /* checkShell */,
14548                "installExistingPackage for user " + userId);
14549        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14550            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14551        }
14552
14553        long callingId = Binder.clearCallingIdentity();
14554        try {
14555            boolean installed = false;
14556            final boolean instantApp =
14557                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14558            final boolean fullApp =
14559                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14560
14561            // writer
14562            synchronized (mPackages) {
14563                pkgSetting = mSettings.mPackages.get(packageName);
14564                if (pkgSetting == null) {
14565                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14566                }
14567                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
14568                    // only allow the existing package to be used if it's installed as a full
14569                    // application for at least one user
14570                    boolean installAllowed = false;
14571                    for (int checkUserId : sUserManager.getUserIds()) {
14572                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
14573                        if (installAllowed) {
14574                            break;
14575                        }
14576                    }
14577                    if (!installAllowed) {
14578                        return PackageManager.INSTALL_FAILED_INVALID_URI;
14579                    }
14580                }
14581                if (!pkgSetting.getInstalled(userId)) {
14582                    pkgSetting.setInstalled(true, userId);
14583                    pkgSetting.setHidden(false, userId);
14584                    pkgSetting.setInstallReason(installReason, userId);
14585                    mSettings.writePackageRestrictionsLPr(userId);
14586                    mSettings.writeKernelMappingLPr(pkgSetting);
14587                    installed = true;
14588                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14589                    // upgrade app from instant to full; we don't allow app downgrade
14590                    installed = true;
14591                }
14592                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14593            }
14594
14595            if (installed) {
14596                if (pkgSetting.pkg != null) {
14597                    synchronized (mInstallLock) {
14598                        // We don't need to freeze for a brand new install
14599                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14600                    }
14601                }
14602                sendPackageAddedForUser(packageName, pkgSetting, userId);
14603                synchronized (mPackages) {
14604                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
14605                }
14606            }
14607        } finally {
14608            Binder.restoreCallingIdentity(callingId);
14609        }
14610
14611        return PackageManager.INSTALL_SUCCEEDED;
14612    }
14613
14614    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14615            boolean instantApp, boolean fullApp) {
14616        // no state specified; do nothing
14617        if (!instantApp && !fullApp) {
14618            return;
14619        }
14620        if (userId != UserHandle.USER_ALL) {
14621            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14622                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14623            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14624                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14625            }
14626        } else {
14627            for (int currentUserId : sUserManager.getUserIds()) {
14628                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14629                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14630                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14631                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14632                }
14633            }
14634        }
14635    }
14636
14637    boolean isUserRestricted(int userId, String restrictionKey) {
14638        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14639        if (restrictions.getBoolean(restrictionKey, false)) {
14640            Log.w(TAG, "User is restricted: " + restrictionKey);
14641            return true;
14642        }
14643        return false;
14644    }
14645
14646    @Override
14647    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14648            int userId) {
14649        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14650        final int callingUid = Binder.getCallingUid();
14651        enforceCrossUserPermission(callingUid, userId,
14652                true /* requireFullPermission */, true /* checkShell */,
14653                "setPackagesSuspended for user " + userId);
14654
14655        if (ArrayUtils.isEmpty(packageNames)) {
14656            return packageNames;
14657        }
14658
14659        // List of package names for whom the suspended state has changed.
14660        List<String> changedPackages = new ArrayList<>(packageNames.length);
14661        // List of package names for whom the suspended state is not set as requested in this
14662        // method.
14663        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14664        long callingId = Binder.clearCallingIdentity();
14665        try {
14666            for (int i = 0; i < packageNames.length; i++) {
14667                String packageName = packageNames[i];
14668                boolean changed = false;
14669                final int appId;
14670                synchronized (mPackages) {
14671                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14672                    if (pkgSetting == null
14673                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
14674                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14675                                + "\". Skipping suspending/un-suspending.");
14676                        unactionedPackages.add(packageName);
14677                        continue;
14678                    }
14679                    appId = pkgSetting.appId;
14680                    if (pkgSetting.getSuspended(userId) != suspended) {
14681                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14682                            unactionedPackages.add(packageName);
14683                            continue;
14684                        }
14685                        pkgSetting.setSuspended(suspended, userId);
14686                        mSettings.writePackageRestrictionsLPr(userId);
14687                        changed = true;
14688                        changedPackages.add(packageName);
14689                    }
14690                }
14691
14692                if (changed && suspended) {
14693                    killApplication(packageName, UserHandle.getUid(userId, appId),
14694                            "suspending package");
14695                }
14696            }
14697        } finally {
14698            Binder.restoreCallingIdentity(callingId);
14699        }
14700
14701        if (!changedPackages.isEmpty()) {
14702            sendPackagesSuspendedForUser(changedPackages.toArray(
14703                    new String[changedPackages.size()]), userId, suspended);
14704        }
14705
14706        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14707    }
14708
14709    @Override
14710    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14711        final int callingUid = Binder.getCallingUid();
14712        enforceCrossUserPermission(callingUid, userId,
14713                true /* requireFullPermission */, false /* checkShell */,
14714                "isPackageSuspendedForUser for user " + userId);
14715        synchronized (mPackages) {
14716            final PackageSetting ps = mSettings.mPackages.get(packageName);
14717            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14718                throw new IllegalArgumentException("Unknown target package: " + packageName);
14719            }
14720            return ps.getSuspended(userId);
14721        }
14722    }
14723
14724    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14725        if (isPackageDeviceAdmin(packageName, userId)) {
14726            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14727                    + "\": has an active device admin");
14728            return false;
14729        }
14730
14731        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14732        if (packageName.equals(activeLauncherPackageName)) {
14733            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14734                    + "\": contains the active launcher");
14735            return false;
14736        }
14737
14738        if (packageName.equals(mRequiredInstallerPackage)) {
14739            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14740                    + "\": required for package installation");
14741            return false;
14742        }
14743
14744        if (packageName.equals(mRequiredUninstallerPackage)) {
14745            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14746                    + "\": required for package uninstallation");
14747            return false;
14748        }
14749
14750        if (packageName.equals(mRequiredVerifierPackage)) {
14751            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14752                    + "\": required for package verification");
14753            return false;
14754        }
14755
14756        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14757            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14758                    + "\": is the default dialer");
14759            return false;
14760        }
14761
14762        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14763            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14764                    + "\": protected package");
14765            return false;
14766        }
14767
14768        // Cannot suspend static shared libs as they are considered
14769        // a part of the using app (emulating static linking). Also
14770        // static libs are installed always on internal storage.
14771        PackageParser.Package pkg = mPackages.get(packageName);
14772        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14773            Slog.w(TAG, "Cannot suspend package: " + packageName
14774                    + " providing static shared library: "
14775                    + pkg.staticSharedLibName);
14776            return false;
14777        }
14778
14779        return true;
14780    }
14781
14782    private String getActiveLauncherPackageName(int userId) {
14783        Intent intent = new Intent(Intent.ACTION_MAIN);
14784        intent.addCategory(Intent.CATEGORY_HOME);
14785        ResolveInfo resolveInfo = resolveIntent(
14786                intent,
14787                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14788                PackageManager.MATCH_DEFAULT_ONLY,
14789                userId);
14790
14791        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14792    }
14793
14794    private String getDefaultDialerPackageName(int userId) {
14795        synchronized (mPackages) {
14796            return mSettings.getDefaultDialerPackageNameLPw(userId);
14797        }
14798    }
14799
14800    @Override
14801    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14802        mContext.enforceCallingOrSelfPermission(
14803                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14804                "Only package verification agents can verify applications");
14805
14806        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14807        final PackageVerificationResponse response = new PackageVerificationResponse(
14808                verificationCode, Binder.getCallingUid());
14809        msg.arg1 = id;
14810        msg.obj = response;
14811        mHandler.sendMessage(msg);
14812    }
14813
14814    @Override
14815    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14816            long millisecondsToDelay) {
14817        mContext.enforceCallingOrSelfPermission(
14818                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14819                "Only package verification agents can extend verification timeouts");
14820
14821        final PackageVerificationState state = mPendingVerification.get(id);
14822        final PackageVerificationResponse response = new PackageVerificationResponse(
14823                verificationCodeAtTimeout, Binder.getCallingUid());
14824
14825        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14826            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14827        }
14828        if (millisecondsToDelay < 0) {
14829            millisecondsToDelay = 0;
14830        }
14831        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14832                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14833            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14834        }
14835
14836        if ((state != null) && !state.timeoutExtended()) {
14837            state.extendTimeout();
14838
14839            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14840            msg.arg1 = id;
14841            msg.obj = response;
14842            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14843        }
14844    }
14845
14846    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14847            int verificationCode, UserHandle user) {
14848        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14849        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14850        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14851        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14852        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14853
14854        mContext.sendBroadcastAsUser(intent, user,
14855                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14856    }
14857
14858    private ComponentName matchComponentForVerifier(String packageName,
14859            List<ResolveInfo> receivers) {
14860        ActivityInfo targetReceiver = null;
14861
14862        final int NR = receivers.size();
14863        for (int i = 0; i < NR; i++) {
14864            final ResolveInfo info = receivers.get(i);
14865            if (info.activityInfo == null) {
14866                continue;
14867            }
14868
14869            if (packageName.equals(info.activityInfo.packageName)) {
14870                targetReceiver = info.activityInfo;
14871                break;
14872            }
14873        }
14874
14875        if (targetReceiver == null) {
14876            return null;
14877        }
14878
14879        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14880    }
14881
14882    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14883            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14884        if (pkgInfo.verifiers.length == 0) {
14885            return null;
14886        }
14887
14888        final int N = pkgInfo.verifiers.length;
14889        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14890        for (int i = 0; i < N; i++) {
14891            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14892
14893            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14894                    receivers);
14895            if (comp == null) {
14896                continue;
14897            }
14898
14899            final int verifierUid = getUidForVerifier(verifierInfo);
14900            if (verifierUid == -1) {
14901                continue;
14902            }
14903
14904            if (DEBUG_VERIFY) {
14905                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14906                        + " with the correct signature");
14907            }
14908            sufficientVerifiers.add(comp);
14909            verificationState.addSufficientVerifier(verifierUid);
14910        }
14911
14912        return sufficientVerifiers;
14913    }
14914
14915    private int getUidForVerifier(VerifierInfo verifierInfo) {
14916        synchronized (mPackages) {
14917            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14918            if (pkg == null) {
14919                return -1;
14920            } else if (pkg.mSignatures.length != 1) {
14921                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14922                        + " has more than one signature; ignoring");
14923                return -1;
14924            }
14925
14926            /*
14927             * If the public key of the package's signature does not match
14928             * our expected public key, then this is a different package and
14929             * we should skip.
14930             */
14931
14932            final byte[] expectedPublicKey;
14933            try {
14934                final Signature verifierSig = pkg.mSignatures[0];
14935                final PublicKey publicKey = verifierSig.getPublicKey();
14936                expectedPublicKey = publicKey.getEncoded();
14937            } catch (CertificateException e) {
14938                return -1;
14939            }
14940
14941            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14942
14943            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14944                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14945                        + " does not have the expected public key; ignoring");
14946                return -1;
14947            }
14948
14949            return pkg.applicationInfo.uid;
14950        }
14951    }
14952
14953    @Override
14954    public void finishPackageInstall(int token, boolean didLaunch) {
14955        enforceSystemOrRoot("Only the system is allowed to finish installs");
14956
14957        if (DEBUG_INSTALL) {
14958            Slog.v(TAG, "BM finishing package install for " + token);
14959        }
14960        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14961
14962        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14963        mHandler.sendMessage(msg);
14964    }
14965
14966    /**
14967     * Get the verification agent timeout.  Used for both the APK verifier and the
14968     * intent filter verifier.
14969     *
14970     * @return verification timeout in milliseconds
14971     */
14972    private long getVerificationTimeout() {
14973        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14974                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14975                DEFAULT_VERIFICATION_TIMEOUT);
14976    }
14977
14978    /**
14979     * Get the default verification agent response code.
14980     *
14981     * @return default verification response code
14982     */
14983    private int getDefaultVerificationResponse(UserHandle user) {
14984        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14985            return PackageManager.VERIFICATION_REJECT;
14986        }
14987        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14988                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14989                DEFAULT_VERIFICATION_RESPONSE);
14990    }
14991
14992    /**
14993     * Check whether or not package verification has been enabled.
14994     *
14995     * @return true if verification should be performed
14996     */
14997    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14998        if (!DEFAULT_VERIFY_ENABLE) {
14999            return false;
15000        }
15001
15002        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
15003
15004        // Check if installing from ADB
15005        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
15006            // Do not run verification in a test harness environment
15007            if (ActivityManager.isRunningInTestHarness()) {
15008                return false;
15009            }
15010            if (ensureVerifyAppsEnabled) {
15011                return true;
15012            }
15013            // Check if the developer does not want package verification for ADB installs
15014            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15015                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
15016                return false;
15017            }
15018        } else {
15019            // only when not installed from ADB, skip verification for instant apps when
15020            // the installer and verifier are the same.
15021            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
15022                if (mInstantAppInstallerActivity != null
15023                        && mInstantAppInstallerActivity.packageName.equals(
15024                                mRequiredVerifierPackage)) {
15025                    try {
15026                        mContext.getSystemService(AppOpsManager.class)
15027                                .checkPackage(installerUid, mRequiredVerifierPackage);
15028                        if (DEBUG_VERIFY) {
15029                            Slog.i(TAG, "disable verification for instant app");
15030                        }
15031                        return false;
15032                    } catch (SecurityException ignore) { }
15033                }
15034            }
15035        }
15036
15037        if (ensureVerifyAppsEnabled) {
15038            return true;
15039        }
15040
15041        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15042                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
15043    }
15044
15045    @Override
15046    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
15047            throws RemoteException {
15048        mContext.enforceCallingOrSelfPermission(
15049                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
15050                "Only intentfilter verification agents can verify applications");
15051
15052        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
15053        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
15054                Binder.getCallingUid(), verificationCode, failedDomains);
15055        msg.arg1 = id;
15056        msg.obj = response;
15057        mHandler.sendMessage(msg);
15058    }
15059
15060    @Override
15061    public int getIntentVerificationStatus(String packageName, int userId) {
15062        final int callingUid = Binder.getCallingUid();
15063        if (getInstantAppPackageName(callingUid) != null) {
15064            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15065        }
15066        synchronized (mPackages) {
15067            final PackageSetting ps = mSettings.mPackages.get(packageName);
15068            if (ps == null
15069                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15070                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
15071            }
15072            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
15073        }
15074    }
15075
15076    @Override
15077    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
15078        mContext.enforceCallingOrSelfPermission(
15079                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15080
15081        boolean result = false;
15082        synchronized (mPackages) {
15083            final PackageSetting ps = mSettings.mPackages.get(packageName);
15084            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15085                return false;
15086            }
15087            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
15088        }
15089        if (result) {
15090            scheduleWritePackageRestrictionsLocked(userId);
15091        }
15092        return result;
15093    }
15094
15095    @Override
15096    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
15097            String packageName) {
15098        final int callingUid = Binder.getCallingUid();
15099        if (getInstantAppPackageName(callingUid) != null) {
15100            return ParceledListSlice.emptyList();
15101        }
15102        synchronized (mPackages) {
15103            final PackageSetting ps = mSettings.mPackages.get(packageName);
15104            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15105                return ParceledListSlice.emptyList();
15106            }
15107            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15108        }
15109    }
15110
15111    @Override
15112    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15113        if (TextUtils.isEmpty(packageName)) {
15114            return ParceledListSlice.emptyList();
15115        }
15116        final int callingUid = Binder.getCallingUid();
15117        final int callingUserId = UserHandle.getUserId(callingUid);
15118        synchronized (mPackages) {
15119            PackageParser.Package pkg = mPackages.get(packageName);
15120            if (pkg == null || pkg.activities == null) {
15121                return ParceledListSlice.emptyList();
15122            }
15123            if (pkg.mExtras == null) {
15124                return ParceledListSlice.emptyList();
15125            }
15126            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15127            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15128                return ParceledListSlice.emptyList();
15129            }
15130            final int count = pkg.activities.size();
15131            ArrayList<IntentFilter> result = new ArrayList<>();
15132            for (int n=0; n<count; n++) {
15133                PackageParser.Activity activity = pkg.activities.get(n);
15134                if (activity.intents != null && activity.intents.size() > 0) {
15135                    result.addAll(activity.intents);
15136                }
15137            }
15138            return new ParceledListSlice<>(result);
15139        }
15140    }
15141
15142    @Override
15143    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15144        mContext.enforceCallingOrSelfPermission(
15145                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15146
15147        synchronized (mPackages) {
15148            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15149            if (packageName != null) {
15150                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15151                        packageName, userId);
15152            }
15153            return result;
15154        }
15155    }
15156
15157    @Override
15158    public String getDefaultBrowserPackageName(int userId) {
15159        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15160            return null;
15161        }
15162        synchronized (mPackages) {
15163            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15164        }
15165    }
15166
15167    /**
15168     * Get the "allow unknown sources" setting.
15169     *
15170     * @return the current "allow unknown sources" setting
15171     */
15172    private int getUnknownSourcesSettings() {
15173        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15174                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15175                -1);
15176    }
15177
15178    @Override
15179    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15180        final int callingUid = Binder.getCallingUid();
15181        if (getInstantAppPackageName(callingUid) != null) {
15182            return;
15183        }
15184        // writer
15185        synchronized (mPackages) {
15186            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15187            if (targetPackageSetting == null
15188                    || filterAppAccessLPr(
15189                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
15190                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15191            }
15192
15193            PackageSetting installerPackageSetting;
15194            if (installerPackageName != null) {
15195                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15196                if (installerPackageSetting == null) {
15197                    throw new IllegalArgumentException("Unknown installer package: "
15198                            + installerPackageName);
15199                }
15200            } else {
15201                installerPackageSetting = null;
15202            }
15203
15204            Signature[] callerSignature;
15205            Object obj = mSettings.getUserIdLPr(callingUid);
15206            if (obj != null) {
15207                if (obj instanceof SharedUserSetting) {
15208                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15209                } else if (obj instanceof PackageSetting) {
15210                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15211                } else {
15212                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15213                }
15214            } else {
15215                throw new SecurityException("Unknown calling UID: " + callingUid);
15216            }
15217
15218            // Verify: can't set installerPackageName to a package that is
15219            // not signed with the same cert as the caller.
15220            if (installerPackageSetting != null) {
15221                if (compareSignatures(callerSignature,
15222                        installerPackageSetting.signatures.mSignatures)
15223                        != PackageManager.SIGNATURE_MATCH) {
15224                    throw new SecurityException(
15225                            "Caller does not have same cert as new installer package "
15226                            + installerPackageName);
15227                }
15228            }
15229
15230            // Verify: if target already has an installer package, it must
15231            // be signed with the same cert as the caller.
15232            if (targetPackageSetting.installerPackageName != null) {
15233                PackageSetting setting = mSettings.mPackages.get(
15234                        targetPackageSetting.installerPackageName);
15235                // If the currently set package isn't valid, then it's always
15236                // okay to change it.
15237                if (setting != null) {
15238                    if (compareSignatures(callerSignature,
15239                            setting.signatures.mSignatures)
15240                            != PackageManager.SIGNATURE_MATCH) {
15241                        throw new SecurityException(
15242                                "Caller does not have same cert as old installer package "
15243                                + targetPackageSetting.installerPackageName);
15244                    }
15245                }
15246            }
15247
15248            // Okay!
15249            targetPackageSetting.installerPackageName = installerPackageName;
15250            if (installerPackageName != null) {
15251                mSettings.mInstallerPackages.add(installerPackageName);
15252            }
15253            scheduleWriteSettingsLocked();
15254        }
15255    }
15256
15257    @Override
15258    public void setApplicationCategoryHint(String packageName, int categoryHint,
15259            String callerPackageName) {
15260        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15261            throw new SecurityException("Instant applications don't have access to this method");
15262        }
15263        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15264                callerPackageName);
15265        synchronized (mPackages) {
15266            PackageSetting ps = mSettings.mPackages.get(packageName);
15267            if (ps == null) {
15268                throw new IllegalArgumentException("Unknown target package " + packageName);
15269            }
15270            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
15271                throw new IllegalArgumentException("Unknown target package " + packageName);
15272            }
15273            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15274                throw new IllegalArgumentException("Calling package " + callerPackageName
15275                        + " is not installer for " + packageName);
15276            }
15277
15278            if (ps.categoryHint != categoryHint) {
15279                ps.categoryHint = categoryHint;
15280                scheduleWriteSettingsLocked();
15281            }
15282        }
15283    }
15284
15285    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15286        // Queue up an async operation since the package installation may take a little while.
15287        mHandler.post(new Runnable() {
15288            public void run() {
15289                mHandler.removeCallbacks(this);
15290                 // Result object to be returned
15291                PackageInstalledInfo res = new PackageInstalledInfo();
15292                res.setReturnCode(currentStatus);
15293                res.uid = -1;
15294                res.pkg = null;
15295                res.removedInfo = null;
15296                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15297                    args.doPreInstall(res.returnCode);
15298                    synchronized (mInstallLock) {
15299                        installPackageTracedLI(args, res);
15300                    }
15301                    args.doPostInstall(res.returnCode, res.uid);
15302                }
15303
15304                // A restore should be performed at this point if (a) the install
15305                // succeeded, (b) the operation is not an update, and (c) the new
15306                // package has not opted out of backup participation.
15307                final boolean update = res.removedInfo != null
15308                        && res.removedInfo.removedPackage != null;
15309                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15310                boolean doRestore = !update
15311                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15312
15313                // Set up the post-install work request bookkeeping.  This will be used
15314                // and cleaned up by the post-install event handling regardless of whether
15315                // there's a restore pass performed.  Token values are >= 1.
15316                int token;
15317                if (mNextInstallToken < 0) mNextInstallToken = 1;
15318                token = mNextInstallToken++;
15319
15320                PostInstallData data = new PostInstallData(args, res);
15321                mRunningInstalls.put(token, data);
15322                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15323
15324                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15325                    // Pass responsibility to the Backup Manager.  It will perform a
15326                    // restore if appropriate, then pass responsibility back to the
15327                    // Package Manager to run the post-install observer callbacks
15328                    // and broadcasts.
15329                    IBackupManager bm = IBackupManager.Stub.asInterface(
15330                            ServiceManager.getService(Context.BACKUP_SERVICE));
15331                    if (bm != null) {
15332                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15333                                + " to BM for possible restore");
15334                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15335                        try {
15336                            // TODO: http://b/22388012
15337                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15338                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15339                            } else {
15340                                doRestore = false;
15341                            }
15342                        } catch (RemoteException e) {
15343                            // can't happen; the backup manager is local
15344                        } catch (Exception e) {
15345                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15346                            doRestore = false;
15347                        }
15348                    } else {
15349                        Slog.e(TAG, "Backup Manager not found!");
15350                        doRestore = false;
15351                    }
15352                }
15353
15354                if (!doRestore) {
15355                    // No restore possible, or the Backup Manager was mysteriously not
15356                    // available -- just fire the post-install work request directly.
15357                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15358
15359                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15360
15361                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15362                    mHandler.sendMessage(msg);
15363                }
15364            }
15365        });
15366    }
15367
15368    /**
15369     * Callback from PackageSettings whenever an app is first transitioned out of the
15370     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15371     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15372     * here whether the app is the target of an ongoing install, and only send the
15373     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15374     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15375     * handling.
15376     */
15377    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15378        // Serialize this with the rest of the install-process message chain.  In the
15379        // restore-at-install case, this Runnable will necessarily run before the
15380        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15381        // are coherent.  In the non-restore case, the app has already completed install
15382        // and been launched through some other means, so it is not in a problematic
15383        // state for observers to see the FIRST_LAUNCH signal.
15384        mHandler.post(new Runnable() {
15385            @Override
15386            public void run() {
15387                for (int i = 0; i < mRunningInstalls.size(); i++) {
15388                    final PostInstallData data = mRunningInstalls.valueAt(i);
15389                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15390                        continue;
15391                    }
15392                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15393                        // right package; but is it for the right user?
15394                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15395                            if (userId == data.res.newUsers[uIndex]) {
15396                                if (DEBUG_BACKUP) {
15397                                    Slog.i(TAG, "Package " + pkgName
15398                                            + " being restored so deferring FIRST_LAUNCH");
15399                                }
15400                                return;
15401                            }
15402                        }
15403                    }
15404                }
15405                // didn't find it, so not being restored
15406                if (DEBUG_BACKUP) {
15407                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15408                }
15409                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15410            }
15411        });
15412    }
15413
15414    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15415        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15416                installerPkg, null, userIds);
15417    }
15418
15419    private abstract class HandlerParams {
15420        private static final int MAX_RETRIES = 4;
15421
15422        /**
15423         * Number of times startCopy() has been attempted and had a non-fatal
15424         * error.
15425         */
15426        private int mRetries = 0;
15427
15428        /** User handle for the user requesting the information or installation. */
15429        private final UserHandle mUser;
15430        String traceMethod;
15431        int traceCookie;
15432
15433        HandlerParams(UserHandle user) {
15434            mUser = user;
15435        }
15436
15437        UserHandle getUser() {
15438            return mUser;
15439        }
15440
15441        HandlerParams setTraceMethod(String traceMethod) {
15442            this.traceMethod = traceMethod;
15443            return this;
15444        }
15445
15446        HandlerParams setTraceCookie(int traceCookie) {
15447            this.traceCookie = traceCookie;
15448            return this;
15449        }
15450
15451        final boolean startCopy() {
15452            boolean res;
15453            try {
15454                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15455
15456                if (++mRetries > MAX_RETRIES) {
15457                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15458                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15459                    handleServiceError();
15460                    return false;
15461                } else {
15462                    handleStartCopy();
15463                    res = true;
15464                }
15465            } catch (RemoteException e) {
15466                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15467                mHandler.sendEmptyMessage(MCS_RECONNECT);
15468                res = false;
15469            }
15470            handleReturnCode();
15471            return res;
15472        }
15473
15474        final void serviceError() {
15475            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15476            handleServiceError();
15477            handleReturnCode();
15478        }
15479
15480        abstract void handleStartCopy() throws RemoteException;
15481        abstract void handleServiceError();
15482        abstract void handleReturnCode();
15483    }
15484
15485    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15486        for (File path : paths) {
15487            try {
15488                mcs.clearDirectory(path.getAbsolutePath());
15489            } catch (RemoteException e) {
15490            }
15491        }
15492    }
15493
15494    static class OriginInfo {
15495        /**
15496         * Location where install is coming from, before it has been
15497         * copied/renamed into place. This could be a single monolithic APK
15498         * file, or a cluster directory. This location may be untrusted.
15499         */
15500        final File file;
15501        final String cid;
15502
15503        /**
15504         * Flag indicating that {@link #file} or {@link #cid} has already been
15505         * staged, meaning downstream users don't need to defensively copy the
15506         * contents.
15507         */
15508        final boolean staged;
15509
15510        /**
15511         * Flag indicating that {@link #file} or {@link #cid} is an already
15512         * installed app that is being moved.
15513         */
15514        final boolean existing;
15515
15516        final String resolvedPath;
15517        final File resolvedFile;
15518
15519        static OriginInfo fromNothing() {
15520            return new OriginInfo(null, null, false, false);
15521        }
15522
15523        static OriginInfo fromUntrustedFile(File file) {
15524            return new OriginInfo(file, null, false, false);
15525        }
15526
15527        static OriginInfo fromExistingFile(File file) {
15528            return new OriginInfo(file, null, false, true);
15529        }
15530
15531        static OriginInfo fromStagedFile(File file) {
15532            return new OriginInfo(file, null, true, false);
15533        }
15534
15535        static OriginInfo fromStagedContainer(String cid) {
15536            return new OriginInfo(null, cid, true, false);
15537        }
15538
15539        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15540            this.file = file;
15541            this.cid = cid;
15542            this.staged = staged;
15543            this.existing = existing;
15544
15545            if (cid != null) {
15546                resolvedPath = PackageHelper.getSdDir(cid);
15547                resolvedFile = new File(resolvedPath);
15548            } else if (file != null) {
15549                resolvedPath = file.getAbsolutePath();
15550                resolvedFile = file;
15551            } else {
15552                resolvedPath = null;
15553                resolvedFile = null;
15554            }
15555        }
15556    }
15557
15558    static class MoveInfo {
15559        final int moveId;
15560        final String fromUuid;
15561        final String toUuid;
15562        final String packageName;
15563        final String dataAppName;
15564        final int appId;
15565        final String seinfo;
15566        final int targetSdkVersion;
15567
15568        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15569                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15570            this.moveId = moveId;
15571            this.fromUuid = fromUuid;
15572            this.toUuid = toUuid;
15573            this.packageName = packageName;
15574            this.dataAppName = dataAppName;
15575            this.appId = appId;
15576            this.seinfo = seinfo;
15577            this.targetSdkVersion = targetSdkVersion;
15578        }
15579    }
15580
15581    static class VerificationInfo {
15582        /** A constant used to indicate that a uid value is not present. */
15583        public static final int NO_UID = -1;
15584
15585        /** URI referencing where the package was downloaded from. */
15586        final Uri originatingUri;
15587
15588        /** HTTP referrer URI associated with the originatingURI. */
15589        final Uri referrer;
15590
15591        /** UID of the application that the install request originated from. */
15592        final int originatingUid;
15593
15594        /** UID of application requesting the install */
15595        final int installerUid;
15596
15597        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15598            this.originatingUri = originatingUri;
15599            this.referrer = referrer;
15600            this.originatingUid = originatingUid;
15601            this.installerUid = installerUid;
15602        }
15603    }
15604
15605    class InstallParams extends HandlerParams {
15606        final OriginInfo origin;
15607        final MoveInfo move;
15608        final IPackageInstallObserver2 observer;
15609        int installFlags;
15610        final String installerPackageName;
15611        final String volumeUuid;
15612        private InstallArgs mArgs;
15613        private int mRet;
15614        final String packageAbiOverride;
15615        final String[] grantedRuntimePermissions;
15616        final VerificationInfo verificationInfo;
15617        final Certificate[][] certificates;
15618        final int installReason;
15619
15620        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15621                int installFlags, String installerPackageName, String volumeUuid,
15622                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15623                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15624            super(user);
15625            this.origin = origin;
15626            this.move = move;
15627            this.observer = observer;
15628            this.installFlags = installFlags;
15629            this.installerPackageName = installerPackageName;
15630            this.volumeUuid = volumeUuid;
15631            this.verificationInfo = verificationInfo;
15632            this.packageAbiOverride = packageAbiOverride;
15633            this.grantedRuntimePermissions = grantedPermissions;
15634            this.certificates = certificates;
15635            this.installReason = installReason;
15636        }
15637
15638        @Override
15639        public String toString() {
15640            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15641                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15642        }
15643
15644        private int installLocationPolicy(PackageInfoLite pkgLite) {
15645            String packageName = pkgLite.packageName;
15646            int installLocation = pkgLite.installLocation;
15647            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15648            // reader
15649            synchronized (mPackages) {
15650                // Currently installed package which the new package is attempting to replace or
15651                // null if no such package is installed.
15652                PackageParser.Package installedPkg = mPackages.get(packageName);
15653                // Package which currently owns the data which the new package will own if installed.
15654                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15655                // will be null whereas dataOwnerPkg will contain information about the package
15656                // which was uninstalled while keeping its data.
15657                PackageParser.Package dataOwnerPkg = installedPkg;
15658                if (dataOwnerPkg  == null) {
15659                    PackageSetting ps = mSettings.mPackages.get(packageName);
15660                    if (ps != null) {
15661                        dataOwnerPkg = ps.pkg;
15662                    }
15663                }
15664
15665                if (dataOwnerPkg != null) {
15666                    // If installed, the package will get access to data left on the device by its
15667                    // predecessor. As a security measure, this is permited only if this is not a
15668                    // version downgrade or if the predecessor package is marked as debuggable and
15669                    // a downgrade is explicitly requested.
15670                    //
15671                    // On debuggable platform builds, downgrades are permitted even for
15672                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15673                    // not offer security guarantees and thus it's OK to disable some security
15674                    // mechanisms to make debugging/testing easier on those builds. However, even on
15675                    // debuggable builds downgrades of packages are permitted only if requested via
15676                    // installFlags. This is because we aim to keep the behavior of debuggable
15677                    // platform builds as close as possible to the behavior of non-debuggable
15678                    // platform builds.
15679                    final boolean downgradeRequested =
15680                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15681                    final boolean packageDebuggable =
15682                                (dataOwnerPkg.applicationInfo.flags
15683                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15684                    final boolean downgradePermitted =
15685                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15686                    if (!downgradePermitted) {
15687                        try {
15688                            checkDowngrade(dataOwnerPkg, pkgLite);
15689                        } catch (PackageManagerException e) {
15690                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15691                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15692                        }
15693                    }
15694                }
15695
15696                if (installedPkg != null) {
15697                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15698                        // Check for updated system application.
15699                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15700                            if (onSd) {
15701                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15702                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15703                            }
15704                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15705                        } else {
15706                            if (onSd) {
15707                                // Install flag overrides everything.
15708                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15709                            }
15710                            // If current upgrade specifies particular preference
15711                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15712                                // Application explicitly specified internal.
15713                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15714                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15715                                // App explictly prefers external. Let policy decide
15716                            } else {
15717                                // Prefer previous location
15718                                if (isExternal(installedPkg)) {
15719                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15720                                }
15721                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15722                            }
15723                        }
15724                    } else {
15725                        // Invalid install. Return error code
15726                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15727                    }
15728                }
15729            }
15730            // All the special cases have been taken care of.
15731            // Return result based on recommended install location.
15732            if (onSd) {
15733                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15734            }
15735            return pkgLite.recommendedInstallLocation;
15736        }
15737
15738        /*
15739         * Invoke remote method to get package information and install
15740         * location values. Override install location based on default
15741         * policy if needed and then create install arguments based
15742         * on the install location.
15743         */
15744        public void handleStartCopy() throws RemoteException {
15745            int ret = PackageManager.INSTALL_SUCCEEDED;
15746
15747            // If we're already staged, we've firmly committed to an install location
15748            if (origin.staged) {
15749                if (origin.file != null) {
15750                    installFlags |= PackageManager.INSTALL_INTERNAL;
15751                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15752                } else if (origin.cid != null) {
15753                    installFlags |= PackageManager.INSTALL_EXTERNAL;
15754                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
15755                } else {
15756                    throw new IllegalStateException("Invalid stage location");
15757                }
15758            }
15759
15760            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15761            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15762            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15763            PackageInfoLite pkgLite = null;
15764
15765            if (onInt && onSd) {
15766                // Check if both bits are set.
15767                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15768                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15769            } else if (onSd && ephemeral) {
15770                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15771                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15772            } else {
15773                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15774                        packageAbiOverride);
15775
15776                if (DEBUG_EPHEMERAL && ephemeral) {
15777                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15778                }
15779
15780                /*
15781                 * If we have too little free space, try to free cache
15782                 * before giving up.
15783                 */
15784                if (!origin.staged && pkgLite.recommendedInstallLocation
15785                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15786                    // TODO: focus freeing disk space on the target device
15787                    final StorageManager storage = StorageManager.from(mContext);
15788                    final long lowThreshold = storage.getStorageLowBytes(
15789                            Environment.getDataDirectory());
15790
15791                    final long sizeBytes = mContainerService.calculateInstalledSize(
15792                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
15793
15794                    try {
15795                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15796                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15797                                installFlags, packageAbiOverride);
15798                    } catch (InstallerException e) {
15799                        Slog.w(TAG, "Failed to free cache", e);
15800                    }
15801
15802                    /*
15803                     * The cache free must have deleted the file we
15804                     * downloaded to install.
15805                     *
15806                     * TODO: fix the "freeCache" call to not delete
15807                     *       the file we care about.
15808                     */
15809                    if (pkgLite.recommendedInstallLocation
15810                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15811                        pkgLite.recommendedInstallLocation
15812                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15813                    }
15814                }
15815            }
15816
15817            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15818                int loc = pkgLite.recommendedInstallLocation;
15819                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15820                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15821                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15822                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15823                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15824                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15825                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15826                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15827                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15828                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15829                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15830                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15831                } else {
15832                    // Override with defaults if needed.
15833                    loc = installLocationPolicy(pkgLite);
15834                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15835                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15836                    } else if (!onSd && !onInt) {
15837                        // Override install location with flags
15838                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15839                            // Set the flag to install on external media.
15840                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15841                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15842                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15843                            if (DEBUG_EPHEMERAL) {
15844                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15845                            }
15846                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15847                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15848                                    |PackageManager.INSTALL_INTERNAL);
15849                        } else {
15850                            // Make sure the flag for installing on external
15851                            // media is unset
15852                            installFlags |= PackageManager.INSTALL_INTERNAL;
15853                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15854                        }
15855                    }
15856                }
15857            }
15858
15859            final InstallArgs args = createInstallArgs(this);
15860            mArgs = args;
15861
15862            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15863                // TODO: http://b/22976637
15864                // Apps installed for "all" users use the device owner to verify the app
15865                UserHandle verifierUser = getUser();
15866                if (verifierUser == UserHandle.ALL) {
15867                    verifierUser = UserHandle.SYSTEM;
15868                }
15869
15870                /*
15871                 * Determine if we have any installed package verifiers. If we
15872                 * do, then we'll defer to them to verify the packages.
15873                 */
15874                final int requiredUid = mRequiredVerifierPackage == null ? -1
15875                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15876                                verifierUser.getIdentifier());
15877                final int installerUid =
15878                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15879                if (!origin.existing && requiredUid != -1
15880                        && isVerificationEnabled(
15881                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15882                    final Intent verification = new Intent(
15883                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15884                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15885                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15886                            PACKAGE_MIME_TYPE);
15887                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15888
15889                    // Query all live verifiers based on current user state
15890                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15891                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15892
15893                    if (DEBUG_VERIFY) {
15894                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15895                                + verification.toString() + " with " + pkgLite.verifiers.length
15896                                + " optional verifiers");
15897                    }
15898
15899                    final int verificationId = mPendingVerificationToken++;
15900
15901                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15902
15903                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15904                            installerPackageName);
15905
15906                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15907                            installFlags);
15908
15909                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15910                            pkgLite.packageName);
15911
15912                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15913                            pkgLite.versionCode);
15914
15915                    if (verificationInfo != null) {
15916                        if (verificationInfo.originatingUri != null) {
15917                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15918                                    verificationInfo.originatingUri);
15919                        }
15920                        if (verificationInfo.referrer != null) {
15921                            verification.putExtra(Intent.EXTRA_REFERRER,
15922                                    verificationInfo.referrer);
15923                        }
15924                        if (verificationInfo.originatingUid >= 0) {
15925                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15926                                    verificationInfo.originatingUid);
15927                        }
15928                        if (verificationInfo.installerUid >= 0) {
15929                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15930                                    verificationInfo.installerUid);
15931                        }
15932                    }
15933
15934                    final PackageVerificationState verificationState = new PackageVerificationState(
15935                            requiredUid, args);
15936
15937                    mPendingVerification.append(verificationId, verificationState);
15938
15939                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15940                            receivers, verificationState);
15941
15942                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15943                    final long idleDuration = getVerificationTimeout();
15944
15945                    /*
15946                     * If any sufficient verifiers were listed in the package
15947                     * manifest, attempt to ask them.
15948                     */
15949                    if (sufficientVerifiers != null) {
15950                        final int N = sufficientVerifiers.size();
15951                        if (N == 0) {
15952                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15953                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15954                        } else {
15955                            for (int i = 0; i < N; i++) {
15956                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15957                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15958                                        verifierComponent.getPackageName(), idleDuration,
15959                                        verifierUser.getIdentifier(), false, "package verifier");
15960
15961                                final Intent sufficientIntent = new Intent(verification);
15962                                sufficientIntent.setComponent(verifierComponent);
15963                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15964                            }
15965                        }
15966                    }
15967
15968                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15969                            mRequiredVerifierPackage, receivers);
15970                    if (ret == PackageManager.INSTALL_SUCCEEDED
15971                            && mRequiredVerifierPackage != null) {
15972                        Trace.asyncTraceBegin(
15973                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15974                        /*
15975                         * Send the intent to the required verification agent,
15976                         * but only start the verification timeout after the
15977                         * target BroadcastReceivers have run.
15978                         */
15979                        verification.setComponent(requiredVerifierComponent);
15980                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15981                                mRequiredVerifierPackage, idleDuration,
15982                                verifierUser.getIdentifier(), false, "package verifier");
15983                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15984                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15985                                new BroadcastReceiver() {
15986                                    @Override
15987                                    public void onReceive(Context context, Intent intent) {
15988                                        final Message msg = mHandler
15989                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15990                                        msg.arg1 = verificationId;
15991                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15992                                    }
15993                                }, null, 0, null, null);
15994
15995                        /*
15996                         * We don't want the copy to proceed until verification
15997                         * succeeds, so null out this field.
15998                         */
15999                        mArgs = null;
16000                    }
16001                } else {
16002                    /*
16003                     * No package verification is enabled, so immediately start
16004                     * the remote call to initiate copy using temporary file.
16005                     */
16006                    ret = args.copyApk(mContainerService, true);
16007                }
16008            }
16009
16010            mRet = ret;
16011        }
16012
16013        @Override
16014        void handleReturnCode() {
16015            // If mArgs is null, then MCS couldn't be reached. When it
16016            // reconnects, it will try again to install. At that point, this
16017            // will succeed.
16018            if (mArgs != null) {
16019                processPendingInstall(mArgs, mRet);
16020            }
16021        }
16022
16023        @Override
16024        void handleServiceError() {
16025            mArgs = createInstallArgs(this);
16026            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16027        }
16028
16029        public boolean isForwardLocked() {
16030            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16031        }
16032    }
16033
16034    /**
16035     * Used during creation of InstallArgs
16036     *
16037     * @param installFlags package installation flags
16038     * @return true if should be installed on external storage
16039     */
16040    private static boolean installOnExternalAsec(int installFlags) {
16041        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
16042            return false;
16043        }
16044        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
16045            return true;
16046        }
16047        return false;
16048    }
16049
16050    /**
16051     * Used during creation of InstallArgs
16052     *
16053     * @param installFlags package installation flags
16054     * @return true if should be installed as forward locked
16055     */
16056    private static boolean installForwardLocked(int installFlags) {
16057        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16058    }
16059
16060    private InstallArgs createInstallArgs(InstallParams params) {
16061        if (params.move != null) {
16062            return new MoveInstallArgs(params);
16063        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
16064            return new AsecInstallArgs(params);
16065        } else {
16066            return new FileInstallArgs(params);
16067        }
16068    }
16069
16070    /**
16071     * Create args that describe an existing installed package. Typically used
16072     * when cleaning up old installs, or used as a move source.
16073     */
16074    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
16075            String resourcePath, String[] instructionSets) {
16076        final boolean isInAsec;
16077        if (installOnExternalAsec(installFlags)) {
16078            /* Apps on SD card are always in ASEC containers. */
16079            isInAsec = true;
16080        } else if (installForwardLocked(installFlags)
16081                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
16082            /*
16083             * Forward-locked apps are only in ASEC containers if they're the
16084             * new style
16085             */
16086            isInAsec = true;
16087        } else {
16088            isInAsec = false;
16089        }
16090
16091        if (isInAsec) {
16092            return new AsecInstallArgs(codePath, instructionSets,
16093                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
16094        } else {
16095            return new FileInstallArgs(codePath, resourcePath, instructionSets);
16096        }
16097    }
16098
16099    static abstract class InstallArgs {
16100        /** @see InstallParams#origin */
16101        final OriginInfo origin;
16102        /** @see InstallParams#move */
16103        final MoveInfo move;
16104
16105        final IPackageInstallObserver2 observer;
16106        // Always refers to PackageManager flags only
16107        final int installFlags;
16108        final String installerPackageName;
16109        final String volumeUuid;
16110        final UserHandle user;
16111        final String abiOverride;
16112        final String[] installGrantPermissions;
16113        /** If non-null, drop an async trace when the install completes */
16114        final String traceMethod;
16115        final int traceCookie;
16116        final Certificate[][] certificates;
16117        final int installReason;
16118
16119        // The list of instruction sets supported by this app. This is currently
16120        // only used during the rmdex() phase to clean up resources. We can get rid of this
16121        // if we move dex files under the common app path.
16122        /* nullable */ String[] instructionSets;
16123
16124        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16125                int installFlags, String installerPackageName, String volumeUuid,
16126                UserHandle user, String[] instructionSets,
16127                String abiOverride, String[] installGrantPermissions,
16128                String traceMethod, int traceCookie, Certificate[][] certificates,
16129                int installReason) {
16130            this.origin = origin;
16131            this.move = move;
16132            this.installFlags = installFlags;
16133            this.observer = observer;
16134            this.installerPackageName = installerPackageName;
16135            this.volumeUuid = volumeUuid;
16136            this.user = user;
16137            this.instructionSets = instructionSets;
16138            this.abiOverride = abiOverride;
16139            this.installGrantPermissions = installGrantPermissions;
16140            this.traceMethod = traceMethod;
16141            this.traceCookie = traceCookie;
16142            this.certificates = certificates;
16143            this.installReason = installReason;
16144        }
16145
16146        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16147        abstract int doPreInstall(int status);
16148
16149        /**
16150         * Rename package into final resting place. All paths on the given
16151         * scanned package should be updated to reflect the rename.
16152         */
16153        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16154        abstract int doPostInstall(int status, int uid);
16155
16156        /** @see PackageSettingBase#codePathString */
16157        abstract String getCodePath();
16158        /** @see PackageSettingBase#resourcePathString */
16159        abstract String getResourcePath();
16160
16161        // Need installer lock especially for dex file removal.
16162        abstract void cleanUpResourcesLI();
16163        abstract boolean doPostDeleteLI(boolean delete);
16164
16165        /**
16166         * Called before the source arguments are copied. This is used mostly
16167         * for MoveParams when it needs to read the source file to put it in the
16168         * destination.
16169         */
16170        int doPreCopy() {
16171            return PackageManager.INSTALL_SUCCEEDED;
16172        }
16173
16174        /**
16175         * Called after the source arguments are copied. This is used mostly for
16176         * MoveParams when it needs to read the source file to put it in the
16177         * destination.
16178         */
16179        int doPostCopy(int uid) {
16180            return PackageManager.INSTALL_SUCCEEDED;
16181        }
16182
16183        protected boolean isFwdLocked() {
16184            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16185        }
16186
16187        protected boolean isExternalAsec() {
16188            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16189        }
16190
16191        protected boolean isEphemeral() {
16192            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16193        }
16194
16195        UserHandle getUser() {
16196            return user;
16197        }
16198    }
16199
16200    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16201        if (!allCodePaths.isEmpty()) {
16202            if (instructionSets == null) {
16203                throw new IllegalStateException("instructionSet == null");
16204            }
16205            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16206            for (String codePath : allCodePaths) {
16207                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16208                    try {
16209                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16210                    } catch (InstallerException ignored) {
16211                    }
16212                }
16213            }
16214        }
16215    }
16216
16217    /**
16218     * Logic to handle installation of non-ASEC applications, including copying
16219     * and renaming logic.
16220     */
16221    class FileInstallArgs extends InstallArgs {
16222        private File codeFile;
16223        private File resourceFile;
16224
16225        // Example topology:
16226        // /data/app/com.example/base.apk
16227        // /data/app/com.example/split_foo.apk
16228        // /data/app/com.example/lib/arm/libfoo.so
16229        // /data/app/com.example/lib/arm64/libfoo.so
16230        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16231
16232        /** New install */
16233        FileInstallArgs(InstallParams params) {
16234            super(params.origin, params.move, params.observer, params.installFlags,
16235                    params.installerPackageName, params.volumeUuid,
16236                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16237                    params.grantedRuntimePermissions,
16238                    params.traceMethod, params.traceCookie, params.certificates,
16239                    params.installReason);
16240            if (isFwdLocked()) {
16241                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16242            }
16243        }
16244
16245        /** Existing install */
16246        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16247            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16248                    null, null, null, 0, null /*certificates*/,
16249                    PackageManager.INSTALL_REASON_UNKNOWN);
16250            this.codeFile = (codePath != null) ? new File(codePath) : null;
16251            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16252        }
16253
16254        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16255            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16256            try {
16257                return doCopyApk(imcs, temp);
16258            } finally {
16259                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16260            }
16261        }
16262
16263        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16264            if (origin.staged) {
16265                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16266                codeFile = origin.file;
16267                resourceFile = origin.file;
16268                return PackageManager.INSTALL_SUCCEEDED;
16269            }
16270
16271            try {
16272                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16273                final File tempDir =
16274                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16275                codeFile = tempDir;
16276                resourceFile = tempDir;
16277            } catch (IOException e) {
16278                Slog.w(TAG, "Failed to create copy file: " + e);
16279                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16280            }
16281
16282            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16283                @Override
16284                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16285                    if (!FileUtils.isValidExtFilename(name)) {
16286                        throw new IllegalArgumentException("Invalid filename: " + name);
16287                    }
16288                    try {
16289                        final File file = new File(codeFile, name);
16290                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16291                                O_RDWR | O_CREAT, 0644);
16292                        Os.chmod(file.getAbsolutePath(), 0644);
16293                        return new ParcelFileDescriptor(fd);
16294                    } catch (ErrnoException e) {
16295                        throw new RemoteException("Failed to open: " + e.getMessage());
16296                    }
16297                }
16298            };
16299
16300            int ret = PackageManager.INSTALL_SUCCEEDED;
16301            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16302            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16303                Slog.e(TAG, "Failed to copy package");
16304                return ret;
16305            }
16306
16307            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16308            NativeLibraryHelper.Handle handle = null;
16309            try {
16310                handle = NativeLibraryHelper.Handle.create(codeFile);
16311                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16312                        abiOverride);
16313            } catch (IOException e) {
16314                Slog.e(TAG, "Copying native libraries failed", e);
16315                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16316            } finally {
16317                IoUtils.closeQuietly(handle);
16318            }
16319
16320            return ret;
16321        }
16322
16323        int doPreInstall(int status) {
16324            if (status != PackageManager.INSTALL_SUCCEEDED) {
16325                cleanUp();
16326            }
16327            return status;
16328        }
16329
16330        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16331            if (status != PackageManager.INSTALL_SUCCEEDED) {
16332                cleanUp();
16333                return false;
16334            }
16335
16336            final File targetDir = codeFile.getParentFile();
16337            final File beforeCodeFile = codeFile;
16338            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16339
16340            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16341            try {
16342                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16343            } catch (ErrnoException e) {
16344                Slog.w(TAG, "Failed to rename", e);
16345                return false;
16346            }
16347
16348            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16349                Slog.w(TAG, "Failed to restorecon");
16350                return false;
16351            }
16352
16353            // Reflect the rename internally
16354            codeFile = afterCodeFile;
16355            resourceFile = afterCodeFile;
16356
16357            // Reflect the rename in scanned details
16358            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16359            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16360                    afterCodeFile, pkg.baseCodePath));
16361            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16362                    afterCodeFile, pkg.splitCodePaths));
16363
16364            // Reflect the rename in app info
16365            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16366            pkg.setApplicationInfoCodePath(pkg.codePath);
16367            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16368            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16369            pkg.setApplicationInfoResourcePath(pkg.codePath);
16370            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16371            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16372
16373            return true;
16374        }
16375
16376        int doPostInstall(int status, int uid) {
16377            if (status != PackageManager.INSTALL_SUCCEEDED) {
16378                cleanUp();
16379            }
16380            return status;
16381        }
16382
16383        @Override
16384        String getCodePath() {
16385            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16386        }
16387
16388        @Override
16389        String getResourcePath() {
16390            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16391        }
16392
16393        private boolean cleanUp() {
16394            if (codeFile == null || !codeFile.exists()) {
16395                return false;
16396            }
16397
16398            removeCodePathLI(codeFile);
16399
16400            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16401                resourceFile.delete();
16402            }
16403
16404            return true;
16405        }
16406
16407        void cleanUpResourcesLI() {
16408            // Try enumerating all code paths before deleting
16409            List<String> allCodePaths = Collections.EMPTY_LIST;
16410            if (codeFile != null && codeFile.exists()) {
16411                try {
16412                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16413                    allCodePaths = pkg.getAllCodePaths();
16414                } catch (PackageParserException e) {
16415                    // Ignored; we tried our best
16416                }
16417            }
16418
16419            cleanUp();
16420            removeDexFiles(allCodePaths, instructionSets);
16421        }
16422
16423        boolean doPostDeleteLI(boolean delete) {
16424            // XXX err, shouldn't we respect the delete flag?
16425            cleanUpResourcesLI();
16426            return true;
16427        }
16428    }
16429
16430    private boolean isAsecExternal(String cid) {
16431        final String asecPath = PackageHelper.getSdFilesystem(cid);
16432        return !asecPath.startsWith(mAsecInternalPath);
16433    }
16434
16435    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16436            PackageManagerException {
16437        if (copyRet < 0) {
16438            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16439                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16440                throw new PackageManagerException(copyRet, message);
16441            }
16442        }
16443    }
16444
16445    /**
16446     * Extract the StorageManagerService "container ID" from the full code path of an
16447     * .apk.
16448     */
16449    static String cidFromCodePath(String fullCodePath) {
16450        int eidx = fullCodePath.lastIndexOf("/");
16451        String subStr1 = fullCodePath.substring(0, eidx);
16452        int sidx = subStr1.lastIndexOf("/");
16453        return subStr1.substring(sidx+1, eidx);
16454    }
16455
16456    /**
16457     * Logic to handle installation of ASEC applications, including copying and
16458     * renaming logic.
16459     */
16460    class AsecInstallArgs extends InstallArgs {
16461        static final String RES_FILE_NAME = "pkg.apk";
16462        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16463
16464        String cid;
16465        String packagePath;
16466        String resourcePath;
16467
16468        /** New install */
16469        AsecInstallArgs(InstallParams params) {
16470            super(params.origin, params.move, params.observer, params.installFlags,
16471                    params.installerPackageName, params.volumeUuid,
16472                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16473                    params.grantedRuntimePermissions,
16474                    params.traceMethod, params.traceCookie, params.certificates,
16475                    params.installReason);
16476        }
16477
16478        /** Existing install */
16479        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16480                        boolean isExternal, boolean isForwardLocked) {
16481            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16482                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16483                    instructionSets, null, null, null, 0, null /*certificates*/,
16484                    PackageManager.INSTALL_REASON_UNKNOWN);
16485            // Hackily pretend we're still looking at a full code path
16486            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16487                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16488            }
16489
16490            // Extract cid from fullCodePath
16491            int eidx = fullCodePath.lastIndexOf("/");
16492            String subStr1 = fullCodePath.substring(0, eidx);
16493            int sidx = subStr1.lastIndexOf("/");
16494            cid = subStr1.substring(sidx+1, eidx);
16495            setMountPath(subStr1);
16496        }
16497
16498        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16499            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16500                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16501                    instructionSets, null, null, null, 0, null /*certificates*/,
16502                    PackageManager.INSTALL_REASON_UNKNOWN);
16503            this.cid = cid;
16504            setMountPath(PackageHelper.getSdDir(cid));
16505        }
16506
16507        void createCopyFile() {
16508            cid = mInstallerService.allocateExternalStageCidLegacy();
16509        }
16510
16511        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16512            if (origin.staged && origin.cid != null) {
16513                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16514                cid = origin.cid;
16515                setMountPath(PackageHelper.getSdDir(cid));
16516                return PackageManager.INSTALL_SUCCEEDED;
16517            }
16518
16519            if (temp) {
16520                createCopyFile();
16521            } else {
16522                /*
16523                 * Pre-emptively destroy the container since it's destroyed if
16524                 * copying fails due to it existing anyway.
16525                 */
16526                PackageHelper.destroySdDir(cid);
16527            }
16528
16529            final String newMountPath = imcs.copyPackageToContainer(
16530                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16531                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16532
16533            if (newMountPath != null) {
16534                setMountPath(newMountPath);
16535                return PackageManager.INSTALL_SUCCEEDED;
16536            } else {
16537                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16538            }
16539        }
16540
16541        @Override
16542        String getCodePath() {
16543            return packagePath;
16544        }
16545
16546        @Override
16547        String getResourcePath() {
16548            return resourcePath;
16549        }
16550
16551        int doPreInstall(int status) {
16552            if (status != PackageManager.INSTALL_SUCCEEDED) {
16553                // Destroy container
16554                PackageHelper.destroySdDir(cid);
16555            } else {
16556                boolean mounted = PackageHelper.isContainerMounted(cid);
16557                if (!mounted) {
16558                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16559                            Process.SYSTEM_UID);
16560                    if (newMountPath != null) {
16561                        setMountPath(newMountPath);
16562                    } else {
16563                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16564                    }
16565                }
16566            }
16567            return status;
16568        }
16569
16570        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16571            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16572            String newMountPath = null;
16573            if (PackageHelper.isContainerMounted(cid)) {
16574                // Unmount the container
16575                if (!PackageHelper.unMountSdDir(cid)) {
16576                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16577                    return false;
16578                }
16579            }
16580            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16581                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16582                        " which might be stale. Will try to clean up.");
16583                // Clean up the stale container and proceed to recreate.
16584                if (!PackageHelper.destroySdDir(newCacheId)) {
16585                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16586                    return false;
16587                }
16588                // Successfully cleaned up stale container. Try to rename again.
16589                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16590                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16591                            + " inspite of cleaning it up.");
16592                    return false;
16593                }
16594            }
16595            if (!PackageHelper.isContainerMounted(newCacheId)) {
16596                Slog.w(TAG, "Mounting container " + newCacheId);
16597                newMountPath = PackageHelper.mountSdDir(newCacheId,
16598                        getEncryptKey(), Process.SYSTEM_UID);
16599            } else {
16600                newMountPath = PackageHelper.getSdDir(newCacheId);
16601            }
16602            if (newMountPath == null) {
16603                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16604                return false;
16605            }
16606            Log.i(TAG, "Succesfully renamed " + cid +
16607                    " to " + newCacheId +
16608                    " at new path: " + newMountPath);
16609            cid = newCacheId;
16610
16611            final File beforeCodeFile = new File(packagePath);
16612            setMountPath(newMountPath);
16613            final File afterCodeFile = new File(packagePath);
16614
16615            // Reflect the rename in scanned details
16616            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16617            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16618                    afterCodeFile, pkg.baseCodePath));
16619            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16620                    afterCodeFile, pkg.splitCodePaths));
16621
16622            // Reflect the rename in app info
16623            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16624            pkg.setApplicationInfoCodePath(pkg.codePath);
16625            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16626            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16627            pkg.setApplicationInfoResourcePath(pkg.codePath);
16628            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16629            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16630
16631            return true;
16632        }
16633
16634        private void setMountPath(String mountPath) {
16635            final File mountFile = new File(mountPath);
16636
16637            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16638            if (monolithicFile.exists()) {
16639                packagePath = monolithicFile.getAbsolutePath();
16640                if (isFwdLocked()) {
16641                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16642                } else {
16643                    resourcePath = packagePath;
16644                }
16645            } else {
16646                packagePath = mountFile.getAbsolutePath();
16647                resourcePath = packagePath;
16648            }
16649        }
16650
16651        int doPostInstall(int status, int uid) {
16652            if (status != PackageManager.INSTALL_SUCCEEDED) {
16653                cleanUp();
16654            } else {
16655                final int groupOwner;
16656                final String protectedFile;
16657                if (isFwdLocked()) {
16658                    groupOwner = UserHandle.getSharedAppGid(uid);
16659                    protectedFile = RES_FILE_NAME;
16660                } else {
16661                    groupOwner = -1;
16662                    protectedFile = null;
16663                }
16664
16665                if (uid < Process.FIRST_APPLICATION_UID
16666                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16667                    Slog.e(TAG, "Failed to finalize " + cid);
16668                    PackageHelper.destroySdDir(cid);
16669                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16670                }
16671
16672                boolean mounted = PackageHelper.isContainerMounted(cid);
16673                if (!mounted) {
16674                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16675                }
16676            }
16677            return status;
16678        }
16679
16680        private void cleanUp() {
16681            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16682
16683            // Destroy secure container
16684            PackageHelper.destroySdDir(cid);
16685        }
16686
16687        private List<String> getAllCodePaths() {
16688            final File codeFile = new File(getCodePath());
16689            if (codeFile != null && codeFile.exists()) {
16690                try {
16691                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16692                    return pkg.getAllCodePaths();
16693                } catch (PackageParserException e) {
16694                    // Ignored; we tried our best
16695                }
16696            }
16697            return Collections.EMPTY_LIST;
16698        }
16699
16700        void cleanUpResourcesLI() {
16701            // Enumerate all code paths before deleting
16702            cleanUpResourcesLI(getAllCodePaths());
16703        }
16704
16705        private void cleanUpResourcesLI(List<String> allCodePaths) {
16706            cleanUp();
16707            removeDexFiles(allCodePaths, instructionSets);
16708        }
16709
16710        String getPackageName() {
16711            return getAsecPackageName(cid);
16712        }
16713
16714        boolean doPostDeleteLI(boolean delete) {
16715            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
16716            final List<String> allCodePaths = getAllCodePaths();
16717            boolean mounted = PackageHelper.isContainerMounted(cid);
16718            if (mounted) {
16719                // Unmount first
16720                if (PackageHelper.unMountSdDir(cid)) {
16721                    mounted = false;
16722                }
16723            }
16724            if (!mounted && delete) {
16725                cleanUpResourcesLI(allCodePaths);
16726            }
16727            return !mounted;
16728        }
16729
16730        @Override
16731        int doPreCopy() {
16732            if (isFwdLocked()) {
16733                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
16734                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
16735                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16736                }
16737            }
16738
16739            return PackageManager.INSTALL_SUCCEEDED;
16740        }
16741
16742        @Override
16743        int doPostCopy(int uid) {
16744            if (isFwdLocked()) {
16745                if (uid < Process.FIRST_APPLICATION_UID
16746                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
16747                                RES_FILE_NAME)) {
16748                    Slog.e(TAG, "Failed to finalize " + cid);
16749                    PackageHelper.destroySdDir(cid);
16750                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16751                }
16752            }
16753
16754            return PackageManager.INSTALL_SUCCEEDED;
16755        }
16756    }
16757
16758    /**
16759     * Logic to handle movement of existing installed applications.
16760     */
16761    class MoveInstallArgs extends InstallArgs {
16762        private File codeFile;
16763        private File resourceFile;
16764
16765        /** New install */
16766        MoveInstallArgs(InstallParams params) {
16767            super(params.origin, params.move, params.observer, params.installFlags,
16768                    params.installerPackageName, params.volumeUuid,
16769                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16770                    params.grantedRuntimePermissions,
16771                    params.traceMethod, params.traceCookie, params.certificates,
16772                    params.installReason);
16773        }
16774
16775        int copyApk(IMediaContainerService imcs, boolean temp) {
16776            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16777                    + move.fromUuid + " to " + move.toUuid);
16778            synchronized (mInstaller) {
16779                try {
16780                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16781                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16782                } catch (InstallerException e) {
16783                    Slog.w(TAG, "Failed to move app", e);
16784                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16785                }
16786            }
16787
16788            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16789            resourceFile = codeFile;
16790            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16791
16792            return PackageManager.INSTALL_SUCCEEDED;
16793        }
16794
16795        int doPreInstall(int status) {
16796            if (status != PackageManager.INSTALL_SUCCEEDED) {
16797                cleanUp(move.toUuid);
16798            }
16799            return status;
16800        }
16801
16802        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16803            if (status != PackageManager.INSTALL_SUCCEEDED) {
16804                cleanUp(move.toUuid);
16805                return false;
16806            }
16807
16808            // Reflect the move in app info
16809            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16810            pkg.setApplicationInfoCodePath(pkg.codePath);
16811            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16812            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16813            pkg.setApplicationInfoResourcePath(pkg.codePath);
16814            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16815            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16816
16817            return true;
16818        }
16819
16820        int doPostInstall(int status, int uid) {
16821            if (status == PackageManager.INSTALL_SUCCEEDED) {
16822                cleanUp(move.fromUuid);
16823            } else {
16824                cleanUp(move.toUuid);
16825            }
16826            return status;
16827        }
16828
16829        @Override
16830        String getCodePath() {
16831            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16832        }
16833
16834        @Override
16835        String getResourcePath() {
16836            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16837        }
16838
16839        private boolean cleanUp(String volumeUuid) {
16840            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16841                    move.dataAppName);
16842            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16843            final int[] userIds = sUserManager.getUserIds();
16844            synchronized (mInstallLock) {
16845                // Clean up both app data and code
16846                // All package moves are frozen until finished
16847                for (int userId : userIds) {
16848                    try {
16849                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16850                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16851                    } catch (InstallerException e) {
16852                        Slog.w(TAG, String.valueOf(e));
16853                    }
16854                }
16855                removeCodePathLI(codeFile);
16856            }
16857            return true;
16858        }
16859
16860        void cleanUpResourcesLI() {
16861            throw new UnsupportedOperationException();
16862        }
16863
16864        boolean doPostDeleteLI(boolean delete) {
16865            throw new UnsupportedOperationException();
16866        }
16867    }
16868
16869    static String getAsecPackageName(String packageCid) {
16870        int idx = packageCid.lastIndexOf("-");
16871        if (idx == -1) {
16872            return packageCid;
16873        }
16874        return packageCid.substring(0, idx);
16875    }
16876
16877    // Utility method used to create code paths based on package name and available index.
16878    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16879        String idxStr = "";
16880        int idx = 1;
16881        // Fall back to default value of idx=1 if prefix is not
16882        // part of oldCodePath
16883        if (oldCodePath != null) {
16884            String subStr = oldCodePath;
16885            // Drop the suffix right away
16886            if (suffix != null && subStr.endsWith(suffix)) {
16887                subStr = subStr.substring(0, subStr.length() - suffix.length());
16888            }
16889            // If oldCodePath already contains prefix find out the
16890            // ending index to either increment or decrement.
16891            int sidx = subStr.lastIndexOf(prefix);
16892            if (sidx != -1) {
16893                subStr = subStr.substring(sidx + prefix.length());
16894                if (subStr != null) {
16895                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16896                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16897                    }
16898                    try {
16899                        idx = Integer.parseInt(subStr);
16900                        if (idx <= 1) {
16901                            idx++;
16902                        } else {
16903                            idx--;
16904                        }
16905                    } catch(NumberFormatException e) {
16906                    }
16907                }
16908            }
16909        }
16910        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16911        return prefix + idxStr;
16912    }
16913
16914    private File getNextCodePath(File targetDir, String packageName) {
16915        File result;
16916        SecureRandom random = new SecureRandom();
16917        byte[] bytes = new byte[16];
16918        do {
16919            random.nextBytes(bytes);
16920            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16921            result = new File(targetDir, packageName + "-" + suffix);
16922        } while (result.exists());
16923        return result;
16924    }
16925
16926    // Utility method that returns the relative package path with respect
16927    // to the installation directory. Like say for /data/data/com.test-1.apk
16928    // string com.test-1 is returned.
16929    static String deriveCodePathName(String codePath) {
16930        if (codePath == null) {
16931            return null;
16932        }
16933        final File codeFile = new File(codePath);
16934        final String name = codeFile.getName();
16935        if (codeFile.isDirectory()) {
16936            return name;
16937        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16938            final int lastDot = name.lastIndexOf('.');
16939            return name.substring(0, lastDot);
16940        } else {
16941            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16942            return null;
16943        }
16944    }
16945
16946    static class PackageInstalledInfo {
16947        String name;
16948        int uid;
16949        // The set of users that originally had this package installed.
16950        int[] origUsers;
16951        // The set of users that now have this package installed.
16952        int[] newUsers;
16953        PackageParser.Package pkg;
16954        int returnCode;
16955        String returnMsg;
16956        PackageRemovedInfo removedInfo;
16957        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16958
16959        public void setError(int code, String msg) {
16960            setReturnCode(code);
16961            setReturnMessage(msg);
16962            Slog.w(TAG, msg);
16963        }
16964
16965        public void setError(String msg, PackageParserException e) {
16966            setReturnCode(e.error);
16967            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16968            Slog.w(TAG, msg, e);
16969        }
16970
16971        public void setError(String msg, PackageManagerException e) {
16972            returnCode = e.error;
16973            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16974            Slog.w(TAG, msg, e);
16975        }
16976
16977        public void setReturnCode(int returnCode) {
16978            this.returnCode = returnCode;
16979            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16980            for (int i = 0; i < childCount; i++) {
16981                addedChildPackages.valueAt(i).returnCode = returnCode;
16982            }
16983        }
16984
16985        private void setReturnMessage(String returnMsg) {
16986            this.returnMsg = returnMsg;
16987            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16988            for (int i = 0; i < childCount; i++) {
16989                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16990            }
16991        }
16992
16993        // In some error cases we want to convey more info back to the observer
16994        String origPackage;
16995        String origPermission;
16996    }
16997
16998    /*
16999     * Install a non-existing package.
17000     */
17001    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
17002            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
17003            PackageInstalledInfo res, int installReason) {
17004        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
17005
17006        // Remember this for later, in case we need to rollback this install
17007        String pkgName = pkg.packageName;
17008
17009        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17010
17011        synchronized(mPackages) {
17012            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
17013            if (renamedPackage != null) {
17014                // A package with the same name is already installed, though
17015                // it has been renamed to an older name.  The package we
17016                // are trying to install should be installed as an update to
17017                // the existing one, but that has not been requested, so bail.
17018                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17019                        + " without first uninstalling package running as "
17020                        + renamedPackage);
17021                return;
17022            }
17023            if (mPackages.containsKey(pkgName)) {
17024                // Don't allow installation over an existing package with the same name.
17025                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
17026                        + " without first uninstalling.");
17027                return;
17028            }
17029        }
17030
17031        try {
17032            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
17033                    System.currentTimeMillis(), user);
17034
17035            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
17036
17037            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17038                prepareAppDataAfterInstallLIF(newPackage);
17039
17040            } else {
17041                // Remove package from internal structures, but keep around any
17042                // data that might have already existed
17043                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
17044                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
17045            }
17046        } catch (PackageManagerException e) {
17047            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17048        }
17049
17050        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17051    }
17052
17053    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
17054        // Can't rotate keys during boot or if sharedUser.
17055        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
17056                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
17057            return false;
17058        }
17059        // app is using upgradeKeySets; make sure all are valid
17060        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17061        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
17062        for (int i = 0; i < upgradeKeySets.length; i++) {
17063            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
17064                Slog.wtf(TAG, "Package "
17065                         + (oldPs.name != null ? oldPs.name : "<null>")
17066                         + " contains upgrade-key-set reference to unknown key-set: "
17067                         + upgradeKeySets[i]
17068                         + " reverting to signatures check.");
17069                return false;
17070            }
17071        }
17072        return true;
17073    }
17074
17075    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
17076        // Upgrade keysets are being used.  Determine if new package has a superset of the
17077        // required keys.
17078        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
17079        KeySetManagerService ksms = mSettings.mKeySetManagerService;
17080        for (int i = 0; i < upgradeKeySets.length; i++) {
17081            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
17082            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
17083                return true;
17084            }
17085        }
17086        return false;
17087    }
17088
17089    private static void updateDigest(MessageDigest digest, File file) throws IOException {
17090        try (DigestInputStream digestStream =
17091                new DigestInputStream(new FileInputStream(file), digest)) {
17092            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
17093        }
17094    }
17095
17096    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
17097            UserHandle user, String installerPackageName, PackageInstalledInfo res,
17098            int installReason) {
17099        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17100
17101        final PackageParser.Package oldPackage;
17102        final PackageSetting ps;
17103        final String pkgName = pkg.packageName;
17104        final int[] allUsers;
17105        final int[] installedUsers;
17106
17107        synchronized(mPackages) {
17108            oldPackage = mPackages.get(pkgName);
17109            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17110
17111            // don't allow upgrade to target a release SDK from a pre-release SDK
17112            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17113                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17114            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17115                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17116            if (oldTargetsPreRelease
17117                    && !newTargetsPreRelease
17118                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17119                Slog.w(TAG, "Can't install package targeting released sdk");
17120                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17121                return;
17122            }
17123
17124            ps = mSettings.mPackages.get(pkgName);
17125
17126            // verify signatures are valid
17127            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17128                if (!checkUpgradeKeySetLP(ps, pkg)) {
17129                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17130                            "New package not signed by keys specified by upgrade-keysets: "
17131                                    + pkgName);
17132                    return;
17133                }
17134            } else {
17135                // default to original signature matching
17136                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17137                        != PackageManager.SIGNATURE_MATCH) {
17138                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17139                            "New package has a different signature: " + pkgName);
17140                    return;
17141                }
17142            }
17143
17144            // don't allow a system upgrade unless the upgrade hash matches
17145            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17146                byte[] digestBytes = null;
17147                try {
17148                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17149                    updateDigest(digest, new File(pkg.baseCodePath));
17150                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17151                        for (String path : pkg.splitCodePaths) {
17152                            updateDigest(digest, new File(path));
17153                        }
17154                    }
17155                    digestBytes = digest.digest();
17156                } catch (NoSuchAlgorithmException | IOException e) {
17157                    res.setError(INSTALL_FAILED_INVALID_APK,
17158                            "Could not compute hash: " + pkgName);
17159                    return;
17160                }
17161                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17162                    res.setError(INSTALL_FAILED_INVALID_APK,
17163                            "New package fails restrict-update check: " + pkgName);
17164                    return;
17165                }
17166                // retain upgrade restriction
17167                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17168            }
17169
17170            // Check for shared user id changes
17171            String invalidPackageName =
17172                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17173            if (invalidPackageName != null) {
17174                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17175                        "Package " + invalidPackageName + " tried to change user "
17176                                + oldPackage.mSharedUserId);
17177                return;
17178            }
17179
17180            // In case of rollback, remember per-user/profile install state
17181            allUsers = sUserManager.getUserIds();
17182            installedUsers = ps.queryInstalledUsers(allUsers, true);
17183
17184            // don't allow an upgrade from full to ephemeral
17185            if (isInstantApp) {
17186                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17187                    for (int currentUser : allUsers) {
17188                        if (!ps.getInstantApp(currentUser)) {
17189                            // can't downgrade from full to instant
17190                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17191                                    + " for user: " + currentUser);
17192                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17193                            return;
17194                        }
17195                    }
17196                } else if (!ps.getInstantApp(user.getIdentifier())) {
17197                    // can't downgrade from full to instant
17198                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17199                            + " for user: " + user.getIdentifier());
17200                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17201                    return;
17202                }
17203            }
17204        }
17205
17206        // Update what is removed
17207        res.removedInfo = new PackageRemovedInfo(this);
17208        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17209        res.removedInfo.removedPackage = oldPackage.packageName;
17210        res.removedInfo.installerPackageName = ps.installerPackageName;
17211        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17212        res.removedInfo.isUpdate = true;
17213        res.removedInfo.origUsers = installedUsers;
17214        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17215        for (int i = 0; i < installedUsers.length; i++) {
17216            final int userId = installedUsers[i];
17217            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17218        }
17219
17220        final int childCount = (oldPackage.childPackages != null)
17221                ? oldPackage.childPackages.size() : 0;
17222        for (int i = 0; i < childCount; i++) {
17223            boolean childPackageUpdated = false;
17224            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17225            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17226            if (res.addedChildPackages != null) {
17227                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17228                if (childRes != null) {
17229                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17230                    childRes.removedInfo.removedPackage = childPkg.packageName;
17231                    if (childPs != null) {
17232                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17233                    }
17234                    childRes.removedInfo.isUpdate = true;
17235                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17236                    childPackageUpdated = true;
17237                }
17238            }
17239            if (!childPackageUpdated) {
17240                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17241                childRemovedRes.removedPackage = childPkg.packageName;
17242                if (childPs != null) {
17243                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17244                }
17245                childRemovedRes.isUpdate = false;
17246                childRemovedRes.dataRemoved = true;
17247                synchronized (mPackages) {
17248                    if (childPs != null) {
17249                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17250                    }
17251                }
17252                if (res.removedInfo.removedChildPackages == null) {
17253                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17254                }
17255                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17256            }
17257        }
17258
17259        boolean sysPkg = (isSystemApp(oldPackage));
17260        if (sysPkg) {
17261            // Set the system/privileged flags as needed
17262            final boolean privileged =
17263                    (oldPackage.applicationInfo.privateFlags
17264                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17265            final int systemPolicyFlags = policyFlags
17266                    | PackageParser.PARSE_IS_SYSTEM
17267                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17268
17269            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17270                    user, allUsers, installerPackageName, res, installReason);
17271        } else {
17272            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17273                    user, allUsers, installerPackageName, res, installReason);
17274        }
17275    }
17276
17277    @Override
17278    public List<String> getPreviousCodePaths(String packageName) {
17279        final int callingUid = Binder.getCallingUid();
17280        final List<String> result = new ArrayList<>();
17281        if (getInstantAppPackageName(callingUid) != null) {
17282            return result;
17283        }
17284        final PackageSetting ps = mSettings.mPackages.get(packageName);
17285        if (ps != null
17286                && ps.oldCodePaths != null
17287                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17288            result.addAll(ps.oldCodePaths);
17289        }
17290        return result;
17291    }
17292
17293    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17294            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17295            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17296            int installReason) {
17297        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17298                + deletedPackage);
17299
17300        String pkgName = deletedPackage.packageName;
17301        boolean deletedPkg = true;
17302        boolean addedPkg = false;
17303        boolean updatedSettings = false;
17304        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17305        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17306                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17307
17308        final long origUpdateTime = (pkg.mExtras != null)
17309                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17310
17311        // First delete the existing package while retaining the data directory
17312        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17313                res.removedInfo, true, pkg)) {
17314            // If the existing package wasn't successfully deleted
17315            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17316            deletedPkg = false;
17317        } else {
17318            // Successfully deleted the old package; proceed with replace.
17319
17320            // If deleted package lived in a container, give users a chance to
17321            // relinquish resources before killing.
17322            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17323                if (DEBUG_INSTALL) {
17324                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17325                }
17326                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17327                final ArrayList<String> pkgList = new ArrayList<String>(1);
17328                pkgList.add(deletedPackage.applicationInfo.packageName);
17329                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17330            }
17331
17332            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17333                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17334            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17335
17336            try {
17337                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17338                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17339                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17340                        installReason);
17341
17342                // Update the in-memory copy of the previous code paths.
17343                PackageSetting ps = mSettings.mPackages.get(pkgName);
17344                if (!killApp) {
17345                    if (ps.oldCodePaths == null) {
17346                        ps.oldCodePaths = new ArraySet<>();
17347                    }
17348                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17349                    if (deletedPackage.splitCodePaths != null) {
17350                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17351                    }
17352                } else {
17353                    ps.oldCodePaths = null;
17354                }
17355                if (ps.childPackageNames != null) {
17356                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17357                        final String childPkgName = ps.childPackageNames.get(i);
17358                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17359                        childPs.oldCodePaths = ps.oldCodePaths;
17360                    }
17361                }
17362                // set instant app status, but, only if it's explicitly specified
17363                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17364                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17365                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17366                prepareAppDataAfterInstallLIF(newPackage);
17367                addedPkg = true;
17368                mDexManager.notifyPackageUpdated(newPackage.packageName,
17369                        newPackage.baseCodePath, newPackage.splitCodePaths);
17370            } catch (PackageManagerException e) {
17371                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17372            }
17373        }
17374
17375        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17376            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17377
17378            // Revert all internal state mutations and added folders for the failed install
17379            if (addedPkg) {
17380                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17381                        res.removedInfo, true, null);
17382            }
17383
17384            // Restore the old package
17385            if (deletedPkg) {
17386                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17387                File restoreFile = new File(deletedPackage.codePath);
17388                // Parse old package
17389                boolean oldExternal = isExternal(deletedPackage);
17390                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17391                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17392                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17393                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17394                try {
17395                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17396                            null);
17397                } catch (PackageManagerException e) {
17398                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17399                            + e.getMessage());
17400                    return;
17401                }
17402
17403                synchronized (mPackages) {
17404                    // Ensure the installer package name up to date
17405                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17406
17407                    // Update permissions for restored package
17408                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17409
17410                    mSettings.writeLPr();
17411                }
17412
17413                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17414            }
17415        } else {
17416            synchronized (mPackages) {
17417                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17418                if (ps != null) {
17419                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17420                    if (res.removedInfo.removedChildPackages != null) {
17421                        final int childCount = res.removedInfo.removedChildPackages.size();
17422                        // Iterate in reverse as we may modify the collection
17423                        for (int i = childCount - 1; i >= 0; i--) {
17424                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17425                            if (res.addedChildPackages.containsKey(childPackageName)) {
17426                                res.removedInfo.removedChildPackages.removeAt(i);
17427                            } else {
17428                                PackageRemovedInfo childInfo = res.removedInfo
17429                                        .removedChildPackages.valueAt(i);
17430                                childInfo.removedForAllUsers = mPackages.get(
17431                                        childInfo.removedPackage) == null;
17432                            }
17433                        }
17434                    }
17435                }
17436            }
17437        }
17438    }
17439
17440    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17441            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17442            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17443            int installReason) {
17444        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17445                + ", old=" + deletedPackage);
17446
17447        final boolean disabledSystem;
17448
17449        // Remove existing system package
17450        removePackageLI(deletedPackage, true);
17451
17452        synchronized (mPackages) {
17453            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17454        }
17455        if (!disabledSystem) {
17456            // We didn't need to disable the .apk as a current system package,
17457            // which means we are replacing another update that is already
17458            // installed.  We need to make sure to delete the older one's .apk.
17459            res.removedInfo.args = createInstallArgsForExisting(0,
17460                    deletedPackage.applicationInfo.getCodePath(),
17461                    deletedPackage.applicationInfo.getResourcePath(),
17462                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17463        } else {
17464            res.removedInfo.args = null;
17465        }
17466
17467        // Successfully disabled the old package. Now proceed with re-installation
17468        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17469                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17470        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17471
17472        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17473        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17474                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17475
17476        PackageParser.Package newPackage = null;
17477        try {
17478            // Add the package to the internal data structures
17479            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17480
17481            // Set the update and install times
17482            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17483            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17484                    System.currentTimeMillis());
17485
17486            // Update the package dynamic state if succeeded
17487            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17488                // Now that the install succeeded make sure we remove data
17489                // directories for any child package the update removed.
17490                final int deletedChildCount = (deletedPackage.childPackages != null)
17491                        ? deletedPackage.childPackages.size() : 0;
17492                final int newChildCount = (newPackage.childPackages != null)
17493                        ? newPackage.childPackages.size() : 0;
17494                for (int i = 0; i < deletedChildCount; i++) {
17495                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17496                    boolean childPackageDeleted = true;
17497                    for (int j = 0; j < newChildCount; j++) {
17498                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17499                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17500                            childPackageDeleted = false;
17501                            break;
17502                        }
17503                    }
17504                    if (childPackageDeleted) {
17505                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17506                                deletedChildPkg.packageName);
17507                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17508                            PackageRemovedInfo removedChildRes = res.removedInfo
17509                                    .removedChildPackages.get(deletedChildPkg.packageName);
17510                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17511                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17512                        }
17513                    }
17514                }
17515
17516                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17517                        installReason);
17518                prepareAppDataAfterInstallLIF(newPackage);
17519
17520                mDexManager.notifyPackageUpdated(newPackage.packageName,
17521                            newPackage.baseCodePath, newPackage.splitCodePaths);
17522            }
17523        } catch (PackageManagerException e) {
17524            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17525            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17526        }
17527
17528        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17529            // Re installation failed. Restore old information
17530            // Remove new pkg information
17531            if (newPackage != null) {
17532                removeInstalledPackageLI(newPackage, true);
17533            }
17534            // Add back the old system package
17535            try {
17536                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17537            } catch (PackageManagerException e) {
17538                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17539            }
17540
17541            synchronized (mPackages) {
17542                if (disabledSystem) {
17543                    enableSystemPackageLPw(deletedPackage);
17544                }
17545
17546                // Ensure the installer package name up to date
17547                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17548
17549                // Update permissions for restored package
17550                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17551
17552                mSettings.writeLPr();
17553            }
17554
17555            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17556                    + " after failed upgrade");
17557        }
17558    }
17559
17560    /**
17561     * Checks whether the parent or any of the child packages have a change shared
17562     * user. For a package to be a valid update the shred users of the parent and
17563     * the children should match. We may later support changing child shared users.
17564     * @param oldPkg The updated package.
17565     * @param newPkg The update package.
17566     * @return The shared user that change between the versions.
17567     */
17568    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17569            PackageParser.Package newPkg) {
17570        // Check parent shared user
17571        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17572            return newPkg.packageName;
17573        }
17574        // Check child shared users
17575        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17576        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17577        for (int i = 0; i < newChildCount; i++) {
17578            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17579            // If this child was present, did it have the same shared user?
17580            for (int j = 0; j < oldChildCount; j++) {
17581                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17582                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17583                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17584                    return newChildPkg.packageName;
17585                }
17586            }
17587        }
17588        return null;
17589    }
17590
17591    private void removeNativeBinariesLI(PackageSetting ps) {
17592        // Remove the lib path for the parent package
17593        if (ps != null) {
17594            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17595            // Remove the lib path for the child packages
17596            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17597            for (int i = 0; i < childCount; i++) {
17598                PackageSetting childPs = null;
17599                synchronized (mPackages) {
17600                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17601                }
17602                if (childPs != null) {
17603                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17604                            .legacyNativeLibraryPathString);
17605                }
17606            }
17607        }
17608    }
17609
17610    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17611        // Enable the parent package
17612        mSettings.enableSystemPackageLPw(pkg.packageName);
17613        // Enable the child packages
17614        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17615        for (int i = 0; i < childCount; i++) {
17616            PackageParser.Package childPkg = pkg.childPackages.get(i);
17617            mSettings.enableSystemPackageLPw(childPkg.packageName);
17618        }
17619    }
17620
17621    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17622            PackageParser.Package newPkg) {
17623        // Disable the parent package (parent always replaced)
17624        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17625        // Disable the child packages
17626        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17627        for (int i = 0; i < childCount; i++) {
17628            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17629            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17630            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17631        }
17632        return disabled;
17633    }
17634
17635    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17636            String installerPackageName) {
17637        // Enable the parent package
17638        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17639        // Enable the child packages
17640        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17641        for (int i = 0; i < childCount; i++) {
17642            PackageParser.Package childPkg = pkg.childPackages.get(i);
17643            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17644        }
17645    }
17646
17647    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17648        // Collect all used permissions in the UID
17649        ArraySet<String> usedPermissions = new ArraySet<>();
17650        final int packageCount = su.packages.size();
17651        for (int i = 0; i < packageCount; i++) {
17652            PackageSetting ps = su.packages.valueAt(i);
17653            if (ps.pkg == null) {
17654                continue;
17655            }
17656            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17657            for (int j = 0; j < requestedPermCount; j++) {
17658                String permission = ps.pkg.requestedPermissions.get(j);
17659                BasePermission bp = mSettings.mPermissions.get(permission);
17660                if (bp != null) {
17661                    usedPermissions.add(permission);
17662                }
17663            }
17664        }
17665
17666        PermissionsState permissionsState = su.getPermissionsState();
17667        // Prune install permissions
17668        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17669        final int installPermCount = installPermStates.size();
17670        for (int i = installPermCount - 1; i >= 0;  i--) {
17671            PermissionState permissionState = installPermStates.get(i);
17672            if (!usedPermissions.contains(permissionState.getName())) {
17673                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17674                if (bp != null) {
17675                    permissionsState.revokeInstallPermission(bp);
17676                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17677                            PackageManager.MASK_PERMISSION_FLAGS, 0);
17678                }
17679            }
17680        }
17681
17682        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17683
17684        // Prune runtime permissions
17685        for (int userId : allUserIds) {
17686            List<PermissionState> runtimePermStates = permissionsState
17687                    .getRuntimePermissionStates(userId);
17688            final int runtimePermCount = runtimePermStates.size();
17689            for (int i = runtimePermCount - 1; i >= 0; i--) {
17690                PermissionState permissionState = runtimePermStates.get(i);
17691                if (!usedPermissions.contains(permissionState.getName())) {
17692                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17693                    if (bp != null) {
17694                        permissionsState.revokeRuntimePermission(bp, userId);
17695                        permissionsState.updatePermissionFlags(bp, userId,
17696                                PackageManager.MASK_PERMISSION_FLAGS, 0);
17697                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
17698                                runtimePermissionChangedUserIds, userId);
17699                    }
17700                }
17701            }
17702        }
17703
17704        return runtimePermissionChangedUserIds;
17705    }
17706
17707    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17708            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17709        // Update the parent package setting
17710        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17711                res, user, installReason);
17712        // Update the child packages setting
17713        final int childCount = (newPackage.childPackages != null)
17714                ? newPackage.childPackages.size() : 0;
17715        for (int i = 0; i < childCount; i++) {
17716            PackageParser.Package childPackage = newPackage.childPackages.get(i);
17717            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17718            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17719                    childRes.origUsers, childRes, user, installReason);
17720        }
17721    }
17722
17723    private void updateSettingsInternalLI(PackageParser.Package newPackage,
17724            String installerPackageName, int[] allUsers, int[] installedForUsers,
17725            PackageInstalledInfo res, UserHandle user, int installReason) {
17726        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17727
17728        String pkgName = newPackage.packageName;
17729        synchronized (mPackages) {
17730            //write settings. the installStatus will be incomplete at this stage.
17731            //note that the new package setting would have already been
17732            //added to mPackages. It hasn't been persisted yet.
17733            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17734            // TODO: Remove this write? It's also written at the end of this method
17735            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17736            mSettings.writeLPr();
17737            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17738        }
17739
17740        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17741        synchronized (mPackages) {
17742            updatePermissionsLPw(newPackage.packageName, newPackage,
17743                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17744                            ? UPDATE_PERMISSIONS_ALL : 0));
17745            // For system-bundled packages, we assume that installing an upgraded version
17746            // of the package implies that the user actually wants to run that new code,
17747            // so we enable the package.
17748            PackageSetting ps = mSettings.mPackages.get(pkgName);
17749            final int userId = user.getIdentifier();
17750            if (ps != null) {
17751                if (isSystemApp(newPackage)) {
17752                    if (DEBUG_INSTALL) {
17753                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17754                    }
17755                    // Enable system package for requested users
17756                    if (res.origUsers != null) {
17757                        for (int origUserId : res.origUsers) {
17758                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17759                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17760                                        origUserId, installerPackageName);
17761                            }
17762                        }
17763                    }
17764                    // Also convey the prior install/uninstall state
17765                    if (allUsers != null && installedForUsers != null) {
17766                        for (int currentUserId : allUsers) {
17767                            final boolean installed = ArrayUtils.contains(
17768                                    installedForUsers, currentUserId);
17769                            if (DEBUG_INSTALL) {
17770                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17771                            }
17772                            ps.setInstalled(installed, currentUserId);
17773                        }
17774                        // these install state changes will be persisted in the
17775                        // upcoming call to mSettings.writeLPr().
17776                    }
17777                }
17778                // It's implied that when a user requests installation, they want the app to be
17779                // installed and enabled.
17780                if (userId != UserHandle.USER_ALL) {
17781                    ps.setInstalled(true, userId);
17782                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17783                }
17784
17785                // When replacing an existing package, preserve the original install reason for all
17786                // users that had the package installed before.
17787                final Set<Integer> previousUserIds = new ArraySet<>();
17788                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17789                    final int installReasonCount = res.removedInfo.installReasons.size();
17790                    for (int i = 0; i < installReasonCount; i++) {
17791                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17792                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17793                        ps.setInstallReason(previousInstallReason, previousUserId);
17794                        previousUserIds.add(previousUserId);
17795                    }
17796                }
17797
17798                // Set install reason for users that are having the package newly installed.
17799                if (userId == UserHandle.USER_ALL) {
17800                    for (int currentUserId : sUserManager.getUserIds()) {
17801                        if (!previousUserIds.contains(currentUserId)) {
17802                            ps.setInstallReason(installReason, currentUserId);
17803                        }
17804                    }
17805                } else if (!previousUserIds.contains(userId)) {
17806                    ps.setInstallReason(installReason, userId);
17807                }
17808                mSettings.writeKernelMappingLPr(ps);
17809            }
17810            res.name = pkgName;
17811            res.uid = newPackage.applicationInfo.uid;
17812            res.pkg = newPackage;
17813            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17814            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17815            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17816            //to update install status
17817            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17818            mSettings.writeLPr();
17819            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17820        }
17821
17822        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17823    }
17824
17825    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17826        try {
17827            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17828            installPackageLI(args, res);
17829        } finally {
17830            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17831        }
17832    }
17833
17834    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17835        final int installFlags = args.installFlags;
17836        final String installerPackageName = args.installerPackageName;
17837        final String volumeUuid = args.volumeUuid;
17838        final File tmpPackageFile = new File(args.getCodePath());
17839        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17840        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17841                || (args.volumeUuid != null));
17842        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17843        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17844        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17845        boolean replace = false;
17846        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17847        if (args.move != null) {
17848            // moving a complete application; perform an initial scan on the new install location
17849            scanFlags |= SCAN_INITIAL;
17850        }
17851        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17852            scanFlags |= SCAN_DONT_KILL_APP;
17853        }
17854        if (instantApp) {
17855            scanFlags |= SCAN_AS_INSTANT_APP;
17856        }
17857        if (fullApp) {
17858            scanFlags |= SCAN_AS_FULL_APP;
17859        }
17860
17861        // Result object to be returned
17862        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17863
17864        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17865
17866        // Sanity check
17867        if (instantApp && (forwardLocked || onExternal)) {
17868            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17869                    + " external=" + onExternal);
17870            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17871            return;
17872        }
17873
17874        // Retrieve PackageSettings and parse package
17875        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17876                | PackageParser.PARSE_ENFORCE_CODE
17877                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17878                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17879                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17880                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17881        PackageParser pp = new PackageParser();
17882        pp.setSeparateProcesses(mSeparateProcesses);
17883        pp.setDisplayMetrics(mMetrics);
17884        pp.setCallback(mPackageParserCallback);
17885
17886        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17887        final PackageParser.Package pkg;
17888        try {
17889            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17890        } catch (PackageParserException e) {
17891            res.setError("Failed parse during installPackageLI", e);
17892            return;
17893        } finally {
17894            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17895        }
17896
17897        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17898        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17899            Slog.w(TAG, "Instant app package " + pkg.packageName
17900                    + " does not target O, this will be a fatal error.");
17901            // STOPSHIP: Make this a fatal error
17902            pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O;
17903        }
17904        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17905            Slog.w(TAG, "Instant app package " + pkg.packageName
17906                    + " does not target targetSandboxVersion 2, this will be a fatal error.");
17907            // STOPSHIP: Make this a fatal error
17908            pkg.applicationInfo.targetSandboxVersion = 2;
17909        }
17910
17911        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17912            // Static shared libraries have synthetic package names
17913            renameStaticSharedLibraryPackage(pkg);
17914
17915            // No static shared libs on external storage
17916            if (onExternal) {
17917                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17918                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17919                        "Packages declaring static-shared libs cannot be updated");
17920                return;
17921            }
17922        }
17923
17924        // If we are installing a clustered package add results for the children
17925        if (pkg.childPackages != null) {
17926            synchronized (mPackages) {
17927                final int childCount = pkg.childPackages.size();
17928                for (int i = 0; i < childCount; i++) {
17929                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17930                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17931                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17932                    childRes.pkg = childPkg;
17933                    childRes.name = childPkg.packageName;
17934                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17935                    if (childPs != null) {
17936                        childRes.origUsers = childPs.queryInstalledUsers(
17937                                sUserManager.getUserIds(), true);
17938                    }
17939                    if ((mPackages.containsKey(childPkg.packageName))) {
17940                        childRes.removedInfo = new PackageRemovedInfo(this);
17941                        childRes.removedInfo.removedPackage = childPkg.packageName;
17942                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17943                    }
17944                    if (res.addedChildPackages == null) {
17945                        res.addedChildPackages = new ArrayMap<>();
17946                    }
17947                    res.addedChildPackages.put(childPkg.packageName, childRes);
17948                }
17949            }
17950        }
17951
17952        // If package doesn't declare API override, mark that we have an install
17953        // time CPU ABI override.
17954        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17955            pkg.cpuAbiOverride = args.abiOverride;
17956        }
17957
17958        String pkgName = res.name = pkg.packageName;
17959        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17960            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17961                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17962                return;
17963            }
17964        }
17965
17966        try {
17967            // either use what we've been given or parse directly from the APK
17968            if (args.certificates != null) {
17969                try {
17970                    PackageParser.populateCertificates(pkg, args.certificates);
17971                } catch (PackageParserException e) {
17972                    // there was something wrong with the certificates we were given;
17973                    // try to pull them from the APK
17974                    PackageParser.collectCertificates(pkg, parseFlags);
17975                }
17976            } else {
17977                PackageParser.collectCertificates(pkg, parseFlags);
17978            }
17979        } catch (PackageParserException e) {
17980            res.setError("Failed collect during installPackageLI", e);
17981            return;
17982        }
17983
17984        // Get rid of all references to package scan path via parser.
17985        pp = null;
17986        String oldCodePath = null;
17987        boolean systemApp = false;
17988        synchronized (mPackages) {
17989            // Check if installing already existing package
17990            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17991                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17992                if (pkg.mOriginalPackages != null
17993                        && pkg.mOriginalPackages.contains(oldName)
17994                        && mPackages.containsKey(oldName)) {
17995                    // This package is derived from an original package,
17996                    // and this device has been updating from that original
17997                    // name.  We must continue using the original name, so
17998                    // rename the new package here.
17999                    pkg.setPackageName(oldName);
18000                    pkgName = pkg.packageName;
18001                    replace = true;
18002                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
18003                            + oldName + " pkgName=" + pkgName);
18004                } else if (mPackages.containsKey(pkgName)) {
18005                    // This package, under its official name, already exists
18006                    // on the device; we should replace it.
18007                    replace = true;
18008                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
18009                }
18010
18011                // Child packages are installed through the parent package
18012                if (pkg.parentPackage != null) {
18013                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18014                            "Package " + pkg.packageName + " is child of package "
18015                                    + pkg.parentPackage.parentPackage + ". Child packages "
18016                                    + "can be updated only through the parent package.");
18017                    return;
18018                }
18019
18020                if (replace) {
18021                    // Prevent apps opting out from runtime permissions
18022                    PackageParser.Package oldPackage = mPackages.get(pkgName);
18023                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
18024                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
18025                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
18026                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
18027                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
18028                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
18029                                        + " doesn't support runtime permissions but the old"
18030                                        + " target SDK " + oldTargetSdk + " does.");
18031                        return;
18032                    }
18033                    // Prevent apps from downgrading their targetSandbox.
18034                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
18035                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
18036                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
18037                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
18038                                "Package " + pkg.packageName + " new target sandbox "
18039                                + newTargetSandbox + " is incompatible with the previous value of"
18040                                + oldTargetSandbox + ".");
18041                        return;
18042                    }
18043
18044                    // Prevent installing of child packages
18045                    if (oldPackage.parentPackage != null) {
18046                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
18047                                "Package " + pkg.packageName + " is child of package "
18048                                        + oldPackage.parentPackage + ". Child packages "
18049                                        + "can be updated only through the parent package.");
18050                        return;
18051                    }
18052                }
18053            }
18054
18055            PackageSetting ps = mSettings.mPackages.get(pkgName);
18056            if (ps != null) {
18057                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
18058
18059                // Static shared libs have same package with different versions where
18060                // we internally use a synthetic package name to allow multiple versions
18061                // of the same package, therefore we need to compare signatures against
18062                // the package setting for the latest library version.
18063                PackageSetting signatureCheckPs = ps;
18064                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18065                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
18066                    if (libraryEntry != null) {
18067                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
18068                    }
18069                }
18070
18071                // Quick sanity check that we're signed correctly if updating;
18072                // we'll check this again later when scanning, but we want to
18073                // bail early here before tripping over redefined permissions.
18074                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
18075                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
18076                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
18077                                + pkg.packageName + " upgrade keys do not match the "
18078                                + "previously installed version");
18079                        return;
18080                    }
18081                } else {
18082                    try {
18083                        verifySignaturesLP(signatureCheckPs, pkg);
18084                    } catch (PackageManagerException e) {
18085                        res.setError(e.error, e.getMessage());
18086                        return;
18087                    }
18088                }
18089
18090                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
18091                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
18092                    systemApp = (ps.pkg.applicationInfo.flags &
18093                            ApplicationInfo.FLAG_SYSTEM) != 0;
18094                }
18095                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18096            }
18097
18098            int N = pkg.permissions.size();
18099            for (int i = N-1; i >= 0; i--) {
18100                PackageParser.Permission perm = pkg.permissions.get(i);
18101                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
18102
18103                // Don't allow anyone but the system to define ephemeral permissions.
18104                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18105                        && !systemApp) {
18106                    Slog.w(TAG, "Non-System package " + pkg.packageName
18107                            + " attempting to delcare ephemeral permission "
18108                            + perm.info.name + "; Removing ephemeral.");
18109                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18110                }
18111                // Check whether the newly-scanned package wants to define an already-defined perm
18112                if (bp != null) {
18113                    // If the defining package is signed with our cert, it's okay.  This
18114                    // also includes the "updating the same package" case, of course.
18115                    // "updating same package" could also involve key-rotation.
18116                    final boolean sigsOk;
18117                    if (bp.sourcePackage.equals(pkg.packageName)
18118                            && (bp.packageSetting instanceof PackageSetting)
18119                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18120                                    scanFlags))) {
18121                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18122                    } else {
18123                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18124                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18125                    }
18126                    if (!sigsOk) {
18127                        // If the owning package is the system itself, we log but allow
18128                        // install to proceed; we fail the install on all other permission
18129                        // redefinitions.
18130                        if (!bp.sourcePackage.equals("android")) {
18131                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18132                                    + pkg.packageName + " attempting to redeclare permission "
18133                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18134                            res.origPermission = perm.info.name;
18135                            res.origPackage = bp.sourcePackage;
18136                            return;
18137                        } else {
18138                            Slog.w(TAG, "Package " + pkg.packageName
18139                                    + " attempting to redeclare system permission "
18140                                    + perm.info.name + "; ignoring new declaration");
18141                            pkg.permissions.remove(i);
18142                        }
18143                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18144                        // Prevent apps to change protection level to dangerous from any other
18145                        // type as this would allow a privilege escalation where an app adds a
18146                        // normal/signature permission in other app's group and later redefines
18147                        // it as dangerous leading to the group auto-grant.
18148                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18149                                == PermissionInfo.PROTECTION_DANGEROUS) {
18150                            if (bp != null && !bp.isRuntime()) {
18151                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18152                                        + "non-runtime permission " + perm.info.name
18153                                        + " to runtime; keeping old protection level");
18154                                perm.info.protectionLevel = bp.protectionLevel;
18155                            }
18156                        }
18157                    }
18158                }
18159            }
18160        }
18161
18162        if (systemApp) {
18163            if (onExternal) {
18164                // Abort update; system app can't be replaced with app on sdcard
18165                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18166                        "Cannot install updates to system apps on sdcard");
18167                return;
18168            } else if (instantApp) {
18169                // Abort update; system app can't be replaced with an instant app
18170                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18171                        "Cannot update a system app with an instant app");
18172                return;
18173            }
18174        }
18175
18176        if (args.move != null) {
18177            // We did an in-place move, so dex is ready to roll
18178            scanFlags |= SCAN_NO_DEX;
18179            scanFlags |= SCAN_MOVE;
18180
18181            synchronized (mPackages) {
18182                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18183                if (ps == null) {
18184                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18185                            "Missing settings for moved package " + pkgName);
18186                }
18187
18188                // We moved the entire application as-is, so bring over the
18189                // previously derived ABI information.
18190                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18191                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18192            }
18193
18194        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18195            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18196            scanFlags |= SCAN_NO_DEX;
18197
18198            try {
18199                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18200                    args.abiOverride : pkg.cpuAbiOverride);
18201                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18202                        true /*extractLibs*/, mAppLib32InstallDir);
18203            } catch (PackageManagerException pme) {
18204                Slog.e(TAG, "Error deriving application ABI", pme);
18205                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18206                return;
18207            }
18208
18209            // Shared libraries for the package need to be updated.
18210            synchronized (mPackages) {
18211                try {
18212                    updateSharedLibrariesLPr(pkg, null);
18213                } catch (PackageManagerException e) {
18214                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18215                }
18216            }
18217
18218            // dexopt can take some time to complete, so, for instant apps, we skip this
18219            // step during installation. Instead, we'll take extra time the first time the
18220            // instant app starts. It's preferred to do it this way to provide continuous
18221            // progress to the user instead of mysteriously blocking somewhere in the
18222            // middle of running an instant app.
18223            if (!instantApp) {
18224                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18225                // Do not run PackageDexOptimizer through the local performDexOpt
18226                // method because `pkg` may not be in `mPackages` yet.
18227                //
18228                // Also, don't fail application installs if the dexopt step fails.
18229                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18230                        null /* instructionSets */, false /* checkProfiles */,
18231                        getCompilerFilterForReason(REASON_INSTALL),
18232                        getOrCreateCompilerPackageStats(pkg),
18233                        mDexManager.isUsedByOtherApps(pkg.packageName),
18234                        true /* bootComplete */);
18235                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18236            }
18237
18238            // Notify BackgroundDexOptService that the package has been changed.
18239            // If this is an update of a package which used to fail to compile,
18240            // BDOS will remove it from its blacklist.
18241            // TODO: Layering violation
18242            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18243        }
18244
18245        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18246            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18247            return;
18248        }
18249
18250        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18251
18252        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18253                "installPackageLI")) {
18254            if (replace) {
18255                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18256                    // Static libs have a synthetic package name containing the version
18257                    // and cannot be updated as an update would get a new package name,
18258                    // unless this is the exact same version code which is useful for
18259                    // development.
18260                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18261                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18262                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18263                                + "static-shared libs cannot be updated");
18264                        return;
18265                    }
18266                }
18267                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18268                        installerPackageName, res, args.installReason);
18269            } else {
18270                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18271                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18272            }
18273        }
18274
18275        synchronized (mPackages) {
18276            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18277            if (ps != null) {
18278                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18279                ps.setUpdateAvailable(false /*updateAvailable*/);
18280            }
18281
18282            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18283            for (int i = 0; i < childCount; i++) {
18284                PackageParser.Package childPkg = pkg.childPackages.get(i);
18285                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18286                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18287                if (childPs != null) {
18288                    childRes.newUsers = childPs.queryInstalledUsers(
18289                            sUserManager.getUserIds(), true);
18290                }
18291            }
18292
18293            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18294                updateSequenceNumberLP(ps, res.newUsers);
18295                updateInstantAppInstallerLocked(pkgName);
18296            }
18297        }
18298    }
18299
18300    private void startIntentFilterVerifications(int userId, boolean replacing,
18301            PackageParser.Package pkg) {
18302        if (mIntentFilterVerifierComponent == null) {
18303            Slog.w(TAG, "No IntentFilter verification will not be done as "
18304                    + "there is no IntentFilterVerifier available!");
18305            return;
18306        }
18307
18308        final int verifierUid = getPackageUid(
18309                mIntentFilterVerifierComponent.getPackageName(),
18310                MATCH_DEBUG_TRIAGED_MISSING,
18311                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18312
18313        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18314        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18315        mHandler.sendMessage(msg);
18316
18317        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18318        for (int i = 0; i < childCount; i++) {
18319            PackageParser.Package childPkg = pkg.childPackages.get(i);
18320            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18321            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18322            mHandler.sendMessage(msg);
18323        }
18324    }
18325
18326    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18327            PackageParser.Package pkg) {
18328        int size = pkg.activities.size();
18329        if (size == 0) {
18330            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18331                    "No activity, so no need to verify any IntentFilter!");
18332            return;
18333        }
18334
18335        final boolean hasDomainURLs = hasDomainURLs(pkg);
18336        if (!hasDomainURLs) {
18337            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18338                    "No domain URLs, so no need to verify any IntentFilter!");
18339            return;
18340        }
18341
18342        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18343                + " if any IntentFilter from the " + size
18344                + " Activities needs verification ...");
18345
18346        int count = 0;
18347        final String packageName = pkg.packageName;
18348
18349        synchronized (mPackages) {
18350            // If this is a new install and we see that we've already run verification for this
18351            // package, we have nothing to do: it means the state was restored from backup.
18352            if (!replacing) {
18353                IntentFilterVerificationInfo ivi =
18354                        mSettings.getIntentFilterVerificationLPr(packageName);
18355                if (ivi != null) {
18356                    if (DEBUG_DOMAIN_VERIFICATION) {
18357                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18358                                + ivi.getStatusString());
18359                    }
18360                    return;
18361                }
18362            }
18363
18364            // If any filters need to be verified, then all need to be.
18365            boolean needToVerify = false;
18366            for (PackageParser.Activity a : pkg.activities) {
18367                for (ActivityIntentInfo filter : a.intents) {
18368                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18369                        if (DEBUG_DOMAIN_VERIFICATION) {
18370                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18371                        }
18372                        needToVerify = true;
18373                        break;
18374                    }
18375                }
18376            }
18377
18378            if (needToVerify) {
18379                final int verificationId = mIntentFilterVerificationToken++;
18380                for (PackageParser.Activity a : pkg.activities) {
18381                    for (ActivityIntentInfo filter : a.intents) {
18382                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18383                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18384                                    "Verification needed for IntentFilter:" + filter.toString());
18385                            mIntentFilterVerifier.addOneIntentFilterVerification(
18386                                    verifierUid, userId, verificationId, filter, packageName);
18387                            count++;
18388                        }
18389                    }
18390                }
18391            }
18392        }
18393
18394        if (count > 0) {
18395            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18396                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18397                    +  " for userId:" + userId);
18398            mIntentFilterVerifier.startVerifications(userId);
18399        } else {
18400            if (DEBUG_DOMAIN_VERIFICATION) {
18401                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18402            }
18403        }
18404    }
18405
18406    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18407        final ComponentName cn  = filter.activity.getComponentName();
18408        final String packageName = cn.getPackageName();
18409
18410        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18411                packageName);
18412        if (ivi == null) {
18413            return true;
18414        }
18415        int status = ivi.getStatus();
18416        switch (status) {
18417            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18418            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18419                return true;
18420
18421            default:
18422                // Nothing to do
18423                return false;
18424        }
18425    }
18426
18427    private static boolean isMultiArch(ApplicationInfo info) {
18428        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18429    }
18430
18431    private static boolean isExternal(PackageParser.Package pkg) {
18432        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18433    }
18434
18435    private static boolean isExternal(PackageSetting ps) {
18436        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18437    }
18438
18439    private static boolean isSystemApp(PackageParser.Package pkg) {
18440        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18441    }
18442
18443    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18444        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18445    }
18446
18447    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18448        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18449    }
18450
18451    private static boolean isSystemApp(PackageSetting ps) {
18452        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18453    }
18454
18455    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18456        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18457    }
18458
18459    private int packageFlagsToInstallFlags(PackageSetting ps) {
18460        int installFlags = 0;
18461        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18462            // This existing package was an external ASEC install when we have
18463            // the external flag without a UUID
18464            installFlags |= PackageManager.INSTALL_EXTERNAL;
18465        }
18466        if (ps.isForwardLocked()) {
18467            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18468        }
18469        return installFlags;
18470    }
18471
18472    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18473        if (isExternal(pkg)) {
18474            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18475                return StorageManager.UUID_PRIMARY_PHYSICAL;
18476            } else {
18477                return pkg.volumeUuid;
18478            }
18479        } else {
18480            return StorageManager.UUID_PRIVATE_INTERNAL;
18481        }
18482    }
18483
18484    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18485        if (isExternal(pkg)) {
18486            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18487                return mSettings.getExternalVersion();
18488            } else {
18489                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18490            }
18491        } else {
18492            return mSettings.getInternalVersion();
18493        }
18494    }
18495
18496    private void deleteTempPackageFiles() {
18497        final FilenameFilter filter = new FilenameFilter() {
18498            public boolean accept(File dir, String name) {
18499                return name.startsWith("vmdl") && name.endsWith(".tmp");
18500            }
18501        };
18502        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18503            file.delete();
18504        }
18505    }
18506
18507    @Override
18508    public void deletePackageAsUser(String packageName, int versionCode,
18509            IPackageDeleteObserver observer, int userId, int flags) {
18510        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18511                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18512    }
18513
18514    @Override
18515    public void deletePackageVersioned(VersionedPackage versionedPackage,
18516            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18517        final int callingUid = Binder.getCallingUid();
18518        mContext.enforceCallingOrSelfPermission(
18519                android.Manifest.permission.DELETE_PACKAGES, null);
18520        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18521        Preconditions.checkNotNull(versionedPackage);
18522        Preconditions.checkNotNull(observer);
18523        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18524                PackageManager.VERSION_CODE_HIGHEST,
18525                Integer.MAX_VALUE, "versionCode must be >= -1");
18526
18527        final String packageName = versionedPackage.getPackageName();
18528        final int versionCode = versionedPackage.getVersionCode();
18529        final String internalPackageName;
18530        synchronized (mPackages) {
18531            // Normalize package name to handle renamed packages and static libs
18532            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18533                    versionedPackage.getVersionCode());
18534        }
18535
18536        final int uid = Binder.getCallingUid();
18537        if (!isOrphaned(internalPackageName)
18538                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18539            try {
18540                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18541                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18542                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18543                observer.onUserActionRequired(intent);
18544            } catch (RemoteException re) {
18545            }
18546            return;
18547        }
18548        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18549        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18550        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18551            mContext.enforceCallingOrSelfPermission(
18552                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18553                    "deletePackage for user " + userId);
18554        }
18555
18556        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18557            try {
18558                observer.onPackageDeleted(packageName,
18559                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18560            } catch (RemoteException re) {
18561            }
18562            return;
18563        }
18564
18565        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18566            try {
18567                observer.onPackageDeleted(packageName,
18568                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18569            } catch (RemoteException re) {
18570            }
18571            return;
18572        }
18573
18574        if (DEBUG_REMOVE) {
18575            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18576                    + " deleteAllUsers: " + deleteAllUsers + " version="
18577                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18578                    ? "VERSION_CODE_HIGHEST" : versionCode));
18579        }
18580        // Queue up an async operation since the package deletion may take a little while.
18581        mHandler.post(new Runnable() {
18582            public void run() {
18583                mHandler.removeCallbacks(this);
18584                int returnCode;
18585                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18586                boolean doDeletePackage = true;
18587                if (ps != null) {
18588                    final boolean targetIsInstantApp =
18589                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18590                    doDeletePackage = !targetIsInstantApp
18591                            || canViewInstantApps;
18592                }
18593                if (doDeletePackage) {
18594                    if (!deleteAllUsers) {
18595                        returnCode = deletePackageX(internalPackageName, versionCode,
18596                                userId, deleteFlags);
18597                    } else {
18598                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18599                                internalPackageName, users);
18600                        // If nobody is blocking uninstall, proceed with delete for all users
18601                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18602                            returnCode = deletePackageX(internalPackageName, versionCode,
18603                                    userId, deleteFlags);
18604                        } else {
18605                            // Otherwise uninstall individually for users with blockUninstalls=false
18606                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18607                            for (int userId : users) {
18608                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18609                                    returnCode = deletePackageX(internalPackageName, versionCode,
18610                                            userId, userFlags);
18611                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18612                                        Slog.w(TAG, "Package delete failed for user " + userId
18613                                                + ", returnCode " + returnCode);
18614                                    }
18615                                }
18616                            }
18617                            // The app has only been marked uninstalled for certain users.
18618                            // We still need to report that delete was blocked
18619                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18620                        }
18621                    }
18622                } else {
18623                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18624                }
18625                try {
18626                    observer.onPackageDeleted(packageName, returnCode, null);
18627                } catch (RemoteException e) {
18628                    Log.i(TAG, "Observer no longer exists.");
18629                } //end catch
18630            } //end run
18631        });
18632    }
18633
18634    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18635        if (pkg.staticSharedLibName != null) {
18636            return pkg.manifestPackageName;
18637        }
18638        return pkg.packageName;
18639    }
18640
18641    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18642        // Handle renamed packages
18643        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18644        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18645
18646        // Is this a static library?
18647        SparseArray<SharedLibraryEntry> versionedLib =
18648                mStaticLibsByDeclaringPackage.get(packageName);
18649        if (versionedLib == null || versionedLib.size() <= 0) {
18650            return packageName;
18651        }
18652
18653        // Figure out which lib versions the caller can see
18654        SparseIntArray versionsCallerCanSee = null;
18655        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18656        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18657                && callingAppId != Process.ROOT_UID) {
18658            versionsCallerCanSee = new SparseIntArray();
18659            String libName = versionedLib.valueAt(0).info.getName();
18660            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18661            if (uidPackages != null) {
18662                for (String uidPackage : uidPackages) {
18663                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18664                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18665                    if (libIdx >= 0) {
18666                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18667                        versionsCallerCanSee.append(libVersion, libVersion);
18668                    }
18669                }
18670            }
18671        }
18672
18673        // Caller can see nothing - done
18674        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18675            return packageName;
18676        }
18677
18678        // Find the version the caller can see and the app version code
18679        SharedLibraryEntry highestVersion = null;
18680        final int versionCount = versionedLib.size();
18681        for (int i = 0; i < versionCount; i++) {
18682            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18683            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18684                    libEntry.info.getVersion()) < 0) {
18685                continue;
18686            }
18687            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18688            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18689                if (libVersionCode == versionCode) {
18690                    return libEntry.apk;
18691                }
18692            } else if (highestVersion == null) {
18693                highestVersion = libEntry;
18694            } else if (libVersionCode  > highestVersion.info
18695                    .getDeclaringPackage().getVersionCode()) {
18696                highestVersion = libEntry;
18697            }
18698        }
18699
18700        if (highestVersion != null) {
18701            return highestVersion.apk;
18702        }
18703
18704        return packageName;
18705    }
18706
18707    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18708        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18709              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18710            return true;
18711        }
18712        final int callingUserId = UserHandle.getUserId(callingUid);
18713        // If the caller installed the pkgName, then allow it to silently uninstall.
18714        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18715            return true;
18716        }
18717
18718        // Allow package verifier to silently uninstall.
18719        if (mRequiredVerifierPackage != null &&
18720                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18721            return true;
18722        }
18723
18724        // Allow package uninstaller to silently uninstall.
18725        if (mRequiredUninstallerPackage != null &&
18726                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18727            return true;
18728        }
18729
18730        // Allow storage manager to silently uninstall.
18731        if (mStorageManagerPackage != null &&
18732                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18733            return true;
18734        }
18735
18736        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18737        // uninstall for device owner provisioning.
18738        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18739                == PERMISSION_GRANTED) {
18740            return true;
18741        }
18742
18743        return false;
18744    }
18745
18746    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18747        int[] result = EMPTY_INT_ARRAY;
18748        for (int userId : userIds) {
18749            if (getBlockUninstallForUser(packageName, userId)) {
18750                result = ArrayUtils.appendInt(result, userId);
18751            }
18752        }
18753        return result;
18754    }
18755
18756    @Override
18757    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18758        final int callingUid = Binder.getCallingUid();
18759        if (getInstantAppPackageName(callingUid) != null
18760                && !isCallerSameApp(packageName, callingUid)) {
18761            return false;
18762        }
18763        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18764    }
18765
18766    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18767        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18768                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18769        try {
18770            if (dpm != null) {
18771                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18772                        /* callingUserOnly =*/ false);
18773                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18774                        : deviceOwnerComponentName.getPackageName();
18775                // Does the package contains the device owner?
18776                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18777                // this check is probably not needed, since DO should be registered as a device
18778                // admin on some user too. (Original bug for this: b/17657954)
18779                if (packageName.equals(deviceOwnerPackageName)) {
18780                    return true;
18781                }
18782                // Does it contain a device admin for any user?
18783                int[] users;
18784                if (userId == UserHandle.USER_ALL) {
18785                    users = sUserManager.getUserIds();
18786                } else {
18787                    users = new int[]{userId};
18788                }
18789                for (int i = 0; i < users.length; ++i) {
18790                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18791                        return true;
18792                    }
18793                }
18794            }
18795        } catch (RemoteException e) {
18796        }
18797        return false;
18798    }
18799
18800    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18801        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18802    }
18803
18804    /**
18805     *  This method is an internal method that could be get invoked either
18806     *  to delete an installed package or to clean up a failed installation.
18807     *  After deleting an installed package, a broadcast is sent to notify any
18808     *  listeners that the package has been removed. For cleaning up a failed
18809     *  installation, the broadcast is not necessary since the package's
18810     *  installation wouldn't have sent the initial broadcast either
18811     *  The key steps in deleting a package are
18812     *  deleting the package information in internal structures like mPackages,
18813     *  deleting the packages base directories through installd
18814     *  updating mSettings to reflect current status
18815     *  persisting settings for later use
18816     *  sending a broadcast if necessary
18817     */
18818    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18819        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18820        final boolean res;
18821
18822        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18823                ? UserHandle.USER_ALL : userId;
18824
18825        if (isPackageDeviceAdmin(packageName, removeUser)) {
18826            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18827            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18828        }
18829
18830        PackageSetting uninstalledPs = null;
18831        PackageParser.Package pkg = null;
18832
18833        // for the uninstall-updates case and restricted profiles, remember the per-
18834        // user handle installed state
18835        int[] allUsers;
18836        synchronized (mPackages) {
18837            uninstalledPs = mSettings.mPackages.get(packageName);
18838            if (uninstalledPs == null) {
18839                Slog.w(TAG, "Not removing non-existent package " + packageName);
18840                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18841            }
18842
18843            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18844                    && uninstalledPs.versionCode != versionCode) {
18845                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18846                        + uninstalledPs.versionCode + " != " + versionCode);
18847                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18848            }
18849
18850            // Static shared libs can be declared by any package, so let us not
18851            // allow removing a package if it provides a lib others depend on.
18852            pkg = mPackages.get(packageName);
18853
18854            allUsers = sUserManager.getUserIds();
18855
18856            if (pkg != null && pkg.staticSharedLibName != null) {
18857                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18858                        pkg.staticSharedLibVersion);
18859                if (libEntry != null) {
18860                    for (int currUserId : allUsers) {
18861                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18862                            continue;
18863                        }
18864                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18865                                libEntry.info, 0, currUserId);
18866                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18867                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18868                                    + " hosting lib " + libEntry.info.getName() + " version "
18869                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18870                                    + " for user " + currUserId);
18871                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18872                        }
18873                    }
18874                }
18875            }
18876
18877            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18878        }
18879
18880        final int freezeUser;
18881        if (isUpdatedSystemApp(uninstalledPs)
18882                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18883            // We're downgrading a system app, which will apply to all users, so
18884            // freeze them all during the downgrade
18885            freezeUser = UserHandle.USER_ALL;
18886        } else {
18887            freezeUser = removeUser;
18888        }
18889
18890        synchronized (mInstallLock) {
18891            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18892            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18893                    deleteFlags, "deletePackageX")) {
18894                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18895                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18896            }
18897            synchronized (mPackages) {
18898                if (res) {
18899                    if (pkg != null) {
18900                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18901                    }
18902                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18903                    updateInstantAppInstallerLocked(packageName);
18904                }
18905            }
18906        }
18907
18908        if (res) {
18909            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18910            info.sendPackageRemovedBroadcasts(killApp);
18911            info.sendSystemPackageUpdatedBroadcasts();
18912            info.sendSystemPackageAppearedBroadcasts();
18913        }
18914        // Force a gc here.
18915        Runtime.getRuntime().gc();
18916        // Delete the resources here after sending the broadcast to let
18917        // other processes clean up before deleting resources.
18918        if (info.args != null) {
18919            synchronized (mInstallLock) {
18920                info.args.doPostDeleteLI(true);
18921            }
18922        }
18923
18924        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18925    }
18926
18927    static class PackageRemovedInfo {
18928        final PackageSender packageSender;
18929        String removedPackage;
18930        String installerPackageName;
18931        int uid = -1;
18932        int removedAppId = -1;
18933        int[] origUsers;
18934        int[] removedUsers = null;
18935        int[] broadcastUsers = null;
18936        SparseArray<Integer> installReasons;
18937        boolean isRemovedPackageSystemUpdate = false;
18938        boolean isUpdate;
18939        boolean dataRemoved;
18940        boolean removedForAllUsers;
18941        boolean isStaticSharedLib;
18942        // Clean up resources deleted packages.
18943        InstallArgs args = null;
18944        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18945        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18946
18947        PackageRemovedInfo(PackageSender packageSender) {
18948            this.packageSender = packageSender;
18949        }
18950
18951        void sendPackageRemovedBroadcasts(boolean killApp) {
18952            sendPackageRemovedBroadcastInternal(killApp);
18953            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18954            for (int i = 0; i < childCount; i++) {
18955                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18956                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18957            }
18958        }
18959
18960        void sendSystemPackageUpdatedBroadcasts() {
18961            if (isRemovedPackageSystemUpdate) {
18962                sendSystemPackageUpdatedBroadcastsInternal();
18963                final int childCount = (removedChildPackages != null)
18964                        ? removedChildPackages.size() : 0;
18965                for (int i = 0; i < childCount; i++) {
18966                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18967                    if (childInfo.isRemovedPackageSystemUpdate) {
18968                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18969                    }
18970                }
18971            }
18972        }
18973
18974        void sendSystemPackageAppearedBroadcasts() {
18975            final int packageCount = (appearedChildPackages != null)
18976                    ? appearedChildPackages.size() : 0;
18977            for (int i = 0; i < packageCount; i++) {
18978                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18979                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18980                    true, UserHandle.getAppId(installedInfo.uid),
18981                    installedInfo.newUsers);
18982            }
18983        }
18984
18985        private void sendSystemPackageUpdatedBroadcastsInternal() {
18986            Bundle extras = new Bundle(2);
18987            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18988            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18989            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18990                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18991            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18992                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18993            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18994                null, null, 0, removedPackage, null, null);
18995            if (installerPackageName != null) {
18996                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18997                        removedPackage, extras, 0 /*flags*/,
18998                        installerPackageName, null, null);
18999                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
19000                        removedPackage, extras, 0 /*flags*/,
19001                        installerPackageName, null, null);
19002            }
19003        }
19004
19005        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
19006            // Don't send static shared library removal broadcasts as these
19007            // libs are visible only the the apps that depend on them an one
19008            // cannot remove the library if it has a dependency.
19009            if (isStaticSharedLib) {
19010                return;
19011            }
19012            Bundle extras = new Bundle(2);
19013            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
19014            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
19015            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
19016            if (isUpdate || isRemovedPackageSystemUpdate) {
19017                extras.putBoolean(Intent.EXTRA_REPLACING, true);
19018            }
19019            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
19020            if (removedPackage != null) {
19021                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19022                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
19023                if (installerPackageName != null) {
19024                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
19025                            removedPackage, extras, 0 /*flags*/,
19026                            installerPackageName, null, broadcastUsers);
19027                }
19028                if (dataRemoved && !isRemovedPackageSystemUpdate) {
19029                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
19030                        removedPackage, extras,
19031                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19032                        null, null, broadcastUsers);
19033                }
19034            }
19035            if (removedAppId >= 0) {
19036                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
19037                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
19038                    null, null, broadcastUsers);
19039            }
19040        }
19041
19042        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
19043            removedUsers = userIds;
19044            if (removedUsers == null) {
19045                broadcastUsers = null;
19046                return;
19047            }
19048
19049            broadcastUsers = EMPTY_INT_ARRAY;
19050            for (int i = userIds.length - 1; i >= 0; --i) {
19051                final int userId = userIds[i];
19052                if (deletedPackageSetting.getInstantApp(userId)) {
19053                    continue;
19054                }
19055                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
19056            }
19057        }
19058    }
19059
19060    /*
19061     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
19062     * flag is not set, the data directory is removed as well.
19063     * make sure this flag is set for partially installed apps. If not its meaningless to
19064     * delete a partially installed application.
19065     */
19066    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
19067            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
19068        String packageName = ps.name;
19069        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
19070        // Retrieve object to delete permissions for shared user later on
19071        final PackageParser.Package deletedPkg;
19072        final PackageSetting deletedPs;
19073        // reader
19074        synchronized (mPackages) {
19075            deletedPkg = mPackages.get(packageName);
19076            deletedPs = mSettings.mPackages.get(packageName);
19077            if (outInfo != null) {
19078                outInfo.removedPackage = packageName;
19079                outInfo.installerPackageName = ps.installerPackageName;
19080                outInfo.isStaticSharedLib = deletedPkg != null
19081                        && deletedPkg.staticSharedLibName != null;
19082                outInfo.populateUsers(deletedPs == null ? null
19083                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
19084            }
19085        }
19086
19087        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
19088
19089        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
19090            final PackageParser.Package resolvedPkg;
19091            if (deletedPkg != null) {
19092                resolvedPkg = deletedPkg;
19093            } else {
19094                // We don't have a parsed package when it lives on an ejected
19095                // adopted storage device, so fake something together
19096                resolvedPkg = new PackageParser.Package(ps.name);
19097                resolvedPkg.setVolumeUuid(ps.volumeUuid);
19098            }
19099            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
19100                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19101            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
19102            if (outInfo != null) {
19103                outInfo.dataRemoved = true;
19104            }
19105            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
19106        }
19107
19108        int removedAppId = -1;
19109
19110        // writer
19111        synchronized (mPackages) {
19112            boolean installedStateChanged = false;
19113            if (deletedPs != null) {
19114                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19115                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19116                    clearDefaultBrowserIfNeeded(packageName);
19117                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19118                    removedAppId = mSettings.removePackageLPw(packageName);
19119                    if (outInfo != null) {
19120                        outInfo.removedAppId = removedAppId;
19121                    }
19122                    updatePermissionsLPw(deletedPs.name, null, 0);
19123                    if (deletedPs.sharedUser != null) {
19124                        // Remove permissions associated with package. Since runtime
19125                        // permissions are per user we have to kill the removed package
19126                        // or packages running under the shared user of the removed
19127                        // package if revoking the permissions requested only by the removed
19128                        // package is successful and this causes a change in gids.
19129                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19130                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19131                                    userId);
19132                            if (userIdToKill == UserHandle.USER_ALL
19133                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19134                                // If gids changed for this user, kill all affected packages.
19135                                mHandler.post(new Runnable() {
19136                                    @Override
19137                                    public void run() {
19138                                        // This has to happen with no lock held.
19139                                        killApplication(deletedPs.name, deletedPs.appId,
19140                                                KILL_APP_REASON_GIDS_CHANGED);
19141                                    }
19142                                });
19143                                break;
19144                            }
19145                        }
19146                    }
19147                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19148                }
19149                // make sure to preserve per-user disabled state if this removal was just
19150                // a downgrade of a system app to the factory package
19151                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19152                    if (DEBUG_REMOVE) {
19153                        Slog.d(TAG, "Propagating install state across downgrade");
19154                    }
19155                    for (int userId : allUserHandles) {
19156                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19157                        if (DEBUG_REMOVE) {
19158                            Slog.d(TAG, "    user " + userId + " => " + installed);
19159                        }
19160                        if (installed != ps.getInstalled(userId)) {
19161                            installedStateChanged = true;
19162                        }
19163                        ps.setInstalled(installed, userId);
19164                    }
19165                }
19166            }
19167            // can downgrade to reader
19168            if (writeSettings) {
19169                // Save settings now
19170                mSettings.writeLPr();
19171            }
19172            if (installedStateChanged) {
19173                mSettings.writeKernelMappingLPr(ps);
19174            }
19175        }
19176        if (removedAppId != -1) {
19177            // A user ID was deleted here. Go through all users and remove it
19178            // from KeyStore.
19179            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19180        }
19181    }
19182
19183    static boolean locationIsPrivileged(File path) {
19184        try {
19185            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19186                    .getCanonicalPath();
19187            return path.getCanonicalPath().startsWith(privilegedAppDir);
19188        } catch (IOException e) {
19189            Slog.e(TAG, "Unable to access code path " + path);
19190        }
19191        return false;
19192    }
19193
19194    /*
19195     * Tries to delete system package.
19196     */
19197    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19198            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19199            boolean writeSettings) {
19200        if (deletedPs.parentPackageName != null) {
19201            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19202            return false;
19203        }
19204
19205        final boolean applyUserRestrictions
19206                = (allUserHandles != null) && (outInfo.origUsers != null);
19207        final PackageSetting disabledPs;
19208        // Confirm if the system package has been updated
19209        // An updated system app can be deleted. This will also have to restore
19210        // the system pkg from system partition
19211        // reader
19212        synchronized (mPackages) {
19213            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19214        }
19215
19216        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19217                + " disabledPs=" + disabledPs);
19218
19219        if (disabledPs == null) {
19220            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19221            return false;
19222        } else if (DEBUG_REMOVE) {
19223            Slog.d(TAG, "Deleting system pkg from data partition");
19224        }
19225
19226        if (DEBUG_REMOVE) {
19227            if (applyUserRestrictions) {
19228                Slog.d(TAG, "Remembering install states:");
19229                for (int userId : allUserHandles) {
19230                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19231                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19232                }
19233            }
19234        }
19235
19236        // Delete the updated package
19237        outInfo.isRemovedPackageSystemUpdate = true;
19238        if (outInfo.removedChildPackages != null) {
19239            final int childCount = (deletedPs.childPackageNames != null)
19240                    ? deletedPs.childPackageNames.size() : 0;
19241            for (int i = 0; i < childCount; i++) {
19242                String childPackageName = deletedPs.childPackageNames.get(i);
19243                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19244                        .contains(childPackageName)) {
19245                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19246                            childPackageName);
19247                    if (childInfo != null) {
19248                        childInfo.isRemovedPackageSystemUpdate = true;
19249                    }
19250                }
19251            }
19252        }
19253
19254        if (disabledPs.versionCode < deletedPs.versionCode) {
19255            // Delete data for downgrades
19256            flags &= ~PackageManager.DELETE_KEEP_DATA;
19257        } else {
19258            // Preserve data by setting flag
19259            flags |= PackageManager.DELETE_KEEP_DATA;
19260        }
19261
19262        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19263                outInfo, writeSettings, disabledPs.pkg);
19264        if (!ret) {
19265            return false;
19266        }
19267
19268        // writer
19269        synchronized (mPackages) {
19270            // Reinstate the old system package
19271            enableSystemPackageLPw(disabledPs.pkg);
19272            // Remove any native libraries from the upgraded package.
19273            removeNativeBinariesLI(deletedPs);
19274        }
19275
19276        // Install the system package
19277        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19278        int parseFlags = mDefParseFlags
19279                | PackageParser.PARSE_MUST_BE_APK
19280                | PackageParser.PARSE_IS_SYSTEM
19281                | PackageParser.PARSE_IS_SYSTEM_DIR;
19282        if (locationIsPrivileged(disabledPs.codePath)) {
19283            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19284        }
19285
19286        final PackageParser.Package newPkg;
19287        try {
19288            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19289                0 /* currentTime */, null);
19290        } catch (PackageManagerException e) {
19291            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19292                    + e.getMessage());
19293            return false;
19294        }
19295
19296        try {
19297            // update shared libraries for the newly re-installed system package
19298            updateSharedLibrariesLPr(newPkg, null);
19299        } catch (PackageManagerException e) {
19300            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19301        }
19302
19303        prepareAppDataAfterInstallLIF(newPkg);
19304
19305        // writer
19306        synchronized (mPackages) {
19307            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19308
19309            // Propagate the permissions state as we do not want to drop on the floor
19310            // runtime permissions. The update permissions method below will take
19311            // care of removing obsolete permissions and grant install permissions.
19312            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19313            updatePermissionsLPw(newPkg.packageName, newPkg,
19314                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19315
19316            if (applyUserRestrictions) {
19317                boolean installedStateChanged = false;
19318                if (DEBUG_REMOVE) {
19319                    Slog.d(TAG, "Propagating install state across reinstall");
19320                }
19321                for (int userId : allUserHandles) {
19322                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19323                    if (DEBUG_REMOVE) {
19324                        Slog.d(TAG, "    user " + userId + " => " + installed);
19325                    }
19326                    if (installed != ps.getInstalled(userId)) {
19327                        installedStateChanged = true;
19328                    }
19329                    ps.setInstalled(installed, userId);
19330
19331                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19332                }
19333                // Regardless of writeSettings we need to ensure that this restriction
19334                // state propagation is persisted
19335                mSettings.writeAllUsersPackageRestrictionsLPr();
19336                if (installedStateChanged) {
19337                    mSettings.writeKernelMappingLPr(ps);
19338                }
19339            }
19340            // can downgrade to reader here
19341            if (writeSettings) {
19342                mSettings.writeLPr();
19343            }
19344        }
19345        return true;
19346    }
19347
19348    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19349            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19350            PackageRemovedInfo outInfo, boolean writeSettings,
19351            PackageParser.Package replacingPackage) {
19352        synchronized (mPackages) {
19353            if (outInfo != null) {
19354                outInfo.uid = ps.appId;
19355            }
19356
19357            if (outInfo != null && outInfo.removedChildPackages != null) {
19358                final int childCount = (ps.childPackageNames != null)
19359                        ? ps.childPackageNames.size() : 0;
19360                for (int i = 0; i < childCount; i++) {
19361                    String childPackageName = ps.childPackageNames.get(i);
19362                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19363                    if (childPs == null) {
19364                        return false;
19365                    }
19366                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19367                            childPackageName);
19368                    if (childInfo != null) {
19369                        childInfo.uid = childPs.appId;
19370                    }
19371                }
19372            }
19373        }
19374
19375        // Delete package data from internal structures and also remove data if flag is set
19376        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19377
19378        // Delete the child packages data
19379        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19380        for (int i = 0; i < childCount; i++) {
19381            PackageSetting childPs;
19382            synchronized (mPackages) {
19383                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19384            }
19385            if (childPs != null) {
19386                PackageRemovedInfo childOutInfo = (outInfo != null
19387                        && outInfo.removedChildPackages != null)
19388                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19389                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19390                        && (replacingPackage != null
19391                        && !replacingPackage.hasChildPackage(childPs.name))
19392                        ? flags & ~DELETE_KEEP_DATA : flags;
19393                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19394                        deleteFlags, writeSettings);
19395            }
19396        }
19397
19398        // Delete application code and resources only for parent packages
19399        if (ps.parentPackageName == null) {
19400            if (deleteCodeAndResources && (outInfo != null)) {
19401                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19402                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19403                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19404            }
19405        }
19406
19407        return true;
19408    }
19409
19410    @Override
19411    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19412            int userId) {
19413        mContext.enforceCallingOrSelfPermission(
19414                android.Manifest.permission.DELETE_PACKAGES, null);
19415        synchronized (mPackages) {
19416            // Cannot block uninstall of static shared libs as they are
19417            // considered a part of the using app (emulating static linking).
19418            // Also static libs are installed always on internal storage.
19419            PackageParser.Package pkg = mPackages.get(packageName);
19420            if (pkg != null && pkg.staticSharedLibName != null) {
19421                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19422                        + " providing static shared library: " + pkg.staticSharedLibName);
19423                return false;
19424            }
19425            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19426            mSettings.writePackageRestrictionsLPr(userId);
19427        }
19428        return true;
19429    }
19430
19431    @Override
19432    public boolean getBlockUninstallForUser(String packageName, int userId) {
19433        synchronized (mPackages) {
19434            final PackageSetting ps = mSettings.mPackages.get(packageName);
19435            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19436                return true;
19437            }
19438            return mSettings.getBlockUninstallLPr(userId, packageName);
19439        }
19440    }
19441
19442    @Override
19443    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19444        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19445        synchronized (mPackages) {
19446            PackageSetting ps = mSettings.mPackages.get(packageName);
19447            if (ps == null) {
19448                Log.w(TAG, "Package doesn't exist: " + packageName);
19449                return false;
19450            }
19451            if (systemUserApp) {
19452                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19453            } else {
19454                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19455            }
19456            mSettings.writeLPr();
19457        }
19458        return true;
19459    }
19460
19461    /*
19462     * This method handles package deletion in general
19463     */
19464    private boolean deletePackageLIF(String packageName, UserHandle user,
19465            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19466            PackageRemovedInfo outInfo, boolean writeSettings,
19467            PackageParser.Package replacingPackage) {
19468        if (packageName == null) {
19469            Slog.w(TAG, "Attempt to delete null packageName.");
19470            return false;
19471        }
19472
19473        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19474
19475        PackageSetting ps;
19476        synchronized (mPackages) {
19477            ps = mSettings.mPackages.get(packageName);
19478            if (ps == null) {
19479                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19480                return false;
19481            }
19482
19483            if (ps.parentPackageName != null && (!isSystemApp(ps)
19484                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19485                if (DEBUG_REMOVE) {
19486                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19487                            + ((user == null) ? UserHandle.USER_ALL : user));
19488                }
19489                final int removedUserId = (user != null) ? user.getIdentifier()
19490                        : UserHandle.USER_ALL;
19491                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19492                    return false;
19493                }
19494                markPackageUninstalledForUserLPw(ps, user);
19495                scheduleWritePackageRestrictionsLocked(user);
19496                return true;
19497            }
19498        }
19499
19500        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19501                && user.getIdentifier() != UserHandle.USER_ALL)) {
19502            // The caller is asking that the package only be deleted for a single
19503            // user.  To do this, we just mark its uninstalled state and delete
19504            // its data. If this is a system app, we only allow this to happen if
19505            // they have set the special DELETE_SYSTEM_APP which requests different
19506            // semantics than normal for uninstalling system apps.
19507            markPackageUninstalledForUserLPw(ps, user);
19508
19509            if (!isSystemApp(ps)) {
19510                // Do not uninstall the APK if an app should be cached
19511                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19512                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19513                    // Other user still have this package installed, so all
19514                    // we need to do is clear this user's data and save that
19515                    // it is uninstalled.
19516                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19517                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19518                        return false;
19519                    }
19520                    scheduleWritePackageRestrictionsLocked(user);
19521                    return true;
19522                } else {
19523                    // We need to set it back to 'installed' so the uninstall
19524                    // broadcasts will be sent correctly.
19525                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19526                    ps.setInstalled(true, user.getIdentifier());
19527                    mSettings.writeKernelMappingLPr(ps);
19528                }
19529            } else {
19530                // This is a system app, so we assume that the
19531                // other users still have this package installed, so all
19532                // we need to do is clear this user's data and save that
19533                // it is uninstalled.
19534                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19535                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19536                    return false;
19537                }
19538                scheduleWritePackageRestrictionsLocked(user);
19539                return true;
19540            }
19541        }
19542
19543        // If we are deleting a composite package for all users, keep track
19544        // of result for each child.
19545        if (ps.childPackageNames != null && outInfo != null) {
19546            synchronized (mPackages) {
19547                final int childCount = ps.childPackageNames.size();
19548                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19549                for (int i = 0; i < childCount; i++) {
19550                    String childPackageName = ps.childPackageNames.get(i);
19551                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19552                    childInfo.removedPackage = childPackageName;
19553                    childInfo.installerPackageName = ps.installerPackageName;
19554                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19555                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19556                    if (childPs != null) {
19557                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19558                    }
19559                }
19560            }
19561        }
19562
19563        boolean ret = false;
19564        if (isSystemApp(ps)) {
19565            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19566            // When an updated system application is deleted we delete the existing resources
19567            // as well and fall back to existing code in system partition
19568            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19569        } else {
19570            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19571            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19572                    outInfo, writeSettings, replacingPackage);
19573        }
19574
19575        // Take a note whether we deleted the package for all users
19576        if (outInfo != null) {
19577            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19578            if (outInfo.removedChildPackages != null) {
19579                synchronized (mPackages) {
19580                    final int childCount = outInfo.removedChildPackages.size();
19581                    for (int i = 0; i < childCount; i++) {
19582                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19583                        if (childInfo != null) {
19584                            childInfo.removedForAllUsers = mPackages.get(
19585                                    childInfo.removedPackage) == null;
19586                        }
19587                    }
19588                }
19589            }
19590            // If we uninstalled an update to a system app there may be some
19591            // child packages that appeared as they are declared in the system
19592            // app but were not declared in the update.
19593            if (isSystemApp(ps)) {
19594                synchronized (mPackages) {
19595                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19596                    final int childCount = (updatedPs.childPackageNames != null)
19597                            ? updatedPs.childPackageNames.size() : 0;
19598                    for (int i = 0; i < childCount; i++) {
19599                        String childPackageName = updatedPs.childPackageNames.get(i);
19600                        if (outInfo.removedChildPackages == null
19601                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19602                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19603                            if (childPs == null) {
19604                                continue;
19605                            }
19606                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19607                            installRes.name = childPackageName;
19608                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19609                            installRes.pkg = mPackages.get(childPackageName);
19610                            installRes.uid = childPs.pkg.applicationInfo.uid;
19611                            if (outInfo.appearedChildPackages == null) {
19612                                outInfo.appearedChildPackages = new ArrayMap<>();
19613                            }
19614                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19615                        }
19616                    }
19617                }
19618            }
19619        }
19620
19621        return ret;
19622    }
19623
19624    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19625        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19626                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19627        for (int nextUserId : userIds) {
19628            if (DEBUG_REMOVE) {
19629                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19630            }
19631            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19632                    false /*installed*/,
19633                    true /*stopped*/,
19634                    true /*notLaunched*/,
19635                    false /*hidden*/,
19636                    false /*suspended*/,
19637                    false /*instantApp*/,
19638                    null /*lastDisableAppCaller*/,
19639                    null /*enabledComponents*/,
19640                    null /*disabledComponents*/,
19641                    ps.readUserState(nextUserId).domainVerificationStatus,
19642                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19643        }
19644        mSettings.writeKernelMappingLPr(ps);
19645    }
19646
19647    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19648            PackageRemovedInfo outInfo) {
19649        final PackageParser.Package pkg;
19650        synchronized (mPackages) {
19651            pkg = mPackages.get(ps.name);
19652        }
19653
19654        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19655                : new int[] {userId};
19656        for (int nextUserId : userIds) {
19657            if (DEBUG_REMOVE) {
19658                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19659                        + nextUserId);
19660            }
19661
19662            destroyAppDataLIF(pkg, userId,
19663                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19664            destroyAppProfilesLIF(pkg, userId);
19665            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19666            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19667            schedulePackageCleaning(ps.name, nextUserId, false);
19668            synchronized (mPackages) {
19669                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19670                    scheduleWritePackageRestrictionsLocked(nextUserId);
19671                }
19672                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19673            }
19674        }
19675
19676        if (outInfo != null) {
19677            outInfo.removedPackage = ps.name;
19678            outInfo.installerPackageName = ps.installerPackageName;
19679            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19680            outInfo.removedAppId = ps.appId;
19681            outInfo.removedUsers = userIds;
19682            outInfo.broadcastUsers = userIds;
19683        }
19684
19685        return true;
19686    }
19687
19688    private final class ClearStorageConnection implements ServiceConnection {
19689        IMediaContainerService mContainerService;
19690
19691        @Override
19692        public void onServiceConnected(ComponentName name, IBinder service) {
19693            synchronized (this) {
19694                mContainerService = IMediaContainerService.Stub
19695                        .asInterface(Binder.allowBlocking(service));
19696                notifyAll();
19697            }
19698        }
19699
19700        @Override
19701        public void onServiceDisconnected(ComponentName name) {
19702        }
19703    }
19704
19705    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19706        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19707
19708        final boolean mounted;
19709        if (Environment.isExternalStorageEmulated()) {
19710            mounted = true;
19711        } else {
19712            final String status = Environment.getExternalStorageState();
19713
19714            mounted = status.equals(Environment.MEDIA_MOUNTED)
19715                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19716        }
19717
19718        if (!mounted) {
19719            return;
19720        }
19721
19722        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19723        int[] users;
19724        if (userId == UserHandle.USER_ALL) {
19725            users = sUserManager.getUserIds();
19726        } else {
19727            users = new int[] { userId };
19728        }
19729        final ClearStorageConnection conn = new ClearStorageConnection();
19730        if (mContext.bindServiceAsUser(
19731                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19732            try {
19733                for (int curUser : users) {
19734                    long timeout = SystemClock.uptimeMillis() + 5000;
19735                    synchronized (conn) {
19736                        long now;
19737                        while (conn.mContainerService == null &&
19738                                (now = SystemClock.uptimeMillis()) < timeout) {
19739                            try {
19740                                conn.wait(timeout - now);
19741                            } catch (InterruptedException e) {
19742                            }
19743                        }
19744                    }
19745                    if (conn.mContainerService == null) {
19746                        return;
19747                    }
19748
19749                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19750                    clearDirectory(conn.mContainerService,
19751                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19752                    if (allData) {
19753                        clearDirectory(conn.mContainerService,
19754                                userEnv.buildExternalStorageAppDataDirs(packageName));
19755                        clearDirectory(conn.mContainerService,
19756                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19757                    }
19758                }
19759            } finally {
19760                mContext.unbindService(conn);
19761            }
19762        }
19763    }
19764
19765    @Override
19766    public void clearApplicationProfileData(String packageName) {
19767        enforceSystemOrRoot("Only the system can clear all profile data");
19768
19769        final PackageParser.Package pkg;
19770        synchronized (mPackages) {
19771            pkg = mPackages.get(packageName);
19772        }
19773
19774        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19775            synchronized (mInstallLock) {
19776                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19777            }
19778        }
19779    }
19780
19781    @Override
19782    public void clearApplicationUserData(final String packageName,
19783            final IPackageDataObserver observer, final int userId) {
19784        mContext.enforceCallingOrSelfPermission(
19785                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19786
19787        final int callingUid = Binder.getCallingUid();
19788        enforceCrossUserPermission(callingUid, userId,
19789                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19790
19791        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19792        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
19793            return;
19794        }
19795        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19796            throw new SecurityException("Cannot clear data for a protected package: "
19797                    + packageName);
19798        }
19799        // Queue up an async operation since the package deletion may take a little while.
19800        mHandler.post(new Runnable() {
19801            public void run() {
19802                mHandler.removeCallbacks(this);
19803                final boolean succeeded;
19804                try (PackageFreezer freezer = freezePackage(packageName,
19805                        "clearApplicationUserData")) {
19806                    synchronized (mInstallLock) {
19807                        succeeded = clearApplicationUserDataLIF(packageName, userId);
19808                    }
19809                    clearExternalStorageDataSync(packageName, userId, true);
19810                    synchronized (mPackages) {
19811                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19812                                packageName, userId);
19813                    }
19814                }
19815                if (succeeded) {
19816                    // invoke DeviceStorageMonitor's update method to clear any notifications
19817                    DeviceStorageMonitorInternal dsm = LocalServices
19818                            .getService(DeviceStorageMonitorInternal.class);
19819                    if (dsm != null) {
19820                        dsm.checkMemory();
19821                    }
19822                }
19823                if(observer != null) {
19824                    try {
19825                        observer.onRemoveCompleted(packageName, succeeded);
19826                    } catch (RemoteException e) {
19827                        Log.i(TAG, "Observer no longer exists.");
19828                    }
19829                } //end if observer
19830            } //end run
19831        });
19832    }
19833
19834    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19835        if (packageName == null) {
19836            Slog.w(TAG, "Attempt to delete null packageName.");
19837            return false;
19838        }
19839
19840        // Try finding details about the requested package
19841        PackageParser.Package pkg;
19842        synchronized (mPackages) {
19843            pkg = mPackages.get(packageName);
19844            if (pkg == null) {
19845                final PackageSetting ps = mSettings.mPackages.get(packageName);
19846                if (ps != null) {
19847                    pkg = ps.pkg;
19848                }
19849            }
19850
19851            if (pkg == null) {
19852                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19853                return false;
19854            }
19855
19856            PackageSetting ps = (PackageSetting) pkg.mExtras;
19857            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19858        }
19859
19860        clearAppDataLIF(pkg, userId,
19861                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19862
19863        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19864        removeKeystoreDataIfNeeded(userId, appId);
19865
19866        UserManagerInternal umInternal = getUserManagerInternal();
19867        final int flags;
19868        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19869            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19870        } else if (umInternal.isUserRunning(userId)) {
19871            flags = StorageManager.FLAG_STORAGE_DE;
19872        } else {
19873            flags = 0;
19874        }
19875        prepareAppDataContentsLIF(pkg, userId, flags);
19876
19877        return true;
19878    }
19879
19880    /**
19881     * Reverts user permission state changes (permissions and flags) in
19882     * all packages for a given user.
19883     *
19884     * @param userId The device user for which to do a reset.
19885     */
19886    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19887        final int packageCount = mPackages.size();
19888        for (int i = 0; i < packageCount; i++) {
19889            PackageParser.Package pkg = mPackages.valueAt(i);
19890            PackageSetting ps = (PackageSetting) pkg.mExtras;
19891            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19892        }
19893    }
19894
19895    private void resetNetworkPolicies(int userId) {
19896        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19897    }
19898
19899    /**
19900     * Reverts user permission state changes (permissions and flags).
19901     *
19902     * @param ps The package for which to reset.
19903     * @param userId The device user for which to do a reset.
19904     */
19905    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19906            final PackageSetting ps, final int userId) {
19907        if (ps.pkg == null) {
19908            return;
19909        }
19910
19911        // These are flags that can change base on user actions.
19912        final int userSettableMask = FLAG_PERMISSION_USER_SET
19913                | FLAG_PERMISSION_USER_FIXED
19914                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19915                | FLAG_PERMISSION_REVIEW_REQUIRED;
19916
19917        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19918                | FLAG_PERMISSION_POLICY_FIXED;
19919
19920        boolean writeInstallPermissions = false;
19921        boolean writeRuntimePermissions = false;
19922
19923        final int permissionCount = ps.pkg.requestedPermissions.size();
19924        for (int i = 0; i < permissionCount; i++) {
19925            String permission = ps.pkg.requestedPermissions.get(i);
19926
19927            BasePermission bp = mSettings.mPermissions.get(permission);
19928            if (bp == null) {
19929                continue;
19930            }
19931
19932            // If shared user we just reset the state to which only this app contributed.
19933            if (ps.sharedUser != null) {
19934                boolean used = false;
19935                final int packageCount = ps.sharedUser.packages.size();
19936                for (int j = 0; j < packageCount; j++) {
19937                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19938                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19939                            && pkg.pkg.requestedPermissions.contains(permission)) {
19940                        used = true;
19941                        break;
19942                    }
19943                }
19944                if (used) {
19945                    continue;
19946                }
19947            }
19948
19949            PermissionsState permissionsState = ps.getPermissionsState();
19950
19951            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
19952
19953            // Always clear the user settable flags.
19954            final boolean hasInstallState = permissionsState.getInstallPermissionState(
19955                    bp.name) != null;
19956            // If permission review is enabled and this is a legacy app, mark the
19957            // permission as requiring a review as this is the initial state.
19958            int flags = 0;
19959            if (mPermissionReviewRequired
19960                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19961                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19962            }
19963            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19964                if (hasInstallState) {
19965                    writeInstallPermissions = true;
19966                } else {
19967                    writeRuntimePermissions = true;
19968                }
19969            }
19970
19971            // Below is only runtime permission handling.
19972            if (!bp.isRuntime()) {
19973                continue;
19974            }
19975
19976            // Never clobber system or policy.
19977            if ((oldFlags & policyOrSystemFlags) != 0) {
19978                continue;
19979            }
19980
19981            // If this permission was granted by default, make sure it is.
19982            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19983                if (permissionsState.grantRuntimePermission(bp, userId)
19984                        != PERMISSION_OPERATION_FAILURE) {
19985                    writeRuntimePermissions = true;
19986                }
19987            // If permission review is enabled the permissions for a legacy apps
19988            // are represented as constantly granted runtime ones, so don't revoke.
19989            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19990                // Otherwise, reset the permission.
19991                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19992                switch (revokeResult) {
19993                    case PERMISSION_OPERATION_SUCCESS:
19994                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19995                        writeRuntimePermissions = true;
19996                        final int appId = ps.appId;
19997                        mHandler.post(new Runnable() {
19998                            @Override
19999                            public void run() {
20000                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
20001                            }
20002                        });
20003                    } break;
20004                }
20005            }
20006        }
20007
20008        // Synchronously write as we are taking permissions away.
20009        if (writeRuntimePermissions) {
20010            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
20011        }
20012
20013        // Synchronously write as we are taking permissions away.
20014        if (writeInstallPermissions) {
20015            mSettings.writeLPr();
20016        }
20017    }
20018
20019    /**
20020     * Remove entries from the keystore daemon. Will only remove it if the
20021     * {@code appId} is valid.
20022     */
20023    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
20024        if (appId < 0) {
20025            return;
20026        }
20027
20028        final KeyStore keyStore = KeyStore.getInstance();
20029        if (keyStore != null) {
20030            if (userId == UserHandle.USER_ALL) {
20031                for (final int individual : sUserManager.getUserIds()) {
20032                    keyStore.clearUid(UserHandle.getUid(individual, appId));
20033                }
20034            } else {
20035                keyStore.clearUid(UserHandle.getUid(userId, appId));
20036            }
20037        } else {
20038            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
20039        }
20040    }
20041
20042    @Override
20043    public void deleteApplicationCacheFiles(final String packageName,
20044            final IPackageDataObserver observer) {
20045        final int userId = UserHandle.getCallingUserId();
20046        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
20047    }
20048
20049    @Override
20050    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20051            final IPackageDataObserver observer) {
20052        final int callingUid = Binder.getCallingUid();
20053        mContext.enforceCallingOrSelfPermission(
20054                android.Manifest.permission.DELETE_CACHE_FILES, null);
20055        enforceCrossUserPermission(callingUid, userId,
20056                /* requireFullPermission= */ true, /* checkShell= */ false,
20057                "delete application cache files");
20058        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20059                android.Manifest.permission.ACCESS_INSTANT_APPS);
20060
20061        final PackageParser.Package pkg;
20062        synchronized (mPackages) {
20063            pkg = mPackages.get(packageName);
20064        }
20065
20066        // Queue up an async operation since the package deletion may take a little while.
20067        mHandler.post(new Runnable() {
20068            public void run() {
20069                final PackageSetting ps = (PackageSetting) pkg.mExtras;
20070                boolean doClearData = true;
20071                if (ps != null) {
20072                    final boolean targetIsInstantApp =
20073                            ps.getInstantApp(UserHandle.getUserId(callingUid));
20074                    doClearData = !targetIsInstantApp
20075                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20076                }
20077                if (doClearData) {
20078                    synchronized (mInstallLock) {
20079                        final int flags = StorageManager.FLAG_STORAGE_DE
20080                                | StorageManager.FLAG_STORAGE_CE;
20081                        // We're only clearing cache files, so we don't care if the
20082                        // app is unfrozen and still able to run
20083                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20084                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20085                    }
20086                    clearExternalStorageDataSync(packageName, userId, false);
20087                }
20088                if (observer != null) {
20089                    try {
20090                        observer.onRemoveCompleted(packageName, true);
20091                    } catch (RemoteException e) {
20092                        Log.i(TAG, "Observer no longer exists.");
20093                    }
20094                }
20095            }
20096        });
20097    }
20098
20099    @Override
20100    public void getPackageSizeInfo(final String packageName, int userHandle,
20101            final IPackageStatsObserver observer) {
20102        throw new UnsupportedOperationException(
20103                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20104    }
20105
20106    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20107        final PackageSetting ps;
20108        synchronized (mPackages) {
20109            ps = mSettings.mPackages.get(packageName);
20110            if (ps == null) {
20111                Slog.w(TAG, "Failed to find settings for " + packageName);
20112                return false;
20113            }
20114        }
20115
20116        final String[] packageNames = { packageName };
20117        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20118        final String[] codePaths = { ps.codePathString };
20119
20120        try {
20121            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20122                    ps.appId, ceDataInodes, codePaths, stats);
20123
20124            // For now, ignore code size of packages on system partition
20125            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20126                stats.codeSize = 0;
20127            }
20128
20129            // External clients expect these to be tracked separately
20130            stats.dataSize -= stats.cacheSize;
20131
20132        } catch (InstallerException e) {
20133            Slog.w(TAG, String.valueOf(e));
20134            return false;
20135        }
20136
20137        return true;
20138    }
20139
20140    private int getUidTargetSdkVersionLockedLPr(int uid) {
20141        Object obj = mSettings.getUserIdLPr(uid);
20142        if (obj instanceof SharedUserSetting) {
20143            final SharedUserSetting sus = (SharedUserSetting) obj;
20144            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20145            final Iterator<PackageSetting> it = sus.packages.iterator();
20146            while (it.hasNext()) {
20147                final PackageSetting ps = it.next();
20148                if (ps.pkg != null) {
20149                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20150                    if (v < vers) vers = v;
20151                }
20152            }
20153            return vers;
20154        } else if (obj instanceof PackageSetting) {
20155            final PackageSetting ps = (PackageSetting) obj;
20156            if (ps.pkg != null) {
20157                return ps.pkg.applicationInfo.targetSdkVersion;
20158            }
20159        }
20160        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20161    }
20162
20163    @Override
20164    public void addPreferredActivity(IntentFilter filter, int match,
20165            ComponentName[] set, ComponentName activity, int userId) {
20166        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20167                "Adding preferred");
20168    }
20169
20170    private void addPreferredActivityInternal(IntentFilter filter, int match,
20171            ComponentName[] set, ComponentName activity, boolean always, int userId,
20172            String opname) {
20173        // writer
20174        int callingUid = Binder.getCallingUid();
20175        enforceCrossUserPermission(callingUid, userId,
20176                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20177        if (filter.countActions() == 0) {
20178            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20179            return;
20180        }
20181        synchronized (mPackages) {
20182            if (mContext.checkCallingOrSelfPermission(
20183                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20184                    != PackageManager.PERMISSION_GRANTED) {
20185                if (getUidTargetSdkVersionLockedLPr(callingUid)
20186                        < Build.VERSION_CODES.FROYO) {
20187                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20188                            + callingUid);
20189                    return;
20190                }
20191                mContext.enforceCallingOrSelfPermission(
20192                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20193            }
20194
20195            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20196            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20197                    + userId + ":");
20198            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20199            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20200            scheduleWritePackageRestrictionsLocked(userId);
20201            postPreferredActivityChangedBroadcast(userId);
20202        }
20203    }
20204
20205    private void postPreferredActivityChangedBroadcast(int userId) {
20206        mHandler.post(() -> {
20207            final IActivityManager am = ActivityManager.getService();
20208            if (am == null) {
20209                return;
20210            }
20211
20212            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20213            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20214            try {
20215                am.broadcastIntent(null, intent, null, null,
20216                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20217                        null, false, false, userId);
20218            } catch (RemoteException e) {
20219            }
20220        });
20221    }
20222
20223    @Override
20224    public void replacePreferredActivity(IntentFilter filter, int match,
20225            ComponentName[] set, ComponentName activity, int userId) {
20226        if (filter.countActions() != 1) {
20227            throw new IllegalArgumentException(
20228                    "replacePreferredActivity expects filter to have only 1 action.");
20229        }
20230        if (filter.countDataAuthorities() != 0
20231                || filter.countDataPaths() != 0
20232                || filter.countDataSchemes() > 1
20233                || filter.countDataTypes() != 0) {
20234            throw new IllegalArgumentException(
20235                    "replacePreferredActivity expects filter to have no data authorities, " +
20236                    "paths, or types; and at most one scheme.");
20237        }
20238
20239        final int callingUid = Binder.getCallingUid();
20240        enforceCrossUserPermission(callingUid, userId,
20241                true /* requireFullPermission */, false /* checkShell */,
20242                "replace preferred activity");
20243        synchronized (mPackages) {
20244            if (mContext.checkCallingOrSelfPermission(
20245                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20246                    != PackageManager.PERMISSION_GRANTED) {
20247                if (getUidTargetSdkVersionLockedLPr(callingUid)
20248                        < Build.VERSION_CODES.FROYO) {
20249                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20250                            + Binder.getCallingUid());
20251                    return;
20252                }
20253                mContext.enforceCallingOrSelfPermission(
20254                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20255            }
20256
20257            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20258            if (pir != null) {
20259                // Get all of the existing entries that exactly match this filter.
20260                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20261                if (existing != null && existing.size() == 1) {
20262                    PreferredActivity cur = existing.get(0);
20263                    if (DEBUG_PREFERRED) {
20264                        Slog.i(TAG, "Checking replace of preferred:");
20265                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20266                        if (!cur.mPref.mAlways) {
20267                            Slog.i(TAG, "  -- CUR; not mAlways!");
20268                        } else {
20269                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20270                            Slog.i(TAG, "  -- CUR: mSet="
20271                                    + Arrays.toString(cur.mPref.mSetComponents));
20272                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20273                            Slog.i(TAG, "  -- NEW: mMatch="
20274                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20275                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20276                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20277                        }
20278                    }
20279                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20280                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20281                            && cur.mPref.sameSet(set)) {
20282                        // Setting the preferred activity to what it happens to be already
20283                        if (DEBUG_PREFERRED) {
20284                            Slog.i(TAG, "Replacing with same preferred activity "
20285                                    + cur.mPref.mShortComponent + " for user "
20286                                    + userId + ":");
20287                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20288                        }
20289                        return;
20290                    }
20291                }
20292
20293                if (existing != null) {
20294                    if (DEBUG_PREFERRED) {
20295                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20296                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20297                    }
20298                    for (int i = 0; i < existing.size(); i++) {
20299                        PreferredActivity pa = existing.get(i);
20300                        if (DEBUG_PREFERRED) {
20301                            Slog.i(TAG, "Removing existing preferred activity "
20302                                    + pa.mPref.mComponent + ":");
20303                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20304                        }
20305                        pir.removeFilter(pa);
20306                    }
20307                }
20308            }
20309            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20310                    "Replacing preferred");
20311        }
20312    }
20313
20314    @Override
20315    public void clearPackagePreferredActivities(String packageName) {
20316        final int callingUid = Binder.getCallingUid();
20317        if (getInstantAppPackageName(callingUid) != null) {
20318            return;
20319        }
20320        // writer
20321        synchronized (mPackages) {
20322            PackageParser.Package pkg = mPackages.get(packageName);
20323            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20324                if (mContext.checkCallingOrSelfPermission(
20325                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20326                        != PackageManager.PERMISSION_GRANTED) {
20327                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20328                            < Build.VERSION_CODES.FROYO) {
20329                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20330                                + callingUid);
20331                        return;
20332                    }
20333                    mContext.enforceCallingOrSelfPermission(
20334                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20335                }
20336            }
20337            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20338            if (ps != null
20339                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20340                return;
20341            }
20342            int user = UserHandle.getCallingUserId();
20343            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20344                scheduleWritePackageRestrictionsLocked(user);
20345            }
20346        }
20347    }
20348
20349    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20350    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20351        ArrayList<PreferredActivity> removed = null;
20352        boolean changed = false;
20353        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20354            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20355            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20356            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20357                continue;
20358            }
20359            Iterator<PreferredActivity> it = pir.filterIterator();
20360            while (it.hasNext()) {
20361                PreferredActivity pa = it.next();
20362                // Mark entry for removal only if it matches the package name
20363                // and the entry is of type "always".
20364                if (packageName == null ||
20365                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20366                                && pa.mPref.mAlways)) {
20367                    if (removed == null) {
20368                        removed = new ArrayList<PreferredActivity>();
20369                    }
20370                    removed.add(pa);
20371                }
20372            }
20373            if (removed != null) {
20374                for (int j=0; j<removed.size(); j++) {
20375                    PreferredActivity pa = removed.get(j);
20376                    pir.removeFilter(pa);
20377                }
20378                changed = true;
20379            }
20380        }
20381        if (changed) {
20382            postPreferredActivityChangedBroadcast(userId);
20383        }
20384        return changed;
20385    }
20386
20387    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20388    private void clearIntentFilterVerificationsLPw(int userId) {
20389        final int packageCount = mPackages.size();
20390        for (int i = 0; i < packageCount; i++) {
20391            PackageParser.Package pkg = mPackages.valueAt(i);
20392            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20393        }
20394    }
20395
20396    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20397    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20398        if (userId == UserHandle.USER_ALL) {
20399            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20400                    sUserManager.getUserIds())) {
20401                for (int oneUserId : sUserManager.getUserIds()) {
20402                    scheduleWritePackageRestrictionsLocked(oneUserId);
20403                }
20404            }
20405        } else {
20406            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20407                scheduleWritePackageRestrictionsLocked(userId);
20408            }
20409        }
20410    }
20411
20412    /** Clears state for all users, and touches intent filter verification policy */
20413    void clearDefaultBrowserIfNeeded(String packageName) {
20414        for (int oneUserId : sUserManager.getUserIds()) {
20415            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20416        }
20417    }
20418
20419    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20420        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20421        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20422            if (packageName.equals(defaultBrowserPackageName)) {
20423                setDefaultBrowserPackageName(null, userId);
20424            }
20425        }
20426    }
20427
20428    @Override
20429    public void resetApplicationPreferences(int userId) {
20430        mContext.enforceCallingOrSelfPermission(
20431                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20432        final long identity = Binder.clearCallingIdentity();
20433        // writer
20434        try {
20435            synchronized (mPackages) {
20436                clearPackagePreferredActivitiesLPw(null, userId);
20437                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20438                // TODO: We have to reset the default SMS and Phone. This requires
20439                // significant refactoring to keep all default apps in the package
20440                // manager (cleaner but more work) or have the services provide
20441                // callbacks to the package manager to request a default app reset.
20442                applyFactoryDefaultBrowserLPw(userId);
20443                clearIntentFilterVerificationsLPw(userId);
20444                primeDomainVerificationsLPw(userId);
20445                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20446                scheduleWritePackageRestrictionsLocked(userId);
20447            }
20448            resetNetworkPolicies(userId);
20449        } finally {
20450            Binder.restoreCallingIdentity(identity);
20451        }
20452    }
20453
20454    @Override
20455    public int getPreferredActivities(List<IntentFilter> outFilters,
20456            List<ComponentName> outActivities, String packageName) {
20457        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20458            return 0;
20459        }
20460        int num = 0;
20461        final int userId = UserHandle.getCallingUserId();
20462        // reader
20463        synchronized (mPackages) {
20464            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20465            if (pir != null) {
20466                final Iterator<PreferredActivity> it = pir.filterIterator();
20467                while (it.hasNext()) {
20468                    final PreferredActivity pa = it.next();
20469                    if (packageName == null
20470                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20471                                    && pa.mPref.mAlways)) {
20472                        if (outFilters != null) {
20473                            outFilters.add(new IntentFilter(pa));
20474                        }
20475                        if (outActivities != null) {
20476                            outActivities.add(pa.mPref.mComponent);
20477                        }
20478                    }
20479                }
20480            }
20481        }
20482
20483        return num;
20484    }
20485
20486    @Override
20487    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20488            int userId) {
20489        int callingUid = Binder.getCallingUid();
20490        if (callingUid != Process.SYSTEM_UID) {
20491            throw new SecurityException(
20492                    "addPersistentPreferredActivity can only be run by the system");
20493        }
20494        if (filter.countActions() == 0) {
20495            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20496            return;
20497        }
20498        synchronized (mPackages) {
20499            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20500                    ":");
20501            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20502            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20503                    new PersistentPreferredActivity(filter, activity));
20504            scheduleWritePackageRestrictionsLocked(userId);
20505            postPreferredActivityChangedBroadcast(userId);
20506        }
20507    }
20508
20509    @Override
20510    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20511        int callingUid = Binder.getCallingUid();
20512        if (callingUid != Process.SYSTEM_UID) {
20513            throw new SecurityException(
20514                    "clearPackagePersistentPreferredActivities can only be run by the system");
20515        }
20516        ArrayList<PersistentPreferredActivity> removed = null;
20517        boolean changed = false;
20518        synchronized (mPackages) {
20519            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20520                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20521                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20522                        .valueAt(i);
20523                if (userId != thisUserId) {
20524                    continue;
20525                }
20526                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20527                while (it.hasNext()) {
20528                    PersistentPreferredActivity ppa = it.next();
20529                    // Mark entry for removal only if it matches the package name.
20530                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20531                        if (removed == null) {
20532                            removed = new ArrayList<PersistentPreferredActivity>();
20533                        }
20534                        removed.add(ppa);
20535                    }
20536                }
20537                if (removed != null) {
20538                    for (int j=0; j<removed.size(); j++) {
20539                        PersistentPreferredActivity ppa = removed.get(j);
20540                        ppir.removeFilter(ppa);
20541                    }
20542                    changed = true;
20543                }
20544            }
20545
20546            if (changed) {
20547                scheduleWritePackageRestrictionsLocked(userId);
20548                postPreferredActivityChangedBroadcast(userId);
20549            }
20550        }
20551    }
20552
20553    /**
20554     * Common machinery for picking apart a restored XML blob and passing
20555     * it to a caller-supplied functor to be applied to the running system.
20556     */
20557    private void restoreFromXml(XmlPullParser parser, int userId,
20558            String expectedStartTag, BlobXmlRestorer functor)
20559            throws IOException, XmlPullParserException {
20560        int type;
20561        while ((type = parser.next()) != XmlPullParser.START_TAG
20562                && type != XmlPullParser.END_DOCUMENT) {
20563        }
20564        if (type != XmlPullParser.START_TAG) {
20565            // oops didn't find a start tag?!
20566            if (DEBUG_BACKUP) {
20567                Slog.e(TAG, "Didn't find start tag during restore");
20568            }
20569            return;
20570        }
20571Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20572        // this is supposed to be TAG_PREFERRED_BACKUP
20573        if (!expectedStartTag.equals(parser.getName())) {
20574            if (DEBUG_BACKUP) {
20575                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20576            }
20577            return;
20578        }
20579
20580        // skip interfering stuff, then we're aligned with the backing implementation
20581        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20582Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20583        functor.apply(parser, userId);
20584    }
20585
20586    private interface BlobXmlRestorer {
20587        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20588    }
20589
20590    /**
20591     * Non-Binder method, support for the backup/restore mechanism: write the
20592     * full set of preferred activities in its canonical XML format.  Returns the
20593     * XML output as a byte array, or null if there is none.
20594     */
20595    @Override
20596    public byte[] getPreferredActivityBackup(int userId) {
20597        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20598            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20599        }
20600
20601        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20602        try {
20603            final XmlSerializer serializer = new FastXmlSerializer();
20604            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20605            serializer.startDocument(null, true);
20606            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20607
20608            synchronized (mPackages) {
20609                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20610            }
20611
20612            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20613            serializer.endDocument();
20614            serializer.flush();
20615        } catch (Exception e) {
20616            if (DEBUG_BACKUP) {
20617                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20618            }
20619            return null;
20620        }
20621
20622        return dataStream.toByteArray();
20623    }
20624
20625    @Override
20626    public void restorePreferredActivities(byte[] backup, int userId) {
20627        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20628            throw new SecurityException("Only the system may call restorePreferredActivities()");
20629        }
20630
20631        try {
20632            final XmlPullParser parser = Xml.newPullParser();
20633            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20634            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20635                    new BlobXmlRestorer() {
20636                        @Override
20637                        public void apply(XmlPullParser parser, int userId)
20638                                throws XmlPullParserException, IOException {
20639                            synchronized (mPackages) {
20640                                mSettings.readPreferredActivitiesLPw(parser, userId);
20641                            }
20642                        }
20643                    } );
20644        } catch (Exception e) {
20645            if (DEBUG_BACKUP) {
20646                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20647            }
20648        }
20649    }
20650
20651    /**
20652     * Non-Binder method, support for the backup/restore mechanism: write the
20653     * default browser (etc) settings in its canonical XML format.  Returns the default
20654     * browser XML representation as a byte array, or null if there is none.
20655     */
20656    @Override
20657    public byte[] getDefaultAppsBackup(int userId) {
20658        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20659            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20660        }
20661
20662        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20663        try {
20664            final XmlSerializer serializer = new FastXmlSerializer();
20665            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20666            serializer.startDocument(null, true);
20667            serializer.startTag(null, TAG_DEFAULT_APPS);
20668
20669            synchronized (mPackages) {
20670                mSettings.writeDefaultAppsLPr(serializer, userId);
20671            }
20672
20673            serializer.endTag(null, TAG_DEFAULT_APPS);
20674            serializer.endDocument();
20675            serializer.flush();
20676        } catch (Exception e) {
20677            if (DEBUG_BACKUP) {
20678                Slog.e(TAG, "Unable to write default apps for backup", e);
20679            }
20680            return null;
20681        }
20682
20683        return dataStream.toByteArray();
20684    }
20685
20686    @Override
20687    public void restoreDefaultApps(byte[] backup, int userId) {
20688        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20689            throw new SecurityException("Only the system may call restoreDefaultApps()");
20690        }
20691
20692        try {
20693            final XmlPullParser parser = Xml.newPullParser();
20694            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20695            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20696                    new BlobXmlRestorer() {
20697                        @Override
20698                        public void apply(XmlPullParser parser, int userId)
20699                                throws XmlPullParserException, IOException {
20700                            synchronized (mPackages) {
20701                                mSettings.readDefaultAppsLPw(parser, userId);
20702                            }
20703                        }
20704                    } );
20705        } catch (Exception e) {
20706            if (DEBUG_BACKUP) {
20707                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20708            }
20709        }
20710    }
20711
20712    @Override
20713    public byte[] getIntentFilterVerificationBackup(int userId) {
20714        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20715            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20716        }
20717
20718        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20719        try {
20720            final XmlSerializer serializer = new FastXmlSerializer();
20721            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20722            serializer.startDocument(null, true);
20723            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20724
20725            synchronized (mPackages) {
20726                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20727            }
20728
20729            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20730            serializer.endDocument();
20731            serializer.flush();
20732        } catch (Exception e) {
20733            if (DEBUG_BACKUP) {
20734                Slog.e(TAG, "Unable to write default apps for backup", e);
20735            }
20736            return null;
20737        }
20738
20739        return dataStream.toByteArray();
20740    }
20741
20742    @Override
20743    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20744        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20745            throw new SecurityException("Only the system may call restorePreferredActivities()");
20746        }
20747
20748        try {
20749            final XmlPullParser parser = Xml.newPullParser();
20750            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20751            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20752                    new BlobXmlRestorer() {
20753                        @Override
20754                        public void apply(XmlPullParser parser, int userId)
20755                                throws XmlPullParserException, IOException {
20756                            synchronized (mPackages) {
20757                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20758                                mSettings.writeLPr();
20759                            }
20760                        }
20761                    } );
20762        } catch (Exception e) {
20763            if (DEBUG_BACKUP) {
20764                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20765            }
20766        }
20767    }
20768
20769    @Override
20770    public byte[] getPermissionGrantBackup(int userId) {
20771        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20772            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20773        }
20774
20775        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20776        try {
20777            final XmlSerializer serializer = new FastXmlSerializer();
20778            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20779            serializer.startDocument(null, true);
20780            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20781
20782            synchronized (mPackages) {
20783                serializeRuntimePermissionGrantsLPr(serializer, userId);
20784            }
20785
20786            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20787            serializer.endDocument();
20788            serializer.flush();
20789        } catch (Exception e) {
20790            if (DEBUG_BACKUP) {
20791                Slog.e(TAG, "Unable to write default apps for backup", e);
20792            }
20793            return null;
20794        }
20795
20796        return dataStream.toByteArray();
20797    }
20798
20799    @Override
20800    public void restorePermissionGrants(byte[] backup, int userId) {
20801        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20802            throw new SecurityException("Only the system may call restorePermissionGrants()");
20803        }
20804
20805        try {
20806            final XmlPullParser parser = Xml.newPullParser();
20807            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20808            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20809                    new BlobXmlRestorer() {
20810                        @Override
20811                        public void apply(XmlPullParser parser, int userId)
20812                                throws XmlPullParserException, IOException {
20813                            synchronized (mPackages) {
20814                                processRestoredPermissionGrantsLPr(parser, userId);
20815                            }
20816                        }
20817                    } );
20818        } catch (Exception e) {
20819            if (DEBUG_BACKUP) {
20820                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20821            }
20822        }
20823    }
20824
20825    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20826            throws IOException {
20827        serializer.startTag(null, TAG_ALL_GRANTS);
20828
20829        final int N = mSettings.mPackages.size();
20830        for (int i = 0; i < N; i++) {
20831            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20832            boolean pkgGrantsKnown = false;
20833
20834            PermissionsState packagePerms = ps.getPermissionsState();
20835
20836            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20837                final int grantFlags = state.getFlags();
20838                // only look at grants that are not system/policy fixed
20839                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20840                    final boolean isGranted = state.isGranted();
20841                    // And only back up the user-twiddled state bits
20842                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20843                        final String packageName = mSettings.mPackages.keyAt(i);
20844                        if (!pkgGrantsKnown) {
20845                            serializer.startTag(null, TAG_GRANT);
20846                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20847                            pkgGrantsKnown = true;
20848                        }
20849
20850                        final boolean userSet =
20851                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20852                        final boolean userFixed =
20853                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20854                        final boolean revoke =
20855                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20856
20857                        serializer.startTag(null, TAG_PERMISSION);
20858                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20859                        if (isGranted) {
20860                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20861                        }
20862                        if (userSet) {
20863                            serializer.attribute(null, ATTR_USER_SET, "true");
20864                        }
20865                        if (userFixed) {
20866                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20867                        }
20868                        if (revoke) {
20869                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20870                        }
20871                        serializer.endTag(null, TAG_PERMISSION);
20872                    }
20873                }
20874            }
20875
20876            if (pkgGrantsKnown) {
20877                serializer.endTag(null, TAG_GRANT);
20878            }
20879        }
20880
20881        serializer.endTag(null, TAG_ALL_GRANTS);
20882    }
20883
20884    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20885            throws XmlPullParserException, IOException {
20886        String pkgName = null;
20887        int outerDepth = parser.getDepth();
20888        int type;
20889        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20890                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20891            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20892                continue;
20893            }
20894
20895            final String tagName = parser.getName();
20896            if (tagName.equals(TAG_GRANT)) {
20897                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20898                if (DEBUG_BACKUP) {
20899                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20900                }
20901            } else if (tagName.equals(TAG_PERMISSION)) {
20902
20903                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20904                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20905
20906                int newFlagSet = 0;
20907                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20908                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20909                }
20910                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20911                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20912                }
20913                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20914                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20915                }
20916                if (DEBUG_BACKUP) {
20917                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
20918                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20919                }
20920                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20921                if (ps != null) {
20922                    // Already installed so we apply the grant immediately
20923                    if (DEBUG_BACKUP) {
20924                        Slog.v(TAG, "        + already installed; applying");
20925                    }
20926                    PermissionsState perms = ps.getPermissionsState();
20927                    BasePermission bp = mSettings.mPermissions.get(permName);
20928                    if (bp != null) {
20929                        if (isGranted) {
20930                            perms.grantRuntimePermission(bp, userId);
20931                        }
20932                        if (newFlagSet != 0) {
20933                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20934                        }
20935                    }
20936                } else {
20937                    // Need to wait for post-restore install to apply the grant
20938                    if (DEBUG_BACKUP) {
20939                        Slog.v(TAG, "        - not yet installed; saving for later");
20940                    }
20941                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20942                            isGranted, newFlagSet, userId);
20943                }
20944            } else {
20945                PackageManagerService.reportSettingsProblem(Log.WARN,
20946                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20947                XmlUtils.skipCurrentTag(parser);
20948            }
20949        }
20950
20951        scheduleWriteSettingsLocked();
20952        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20953    }
20954
20955    @Override
20956    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20957            int sourceUserId, int targetUserId, int flags) {
20958        mContext.enforceCallingOrSelfPermission(
20959                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20960        int callingUid = Binder.getCallingUid();
20961        enforceOwnerRights(ownerPackage, callingUid);
20962        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20963        if (intentFilter.countActions() == 0) {
20964            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20965            return;
20966        }
20967        synchronized (mPackages) {
20968            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20969                    ownerPackage, targetUserId, flags);
20970            CrossProfileIntentResolver resolver =
20971                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20972            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20973            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20974            if (existing != null) {
20975                int size = existing.size();
20976                for (int i = 0; i < size; i++) {
20977                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20978                        return;
20979                    }
20980                }
20981            }
20982            resolver.addFilter(newFilter);
20983            scheduleWritePackageRestrictionsLocked(sourceUserId);
20984        }
20985    }
20986
20987    @Override
20988    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20989        mContext.enforceCallingOrSelfPermission(
20990                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20991        final int callingUid = Binder.getCallingUid();
20992        enforceOwnerRights(ownerPackage, callingUid);
20993        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20994        synchronized (mPackages) {
20995            CrossProfileIntentResolver resolver =
20996                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20997            ArraySet<CrossProfileIntentFilter> set =
20998                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20999            for (CrossProfileIntentFilter filter : set) {
21000                if (filter.getOwnerPackage().equals(ownerPackage)) {
21001                    resolver.removeFilter(filter);
21002                }
21003            }
21004            scheduleWritePackageRestrictionsLocked(sourceUserId);
21005        }
21006    }
21007
21008    // Enforcing that callingUid is owning pkg on userId
21009    private void enforceOwnerRights(String pkg, int callingUid) {
21010        // The system owns everything.
21011        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
21012            return;
21013        }
21014        final int callingUserId = UserHandle.getUserId(callingUid);
21015        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
21016        if (pi == null) {
21017            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
21018                    + callingUserId);
21019        }
21020        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
21021            throw new SecurityException("Calling uid " + callingUid
21022                    + " does not own package " + pkg);
21023        }
21024    }
21025
21026    @Override
21027    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
21028        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21029            return null;
21030        }
21031        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
21032    }
21033
21034    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
21035        UserManagerService ums = UserManagerService.getInstance();
21036        if (ums != null) {
21037            final UserInfo parent = ums.getProfileParent(userId);
21038            final int launcherUid = (parent != null) ? parent.id : userId;
21039            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
21040            if (launcherComponent != null) {
21041                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
21042                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
21043                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
21044                        .setPackage(launcherComponent.getPackageName());
21045                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
21046            }
21047        }
21048    }
21049
21050    /**
21051     * Report the 'Home' activity which is currently set as "always use this one". If non is set
21052     * then reports the most likely home activity or null if there are more than one.
21053     */
21054    private ComponentName getDefaultHomeActivity(int userId) {
21055        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
21056        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
21057        if (cn != null) {
21058            return cn;
21059        }
21060
21061        // Find the launcher with the highest priority and return that component if there are no
21062        // other home activity with the same priority.
21063        int lastPriority = Integer.MIN_VALUE;
21064        ComponentName lastComponent = null;
21065        final int size = allHomeCandidates.size();
21066        for (int i = 0; i < size; i++) {
21067            final ResolveInfo ri = allHomeCandidates.get(i);
21068            if (ri.priority > lastPriority) {
21069                lastComponent = ri.activityInfo.getComponentName();
21070                lastPriority = ri.priority;
21071            } else if (ri.priority == lastPriority) {
21072                // Two components found with same priority.
21073                lastComponent = null;
21074            }
21075        }
21076        return lastComponent;
21077    }
21078
21079    private Intent getHomeIntent() {
21080        Intent intent = new Intent(Intent.ACTION_MAIN);
21081        intent.addCategory(Intent.CATEGORY_HOME);
21082        intent.addCategory(Intent.CATEGORY_DEFAULT);
21083        return intent;
21084    }
21085
21086    private IntentFilter getHomeFilter() {
21087        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
21088        filter.addCategory(Intent.CATEGORY_HOME);
21089        filter.addCategory(Intent.CATEGORY_DEFAULT);
21090        return filter;
21091    }
21092
21093    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
21094            int userId) {
21095        Intent intent  = getHomeIntent();
21096        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
21097                PackageManager.GET_META_DATA, userId);
21098        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
21099                true, false, false, userId);
21100
21101        allHomeCandidates.clear();
21102        if (list != null) {
21103            for (ResolveInfo ri : list) {
21104                allHomeCandidates.add(ri);
21105            }
21106        }
21107        return (preferred == null || preferred.activityInfo == null)
21108                ? null
21109                : new ComponentName(preferred.activityInfo.packageName,
21110                        preferred.activityInfo.name);
21111    }
21112
21113    @Override
21114    public void setHomeActivity(ComponentName comp, int userId) {
21115        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21116            return;
21117        }
21118        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21119        getHomeActivitiesAsUser(homeActivities, userId);
21120
21121        boolean found = false;
21122
21123        final int size = homeActivities.size();
21124        final ComponentName[] set = new ComponentName[size];
21125        for (int i = 0; i < size; i++) {
21126            final ResolveInfo candidate = homeActivities.get(i);
21127            final ActivityInfo info = candidate.activityInfo;
21128            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21129            set[i] = activityName;
21130            if (!found && activityName.equals(comp)) {
21131                found = true;
21132            }
21133        }
21134        if (!found) {
21135            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21136                    + userId);
21137        }
21138        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21139                set, comp, userId);
21140    }
21141
21142    private @Nullable String getSetupWizardPackageName() {
21143        final Intent intent = new Intent(Intent.ACTION_MAIN);
21144        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21145
21146        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21147                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21148                        | MATCH_DISABLED_COMPONENTS,
21149                UserHandle.myUserId());
21150        if (matches.size() == 1) {
21151            return matches.get(0).getComponentInfo().packageName;
21152        } else {
21153            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21154                    + ": matches=" + matches);
21155            return null;
21156        }
21157    }
21158
21159    private @Nullable String getStorageManagerPackageName() {
21160        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21161
21162        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21163                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21164                        | MATCH_DISABLED_COMPONENTS,
21165                UserHandle.myUserId());
21166        if (matches.size() == 1) {
21167            return matches.get(0).getComponentInfo().packageName;
21168        } else {
21169            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21170                    + matches.size() + ": matches=" + matches);
21171            return null;
21172        }
21173    }
21174
21175    @Override
21176    public void setApplicationEnabledSetting(String appPackageName,
21177            int newState, int flags, int userId, String callingPackage) {
21178        if (!sUserManager.exists(userId)) return;
21179        if (callingPackage == null) {
21180            callingPackage = Integer.toString(Binder.getCallingUid());
21181        }
21182        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21183    }
21184
21185    @Override
21186    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21187        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21188        synchronized (mPackages) {
21189            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21190            if (pkgSetting != null) {
21191                pkgSetting.setUpdateAvailable(updateAvailable);
21192            }
21193        }
21194    }
21195
21196    @Override
21197    public void setComponentEnabledSetting(ComponentName componentName,
21198            int newState, int flags, int userId) {
21199        if (!sUserManager.exists(userId)) return;
21200        setEnabledSetting(componentName.getPackageName(),
21201                componentName.getClassName(), newState, flags, userId, null);
21202    }
21203
21204    private void setEnabledSetting(final String packageName, String className, int newState,
21205            final int flags, int userId, String callingPackage) {
21206        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21207              || newState == COMPONENT_ENABLED_STATE_ENABLED
21208              || newState == COMPONENT_ENABLED_STATE_DISABLED
21209              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21210              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21211            throw new IllegalArgumentException("Invalid new component state: "
21212                    + newState);
21213        }
21214        PackageSetting pkgSetting;
21215        final int callingUid = Binder.getCallingUid();
21216        final int permission;
21217        if (callingUid == Process.SYSTEM_UID) {
21218            permission = PackageManager.PERMISSION_GRANTED;
21219        } else {
21220            permission = mContext.checkCallingOrSelfPermission(
21221                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21222        }
21223        enforceCrossUserPermission(callingUid, userId,
21224                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21225        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21226        boolean sendNow = false;
21227        boolean isApp = (className == null);
21228        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21229        String componentName = isApp ? packageName : className;
21230        int packageUid = -1;
21231        ArrayList<String> components;
21232
21233        // reader
21234        synchronized (mPackages) {
21235            pkgSetting = mSettings.mPackages.get(packageName);
21236            if (pkgSetting == null) {
21237                if (!isCallerInstantApp) {
21238                    if (className == null) {
21239                        throw new IllegalArgumentException("Unknown package: " + packageName);
21240                    }
21241                    throw new IllegalArgumentException(
21242                            "Unknown component: " + packageName + "/" + className);
21243                } else {
21244                    // throw SecurityException to prevent leaking package information
21245                    throw new SecurityException(
21246                            "Attempt to change component state; "
21247                            + "pid=" + Binder.getCallingPid()
21248                            + ", uid=" + callingUid
21249                            + (className == null
21250                                    ? ", package=" + packageName
21251                                    : ", component=" + packageName + "/" + className));
21252                }
21253            }
21254        }
21255
21256        // Limit who can change which apps
21257        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21258            // Don't allow apps that don't have permission to modify other apps
21259            if (!allowedByPermission
21260                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21261                throw new SecurityException(
21262                        "Attempt to change component state; "
21263                        + "pid=" + Binder.getCallingPid()
21264                        + ", uid=" + callingUid
21265                        + (className == null
21266                                ? ", package=" + packageName
21267                                : ", component=" + packageName + "/" + className));
21268            }
21269            // Don't allow changing protected packages.
21270            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21271                throw new SecurityException("Cannot disable a protected package: " + packageName);
21272            }
21273        }
21274
21275        synchronized (mPackages) {
21276            if (callingUid == Process.SHELL_UID
21277                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21278                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21279                // unless it is a test package.
21280                int oldState = pkgSetting.getEnabled(userId);
21281                if (className == null
21282                    &&
21283                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21284                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21285                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21286                    &&
21287                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21288                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21289                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21290                    // ok
21291                } else {
21292                    throw new SecurityException(
21293                            "Shell cannot change component state for " + packageName + "/"
21294                            + className + " to " + newState);
21295                }
21296            }
21297            if (className == null) {
21298                // We're dealing with an application/package level state change
21299                if (pkgSetting.getEnabled(userId) == newState) {
21300                    // Nothing to do
21301                    return;
21302                }
21303                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21304                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21305                    // Don't care about who enables an app.
21306                    callingPackage = null;
21307                }
21308                pkgSetting.setEnabled(newState, userId, callingPackage);
21309                // pkgSetting.pkg.mSetEnabled = newState;
21310            } else {
21311                // We're dealing with a component level state change
21312                // First, verify that this is a valid class name.
21313                PackageParser.Package pkg = pkgSetting.pkg;
21314                if (pkg == null || !pkg.hasComponentClassName(className)) {
21315                    if (pkg != null &&
21316                            pkg.applicationInfo.targetSdkVersion >=
21317                                    Build.VERSION_CODES.JELLY_BEAN) {
21318                        throw new IllegalArgumentException("Component class " + className
21319                                + " does not exist in " + packageName);
21320                    } else {
21321                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21322                                + className + " does not exist in " + packageName);
21323                    }
21324                }
21325                switch (newState) {
21326                case COMPONENT_ENABLED_STATE_ENABLED:
21327                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21328                        return;
21329                    }
21330                    break;
21331                case COMPONENT_ENABLED_STATE_DISABLED:
21332                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21333                        return;
21334                    }
21335                    break;
21336                case COMPONENT_ENABLED_STATE_DEFAULT:
21337                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21338                        return;
21339                    }
21340                    break;
21341                default:
21342                    Slog.e(TAG, "Invalid new component state: " + newState);
21343                    return;
21344                }
21345            }
21346            scheduleWritePackageRestrictionsLocked(userId);
21347            updateSequenceNumberLP(pkgSetting, new int[] { userId });
21348            final long callingId = Binder.clearCallingIdentity();
21349            try {
21350                updateInstantAppInstallerLocked(packageName);
21351            } finally {
21352                Binder.restoreCallingIdentity(callingId);
21353            }
21354            components = mPendingBroadcasts.get(userId, packageName);
21355            final boolean newPackage = components == null;
21356            if (newPackage) {
21357                components = new ArrayList<String>();
21358            }
21359            if (!components.contains(componentName)) {
21360                components.add(componentName);
21361            }
21362            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21363                sendNow = true;
21364                // Purge entry from pending broadcast list if another one exists already
21365                // since we are sending one right away.
21366                mPendingBroadcasts.remove(userId, packageName);
21367            } else {
21368                if (newPackage) {
21369                    mPendingBroadcasts.put(userId, packageName, components);
21370                }
21371                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21372                    // Schedule a message
21373                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21374                }
21375            }
21376        }
21377
21378        long callingId = Binder.clearCallingIdentity();
21379        try {
21380            if (sendNow) {
21381                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21382                sendPackageChangedBroadcast(packageName,
21383                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21384            }
21385        } finally {
21386            Binder.restoreCallingIdentity(callingId);
21387        }
21388    }
21389
21390    @Override
21391    public void flushPackageRestrictionsAsUser(int userId) {
21392        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21393            return;
21394        }
21395        if (!sUserManager.exists(userId)) {
21396            return;
21397        }
21398        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21399                false /* checkShell */, "flushPackageRestrictions");
21400        synchronized (mPackages) {
21401            mSettings.writePackageRestrictionsLPr(userId);
21402            mDirtyUsers.remove(userId);
21403            if (mDirtyUsers.isEmpty()) {
21404                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21405            }
21406        }
21407    }
21408
21409    private void sendPackageChangedBroadcast(String packageName,
21410            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21411        if (DEBUG_INSTALL)
21412            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21413                    + componentNames);
21414        Bundle extras = new Bundle(4);
21415        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21416        String nameList[] = new String[componentNames.size()];
21417        componentNames.toArray(nameList);
21418        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21419        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21420        extras.putInt(Intent.EXTRA_UID, packageUid);
21421        // If this is not reporting a change of the overall package, then only send it
21422        // to registered receivers.  We don't want to launch a swath of apps for every
21423        // little component state change.
21424        final int flags = !componentNames.contains(packageName)
21425                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21426        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21427                new int[] {UserHandle.getUserId(packageUid)});
21428    }
21429
21430    @Override
21431    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21432        if (!sUserManager.exists(userId)) return;
21433        final int callingUid = Binder.getCallingUid();
21434        if (getInstantAppPackageName(callingUid) != null) {
21435            return;
21436        }
21437        final int permission = mContext.checkCallingOrSelfPermission(
21438                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21439        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21440        enforceCrossUserPermission(callingUid, userId,
21441                true /* requireFullPermission */, true /* checkShell */, "stop package");
21442        // writer
21443        synchronized (mPackages) {
21444            final PackageSetting ps = mSettings.mPackages.get(packageName);
21445            if (!filterAppAccessLPr(ps, callingUid, userId)
21446                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21447                            allowedByPermission, callingUid, userId)) {
21448                scheduleWritePackageRestrictionsLocked(userId);
21449            }
21450        }
21451    }
21452
21453    @Override
21454    public String getInstallerPackageName(String packageName) {
21455        final int callingUid = Binder.getCallingUid();
21456        if (getInstantAppPackageName(callingUid) != null) {
21457            return null;
21458        }
21459        // reader
21460        synchronized (mPackages) {
21461            final PackageSetting ps = mSettings.mPackages.get(packageName);
21462            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21463                return null;
21464            }
21465            return mSettings.getInstallerPackageNameLPr(packageName);
21466        }
21467    }
21468
21469    public boolean isOrphaned(String packageName) {
21470        // reader
21471        synchronized (mPackages) {
21472            return mSettings.isOrphaned(packageName);
21473        }
21474    }
21475
21476    @Override
21477    public int getApplicationEnabledSetting(String packageName, int userId) {
21478        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21479        int callingUid = Binder.getCallingUid();
21480        enforceCrossUserPermission(callingUid, userId,
21481                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21482        // reader
21483        synchronized (mPackages) {
21484            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21485                return COMPONENT_ENABLED_STATE_DISABLED;
21486            }
21487            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21488        }
21489    }
21490
21491    @Override
21492    public int getComponentEnabledSetting(ComponentName component, int userId) {
21493        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21494        int callingUid = Binder.getCallingUid();
21495        enforceCrossUserPermission(callingUid, userId,
21496                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21497        synchronized (mPackages) {
21498            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21499                    component, TYPE_UNKNOWN, userId)) {
21500                return COMPONENT_ENABLED_STATE_DISABLED;
21501            }
21502            return mSettings.getComponentEnabledSettingLPr(component, userId);
21503        }
21504    }
21505
21506    @Override
21507    public void enterSafeMode() {
21508        enforceSystemOrRoot("Only the system can request entering safe mode");
21509
21510        if (!mSystemReady) {
21511            mSafeMode = true;
21512        }
21513    }
21514
21515    @Override
21516    public void systemReady() {
21517        enforceSystemOrRoot("Only the system can claim the system is ready");
21518
21519        mSystemReady = true;
21520        final ContentResolver resolver = mContext.getContentResolver();
21521        ContentObserver co = new ContentObserver(mHandler) {
21522            @Override
21523            public void onChange(boolean selfChange) {
21524                mEphemeralAppsDisabled =
21525                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21526                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21527            }
21528        };
21529        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21530                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21531                false, co, UserHandle.USER_SYSTEM);
21532        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21533                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21534        co.onChange(true);
21535
21536        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21537        // disabled after already being started.
21538        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21539                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21540
21541        // Read the compatibilty setting when the system is ready.
21542        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21543                mContext.getContentResolver(),
21544                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21545        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21546        if (DEBUG_SETTINGS) {
21547            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21548        }
21549
21550        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21551
21552        synchronized (mPackages) {
21553            // Verify that all of the preferred activity components actually
21554            // exist.  It is possible for applications to be updated and at
21555            // that point remove a previously declared activity component that
21556            // had been set as a preferred activity.  We try to clean this up
21557            // the next time we encounter that preferred activity, but it is
21558            // possible for the user flow to never be able to return to that
21559            // situation so here we do a sanity check to make sure we haven't
21560            // left any junk around.
21561            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21562            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21563                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21564                removed.clear();
21565                for (PreferredActivity pa : pir.filterSet()) {
21566                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21567                        removed.add(pa);
21568                    }
21569                }
21570                if (removed.size() > 0) {
21571                    for (int r=0; r<removed.size(); r++) {
21572                        PreferredActivity pa = removed.get(r);
21573                        Slog.w(TAG, "Removing dangling preferred activity: "
21574                                + pa.mPref.mComponent);
21575                        pir.removeFilter(pa);
21576                    }
21577                    mSettings.writePackageRestrictionsLPr(
21578                            mSettings.mPreferredActivities.keyAt(i));
21579                }
21580            }
21581
21582            for (int userId : UserManagerService.getInstance().getUserIds()) {
21583                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21584                    grantPermissionsUserIds = ArrayUtils.appendInt(
21585                            grantPermissionsUserIds, userId);
21586                }
21587            }
21588        }
21589        sUserManager.systemReady();
21590
21591        // If we upgraded grant all default permissions before kicking off.
21592        for (int userId : grantPermissionsUserIds) {
21593            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21594        }
21595
21596        // If we did not grant default permissions, we preload from this the
21597        // default permission exceptions lazily to ensure we don't hit the
21598        // disk on a new user creation.
21599        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21600            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21601        }
21602
21603        // Kick off any messages waiting for system ready
21604        if (mPostSystemReadyMessages != null) {
21605            for (Message msg : mPostSystemReadyMessages) {
21606                msg.sendToTarget();
21607            }
21608            mPostSystemReadyMessages = null;
21609        }
21610
21611        // Watch for external volumes that come and go over time
21612        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21613        storage.registerListener(mStorageListener);
21614
21615        mInstallerService.systemReady();
21616        mPackageDexOptimizer.systemReady();
21617
21618        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21619                StorageManagerInternal.class);
21620        StorageManagerInternal.addExternalStoragePolicy(
21621                new StorageManagerInternal.ExternalStorageMountPolicy() {
21622            @Override
21623            public int getMountMode(int uid, String packageName) {
21624                if (Process.isIsolated(uid)) {
21625                    return Zygote.MOUNT_EXTERNAL_NONE;
21626                }
21627                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21628                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21629                }
21630                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21631                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21632                }
21633                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21634                    return Zygote.MOUNT_EXTERNAL_READ;
21635                }
21636                return Zygote.MOUNT_EXTERNAL_WRITE;
21637            }
21638
21639            @Override
21640            public boolean hasExternalStorage(int uid, String packageName) {
21641                return true;
21642            }
21643        });
21644
21645        // Now that we're mostly running, clean up stale users and apps
21646        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21647        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21648
21649        if (mPrivappPermissionsViolations != null) {
21650            Slog.wtf(TAG,"Signature|privileged permissions not in "
21651                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21652            mPrivappPermissionsViolations = null;
21653        }
21654    }
21655
21656    public void waitForAppDataPrepared() {
21657        if (mPrepareAppDataFuture == null) {
21658            return;
21659        }
21660        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21661        mPrepareAppDataFuture = null;
21662    }
21663
21664    @Override
21665    public boolean isSafeMode() {
21666        // allow instant applications
21667        return mSafeMode;
21668    }
21669
21670    @Override
21671    public boolean hasSystemUidErrors() {
21672        // allow instant applications
21673        return mHasSystemUidErrors;
21674    }
21675
21676    static String arrayToString(int[] array) {
21677        StringBuffer buf = new StringBuffer(128);
21678        buf.append('[');
21679        if (array != null) {
21680            for (int i=0; i<array.length; i++) {
21681                if (i > 0) buf.append(", ");
21682                buf.append(array[i]);
21683            }
21684        }
21685        buf.append(']');
21686        return buf.toString();
21687    }
21688
21689    static class DumpState {
21690        public static final int DUMP_LIBS = 1 << 0;
21691        public static final int DUMP_FEATURES = 1 << 1;
21692        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
21693        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
21694        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
21695        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
21696        public static final int DUMP_PERMISSIONS = 1 << 6;
21697        public static final int DUMP_PACKAGES = 1 << 7;
21698        public static final int DUMP_SHARED_USERS = 1 << 8;
21699        public static final int DUMP_MESSAGES = 1 << 9;
21700        public static final int DUMP_PROVIDERS = 1 << 10;
21701        public static final int DUMP_VERIFIERS = 1 << 11;
21702        public static final int DUMP_PREFERRED = 1 << 12;
21703        public static final int DUMP_PREFERRED_XML = 1 << 13;
21704        public static final int DUMP_KEYSETS = 1 << 14;
21705        public static final int DUMP_VERSION = 1 << 15;
21706        public static final int DUMP_INSTALLS = 1 << 16;
21707        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
21708        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
21709        public static final int DUMP_FROZEN = 1 << 19;
21710        public static final int DUMP_DEXOPT = 1 << 20;
21711        public static final int DUMP_COMPILER_STATS = 1 << 21;
21712        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
21713        public static final int DUMP_CHANGES = 1 << 23;
21714
21715        public static final int OPTION_SHOW_FILTERS = 1 << 0;
21716
21717        private int mTypes;
21718
21719        private int mOptions;
21720
21721        private boolean mTitlePrinted;
21722
21723        private SharedUserSetting mSharedUser;
21724
21725        public boolean isDumping(int type) {
21726            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
21727                return true;
21728            }
21729
21730            return (mTypes & type) != 0;
21731        }
21732
21733        public void setDump(int type) {
21734            mTypes |= type;
21735        }
21736
21737        public boolean isOptionEnabled(int option) {
21738            return (mOptions & option) != 0;
21739        }
21740
21741        public void setOptionEnabled(int option) {
21742            mOptions |= option;
21743        }
21744
21745        public boolean onTitlePrinted() {
21746            final boolean printed = mTitlePrinted;
21747            mTitlePrinted = true;
21748            return printed;
21749        }
21750
21751        public boolean getTitlePrinted() {
21752            return mTitlePrinted;
21753        }
21754
21755        public void setTitlePrinted(boolean enabled) {
21756            mTitlePrinted = enabled;
21757        }
21758
21759        public SharedUserSetting getSharedUser() {
21760            return mSharedUser;
21761        }
21762
21763        public void setSharedUser(SharedUserSetting user) {
21764            mSharedUser = user;
21765        }
21766    }
21767
21768    @Override
21769    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21770            FileDescriptor err, String[] args, ShellCallback callback,
21771            ResultReceiver resultReceiver) {
21772        (new PackageManagerShellCommand(this)).exec(
21773                this, in, out, err, args, callback, resultReceiver);
21774    }
21775
21776    @Override
21777    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21778        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21779
21780        DumpState dumpState = new DumpState();
21781        boolean fullPreferred = false;
21782        boolean checkin = false;
21783
21784        String packageName = null;
21785        ArraySet<String> permissionNames = null;
21786
21787        int opti = 0;
21788        while (opti < args.length) {
21789            String opt = args[opti];
21790            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21791                break;
21792            }
21793            opti++;
21794
21795            if ("-a".equals(opt)) {
21796                // Right now we only know how to print all.
21797            } else if ("-h".equals(opt)) {
21798                pw.println("Package manager dump options:");
21799                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21800                pw.println("    --checkin: dump for a checkin");
21801                pw.println("    -f: print details of intent filters");
21802                pw.println("    -h: print this help");
21803                pw.println("  cmd may be one of:");
21804                pw.println("    l[ibraries]: list known shared libraries");
21805                pw.println("    f[eatures]: list device features");
21806                pw.println("    k[eysets]: print known keysets");
21807                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21808                pw.println("    perm[issions]: dump permissions");
21809                pw.println("    permission [name ...]: dump declaration and use of given permission");
21810                pw.println("    pref[erred]: print preferred package settings");
21811                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21812                pw.println("    prov[iders]: dump content providers");
21813                pw.println("    p[ackages]: dump installed packages");
21814                pw.println("    s[hared-users]: dump shared user IDs");
21815                pw.println("    m[essages]: print collected runtime messages");
21816                pw.println("    v[erifiers]: print package verifier info");
21817                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21818                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21819                pw.println("    version: print database version info");
21820                pw.println("    write: write current settings now");
21821                pw.println("    installs: details about install sessions");
21822                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21823                pw.println("    dexopt: dump dexopt state");
21824                pw.println("    compiler-stats: dump compiler statistics");
21825                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21826                pw.println("    <package.name>: info about given package");
21827                return;
21828            } else if ("--checkin".equals(opt)) {
21829                checkin = true;
21830            } else if ("-f".equals(opt)) {
21831                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21832            } else if ("--proto".equals(opt)) {
21833                dumpProto(fd);
21834                return;
21835            } else {
21836                pw.println("Unknown argument: " + opt + "; use -h for help");
21837            }
21838        }
21839
21840        // Is the caller requesting to dump a particular piece of data?
21841        if (opti < args.length) {
21842            String cmd = args[opti];
21843            opti++;
21844            // Is this a package name?
21845            if ("android".equals(cmd) || cmd.contains(".")) {
21846                packageName = cmd;
21847                // When dumping a single package, we always dump all of its
21848                // filter information since the amount of data will be reasonable.
21849                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21850            } else if ("check-permission".equals(cmd)) {
21851                if (opti >= args.length) {
21852                    pw.println("Error: check-permission missing permission argument");
21853                    return;
21854                }
21855                String perm = args[opti];
21856                opti++;
21857                if (opti >= args.length) {
21858                    pw.println("Error: check-permission missing package argument");
21859                    return;
21860                }
21861
21862                String pkg = args[opti];
21863                opti++;
21864                int user = UserHandle.getUserId(Binder.getCallingUid());
21865                if (opti < args.length) {
21866                    try {
21867                        user = Integer.parseInt(args[opti]);
21868                    } catch (NumberFormatException e) {
21869                        pw.println("Error: check-permission user argument is not a number: "
21870                                + args[opti]);
21871                        return;
21872                    }
21873                }
21874
21875                // Normalize package name to handle renamed packages and static libs
21876                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21877
21878                pw.println(checkPermission(perm, pkg, user));
21879                return;
21880            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21881                dumpState.setDump(DumpState.DUMP_LIBS);
21882            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21883                dumpState.setDump(DumpState.DUMP_FEATURES);
21884            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21885                if (opti >= args.length) {
21886                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21887                            | DumpState.DUMP_SERVICE_RESOLVERS
21888                            | DumpState.DUMP_RECEIVER_RESOLVERS
21889                            | DumpState.DUMP_CONTENT_RESOLVERS);
21890                } else {
21891                    while (opti < args.length) {
21892                        String name = args[opti];
21893                        if ("a".equals(name) || "activity".equals(name)) {
21894                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21895                        } else if ("s".equals(name) || "service".equals(name)) {
21896                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21897                        } else if ("r".equals(name) || "receiver".equals(name)) {
21898                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21899                        } else if ("c".equals(name) || "content".equals(name)) {
21900                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21901                        } else {
21902                            pw.println("Error: unknown resolver table type: " + name);
21903                            return;
21904                        }
21905                        opti++;
21906                    }
21907                }
21908            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21909                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21910            } else if ("permission".equals(cmd)) {
21911                if (opti >= args.length) {
21912                    pw.println("Error: permission requires permission name");
21913                    return;
21914                }
21915                permissionNames = new ArraySet<>();
21916                while (opti < args.length) {
21917                    permissionNames.add(args[opti]);
21918                    opti++;
21919                }
21920                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21921                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21922            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21923                dumpState.setDump(DumpState.DUMP_PREFERRED);
21924            } else if ("preferred-xml".equals(cmd)) {
21925                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21926                if (opti < args.length && "--full".equals(args[opti])) {
21927                    fullPreferred = true;
21928                    opti++;
21929                }
21930            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21931                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21932            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21933                dumpState.setDump(DumpState.DUMP_PACKAGES);
21934            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21935                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21936            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21937                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21938            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21939                dumpState.setDump(DumpState.DUMP_MESSAGES);
21940            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21941                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21942            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21943                    || "intent-filter-verifiers".equals(cmd)) {
21944                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21945            } else if ("version".equals(cmd)) {
21946                dumpState.setDump(DumpState.DUMP_VERSION);
21947            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21948                dumpState.setDump(DumpState.DUMP_KEYSETS);
21949            } else if ("installs".equals(cmd)) {
21950                dumpState.setDump(DumpState.DUMP_INSTALLS);
21951            } else if ("frozen".equals(cmd)) {
21952                dumpState.setDump(DumpState.DUMP_FROZEN);
21953            } else if ("dexopt".equals(cmd)) {
21954                dumpState.setDump(DumpState.DUMP_DEXOPT);
21955            } else if ("compiler-stats".equals(cmd)) {
21956                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21957            } else if ("enabled-overlays".equals(cmd)) {
21958                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
21959            } else if ("changes".equals(cmd)) {
21960                dumpState.setDump(DumpState.DUMP_CHANGES);
21961            } else if ("write".equals(cmd)) {
21962                synchronized (mPackages) {
21963                    mSettings.writeLPr();
21964                    pw.println("Settings written.");
21965                    return;
21966                }
21967            }
21968        }
21969
21970        if (checkin) {
21971            pw.println("vers,1");
21972        }
21973
21974        // reader
21975        synchronized (mPackages) {
21976            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21977                if (!checkin) {
21978                    if (dumpState.onTitlePrinted())
21979                        pw.println();
21980                    pw.println("Database versions:");
21981                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21982                }
21983            }
21984
21985            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21986                if (!checkin) {
21987                    if (dumpState.onTitlePrinted())
21988                        pw.println();
21989                    pw.println("Verifiers:");
21990                    pw.print("  Required: ");
21991                    pw.print(mRequiredVerifierPackage);
21992                    pw.print(" (uid=");
21993                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21994                            UserHandle.USER_SYSTEM));
21995                    pw.println(")");
21996                } else if (mRequiredVerifierPackage != null) {
21997                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21998                    pw.print(",");
21999                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
22000                            UserHandle.USER_SYSTEM));
22001                }
22002            }
22003
22004            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
22005                    packageName == null) {
22006                if (mIntentFilterVerifierComponent != null) {
22007                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22008                    if (!checkin) {
22009                        if (dumpState.onTitlePrinted())
22010                            pw.println();
22011                        pw.println("Intent Filter Verifier:");
22012                        pw.print("  Using: ");
22013                        pw.print(verifierPackageName);
22014                        pw.print(" (uid=");
22015                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22016                                UserHandle.USER_SYSTEM));
22017                        pw.println(")");
22018                    } else if (verifierPackageName != null) {
22019                        pw.print("ifv,"); pw.print(verifierPackageName);
22020                        pw.print(",");
22021                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22022                                UserHandle.USER_SYSTEM));
22023                    }
22024                } else {
22025                    pw.println();
22026                    pw.println("No Intent Filter Verifier available!");
22027                }
22028            }
22029
22030            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22031                boolean printedHeader = false;
22032                final Iterator<String> it = mSharedLibraries.keySet().iterator();
22033                while (it.hasNext()) {
22034                    String libName = it.next();
22035                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22036                    if (versionedLib == null) {
22037                        continue;
22038                    }
22039                    final int versionCount = versionedLib.size();
22040                    for (int i = 0; i < versionCount; i++) {
22041                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
22042                        if (!checkin) {
22043                            if (!printedHeader) {
22044                                if (dumpState.onTitlePrinted())
22045                                    pw.println();
22046                                pw.println("Libraries:");
22047                                printedHeader = true;
22048                            }
22049                            pw.print("  ");
22050                        } else {
22051                            pw.print("lib,");
22052                        }
22053                        pw.print(libEntry.info.getName());
22054                        if (libEntry.info.isStatic()) {
22055                            pw.print(" version=" + libEntry.info.getVersion());
22056                        }
22057                        if (!checkin) {
22058                            pw.print(" -> ");
22059                        }
22060                        if (libEntry.path != null) {
22061                            pw.print(" (jar) ");
22062                            pw.print(libEntry.path);
22063                        } else {
22064                            pw.print(" (apk) ");
22065                            pw.print(libEntry.apk);
22066                        }
22067                        pw.println();
22068                    }
22069                }
22070            }
22071
22072            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22073                if (dumpState.onTitlePrinted())
22074                    pw.println();
22075                if (!checkin) {
22076                    pw.println("Features:");
22077                }
22078
22079                synchronized (mAvailableFeatures) {
22080                    for (FeatureInfo feat : mAvailableFeatures.values()) {
22081                        if (checkin) {
22082                            pw.print("feat,");
22083                            pw.print(feat.name);
22084                            pw.print(",");
22085                            pw.println(feat.version);
22086                        } else {
22087                            pw.print("  ");
22088                            pw.print(feat.name);
22089                            if (feat.version > 0) {
22090                                pw.print(" version=");
22091                                pw.print(feat.version);
22092                            }
22093                            pw.println();
22094                        }
22095                    }
22096                }
22097            }
22098
22099            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22100                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
22101                        : "Activity Resolver Table:", "  ", packageName,
22102                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22103                    dumpState.setTitlePrinted(true);
22104                }
22105            }
22106            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22107                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
22108                        : "Receiver Resolver Table:", "  ", packageName,
22109                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22110                    dumpState.setTitlePrinted(true);
22111                }
22112            }
22113            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22114                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
22115                        : "Service Resolver Table:", "  ", packageName,
22116                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22117                    dumpState.setTitlePrinted(true);
22118                }
22119            }
22120            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22121                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22122                        : "Provider Resolver Table:", "  ", packageName,
22123                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22124                    dumpState.setTitlePrinted(true);
22125                }
22126            }
22127
22128            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22129                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22130                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22131                    int user = mSettings.mPreferredActivities.keyAt(i);
22132                    if (pir.dump(pw,
22133                            dumpState.getTitlePrinted()
22134                                ? "\nPreferred Activities User " + user + ":"
22135                                : "Preferred Activities User " + user + ":", "  ",
22136                            packageName, true, false)) {
22137                        dumpState.setTitlePrinted(true);
22138                    }
22139                }
22140            }
22141
22142            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22143                pw.flush();
22144                FileOutputStream fout = new FileOutputStream(fd);
22145                BufferedOutputStream str = new BufferedOutputStream(fout);
22146                XmlSerializer serializer = new FastXmlSerializer();
22147                try {
22148                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22149                    serializer.startDocument(null, true);
22150                    serializer.setFeature(
22151                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22152                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22153                    serializer.endDocument();
22154                    serializer.flush();
22155                } catch (IllegalArgumentException e) {
22156                    pw.println("Failed writing: " + e);
22157                } catch (IllegalStateException e) {
22158                    pw.println("Failed writing: " + e);
22159                } catch (IOException e) {
22160                    pw.println("Failed writing: " + e);
22161                }
22162            }
22163
22164            if (!checkin
22165                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22166                    && packageName == null) {
22167                pw.println();
22168                int count = mSettings.mPackages.size();
22169                if (count == 0) {
22170                    pw.println("No applications!");
22171                    pw.println();
22172                } else {
22173                    final String prefix = "  ";
22174                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22175                    if (allPackageSettings.size() == 0) {
22176                        pw.println("No domain preferred apps!");
22177                        pw.println();
22178                    } else {
22179                        pw.println("App verification status:");
22180                        pw.println();
22181                        count = 0;
22182                        for (PackageSetting ps : allPackageSettings) {
22183                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22184                            if (ivi == null || ivi.getPackageName() == null) continue;
22185                            pw.println(prefix + "Package: " + ivi.getPackageName());
22186                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22187                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22188                            pw.println();
22189                            count++;
22190                        }
22191                        if (count == 0) {
22192                            pw.println(prefix + "No app verification established.");
22193                            pw.println();
22194                        }
22195                        for (int userId : sUserManager.getUserIds()) {
22196                            pw.println("App linkages for user " + userId + ":");
22197                            pw.println();
22198                            count = 0;
22199                            for (PackageSetting ps : allPackageSettings) {
22200                                final long status = ps.getDomainVerificationStatusForUser(userId);
22201                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22202                                        && !DEBUG_DOMAIN_VERIFICATION) {
22203                                    continue;
22204                                }
22205                                pw.println(prefix + "Package: " + ps.name);
22206                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22207                                String statusStr = IntentFilterVerificationInfo.
22208                                        getStatusStringFromValue(status);
22209                                pw.println(prefix + "Status:  " + statusStr);
22210                                pw.println();
22211                                count++;
22212                            }
22213                            if (count == 0) {
22214                                pw.println(prefix + "No configured app linkages.");
22215                                pw.println();
22216                            }
22217                        }
22218                    }
22219                }
22220            }
22221
22222            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22223                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22224                if (packageName == null && permissionNames == null) {
22225                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22226                        if (iperm == 0) {
22227                            if (dumpState.onTitlePrinted())
22228                                pw.println();
22229                            pw.println("AppOp Permissions:");
22230                        }
22231                        pw.print("  AppOp Permission ");
22232                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22233                        pw.println(":");
22234                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22235                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22236                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22237                        }
22238                    }
22239                }
22240            }
22241
22242            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22243                boolean printedSomething = false;
22244                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22245                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22246                        continue;
22247                    }
22248                    if (!printedSomething) {
22249                        if (dumpState.onTitlePrinted())
22250                            pw.println();
22251                        pw.println("Registered ContentProviders:");
22252                        printedSomething = true;
22253                    }
22254                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22255                    pw.print("    "); pw.println(p.toString());
22256                }
22257                printedSomething = false;
22258                for (Map.Entry<String, PackageParser.Provider> entry :
22259                        mProvidersByAuthority.entrySet()) {
22260                    PackageParser.Provider p = entry.getValue();
22261                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22262                        continue;
22263                    }
22264                    if (!printedSomething) {
22265                        if (dumpState.onTitlePrinted())
22266                            pw.println();
22267                        pw.println("ContentProvider Authorities:");
22268                        printedSomething = true;
22269                    }
22270                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22271                    pw.print("    "); pw.println(p.toString());
22272                    if (p.info != null && p.info.applicationInfo != null) {
22273                        final String appInfo = p.info.applicationInfo.toString();
22274                        pw.print("      applicationInfo="); pw.println(appInfo);
22275                    }
22276                }
22277            }
22278
22279            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22280                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22281            }
22282
22283            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22284                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22285            }
22286
22287            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22288                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22289            }
22290
22291            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22292                if (dumpState.onTitlePrinted()) pw.println();
22293                pw.println("Package Changes:");
22294                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22295                final int K = mChangedPackages.size();
22296                for (int i = 0; i < K; i++) {
22297                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22298                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22299                    final int N = changes.size();
22300                    if (N == 0) {
22301                        pw.print("    "); pw.println("No packages changed");
22302                    } else {
22303                        for (int j = 0; j < N; j++) {
22304                            final String pkgName = changes.valueAt(j);
22305                            final int sequenceNumber = changes.keyAt(j);
22306                            pw.print("    ");
22307                            pw.print("seq=");
22308                            pw.print(sequenceNumber);
22309                            pw.print(", package=");
22310                            pw.println(pkgName);
22311                        }
22312                    }
22313                }
22314            }
22315
22316            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22317                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22318            }
22319
22320            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22321                // XXX should handle packageName != null by dumping only install data that
22322                // the given package is involved with.
22323                if (dumpState.onTitlePrinted()) pw.println();
22324
22325                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22326                ipw.println();
22327                ipw.println("Frozen packages:");
22328                ipw.increaseIndent();
22329                if (mFrozenPackages.size() == 0) {
22330                    ipw.println("(none)");
22331                } else {
22332                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22333                        ipw.println(mFrozenPackages.valueAt(i));
22334                    }
22335                }
22336                ipw.decreaseIndent();
22337            }
22338
22339            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22340                if (dumpState.onTitlePrinted()) pw.println();
22341                dumpDexoptStateLPr(pw, packageName);
22342            }
22343
22344            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22345                if (dumpState.onTitlePrinted()) pw.println();
22346                dumpCompilerStatsLPr(pw, packageName);
22347            }
22348
22349            if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) {
22350                if (dumpState.onTitlePrinted()) pw.println();
22351                dumpEnabledOverlaysLPr(pw);
22352            }
22353
22354            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22355                if (dumpState.onTitlePrinted()) pw.println();
22356                mSettings.dumpReadMessagesLPr(pw, dumpState);
22357
22358                pw.println();
22359                pw.println("Package warning messages:");
22360                BufferedReader in = null;
22361                String line = null;
22362                try {
22363                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22364                    while ((line = in.readLine()) != null) {
22365                        if (line.contains("ignored: updated version")) continue;
22366                        pw.println(line);
22367                    }
22368                } catch (IOException ignored) {
22369                } finally {
22370                    IoUtils.closeQuietly(in);
22371                }
22372            }
22373
22374            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22375                BufferedReader in = null;
22376                String line = null;
22377                try {
22378                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22379                    while ((line = in.readLine()) != null) {
22380                        if (line.contains("ignored: updated version")) continue;
22381                        pw.print("msg,");
22382                        pw.println(line);
22383                    }
22384                } catch (IOException ignored) {
22385                } finally {
22386                    IoUtils.closeQuietly(in);
22387                }
22388            }
22389        }
22390
22391        // PackageInstaller should be called outside of mPackages lock
22392        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22393            // XXX should handle packageName != null by dumping only install data that
22394            // the given package is involved with.
22395            if (dumpState.onTitlePrinted()) pw.println();
22396            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22397        }
22398    }
22399
22400    private void dumpProto(FileDescriptor fd) {
22401        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22402
22403        synchronized (mPackages) {
22404            final long requiredVerifierPackageToken =
22405                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22406            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22407            proto.write(
22408                    PackageServiceDumpProto.PackageShortProto.UID,
22409                    getPackageUid(
22410                            mRequiredVerifierPackage,
22411                            MATCH_DEBUG_TRIAGED_MISSING,
22412                            UserHandle.USER_SYSTEM));
22413            proto.end(requiredVerifierPackageToken);
22414
22415            if (mIntentFilterVerifierComponent != null) {
22416                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22417                final long verifierPackageToken =
22418                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22419                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22420                proto.write(
22421                        PackageServiceDumpProto.PackageShortProto.UID,
22422                        getPackageUid(
22423                                verifierPackageName,
22424                                MATCH_DEBUG_TRIAGED_MISSING,
22425                                UserHandle.USER_SYSTEM));
22426                proto.end(verifierPackageToken);
22427            }
22428
22429            dumpSharedLibrariesProto(proto);
22430            dumpFeaturesProto(proto);
22431            mSettings.dumpPackagesProto(proto);
22432            mSettings.dumpSharedUsersProto(proto);
22433            dumpMessagesProto(proto);
22434        }
22435        proto.flush();
22436    }
22437
22438    private void dumpMessagesProto(ProtoOutputStream proto) {
22439        BufferedReader in = null;
22440        String line = null;
22441        try {
22442            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22443            while ((line = in.readLine()) != null) {
22444                if (line.contains("ignored: updated version")) continue;
22445                proto.write(PackageServiceDumpProto.MESSAGES, line);
22446            }
22447        } catch (IOException ignored) {
22448        } finally {
22449            IoUtils.closeQuietly(in);
22450        }
22451    }
22452
22453    private void dumpFeaturesProto(ProtoOutputStream proto) {
22454        synchronized (mAvailableFeatures) {
22455            final int count = mAvailableFeatures.size();
22456            for (int i = 0; i < count; i++) {
22457                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22458                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22459                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22460                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22461                proto.end(featureToken);
22462            }
22463        }
22464    }
22465
22466    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22467        final int count = mSharedLibraries.size();
22468        for (int i = 0; i < count; i++) {
22469            final String libName = mSharedLibraries.keyAt(i);
22470            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22471            if (versionedLib == null) {
22472                continue;
22473            }
22474            final int versionCount = versionedLib.size();
22475            for (int j = 0; j < versionCount; j++) {
22476                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22477                final long sharedLibraryToken =
22478                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22479                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22480                final boolean isJar = (libEntry.path != null);
22481                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22482                if (isJar) {
22483                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22484                } else {
22485                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22486                }
22487                proto.end(sharedLibraryToken);
22488            }
22489        }
22490    }
22491
22492    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22493        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22494        ipw.println();
22495        ipw.println("Dexopt state:");
22496        ipw.increaseIndent();
22497        Collection<PackageParser.Package> packages = null;
22498        if (packageName != null) {
22499            PackageParser.Package targetPackage = mPackages.get(packageName);
22500            if (targetPackage != null) {
22501                packages = Collections.singletonList(targetPackage);
22502            } else {
22503                ipw.println("Unable to find package: " + packageName);
22504                return;
22505            }
22506        } else {
22507            packages = mPackages.values();
22508        }
22509
22510        for (PackageParser.Package pkg : packages) {
22511            ipw.println("[" + pkg.packageName + "]");
22512            ipw.increaseIndent();
22513            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
22514            ipw.decreaseIndent();
22515        }
22516    }
22517
22518    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22519        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22520        ipw.println();
22521        ipw.println("Compiler stats:");
22522        ipw.increaseIndent();
22523        Collection<PackageParser.Package> packages = null;
22524        if (packageName != null) {
22525            PackageParser.Package targetPackage = mPackages.get(packageName);
22526            if (targetPackage != null) {
22527                packages = Collections.singletonList(targetPackage);
22528            } else {
22529                ipw.println("Unable to find package: " + packageName);
22530                return;
22531            }
22532        } else {
22533            packages = mPackages.values();
22534        }
22535
22536        for (PackageParser.Package pkg : packages) {
22537            ipw.println("[" + pkg.packageName + "]");
22538            ipw.increaseIndent();
22539
22540            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22541            if (stats == null) {
22542                ipw.println("(No recorded stats)");
22543            } else {
22544                stats.dump(ipw);
22545            }
22546            ipw.decreaseIndent();
22547        }
22548    }
22549
22550    private void dumpEnabledOverlaysLPr(PrintWriter pw) {
22551        pw.println("Enabled overlay paths:");
22552        final int N = mEnabledOverlayPaths.size();
22553        for (int i = 0; i < N; i++) {
22554            final int userId = mEnabledOverlayPaths.keyAt(i);
22555            pw.println(String.format("    User %d:", userId));
22556            final ArrayMap<String, ArrayList<String>> userSpecificOverlays =
22557                mEnabledOverlayPaths.valueAt(i);
22558            final int M = userSpecificOverlays.size();
22559            for (int j = 0; j < M; j++) {
22560                final String targetPackageName = userSpecificOverlays.keyAt(j);
22561                final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j);
22562                pw.println(String.format("        %s: %s", targetPackageName, overlayPackagePaths));
22563            }
22564        }
22565    }
22566
22567    private String dumpDomainString(String packageName) {
22568        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22569                .getList();
22570        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22571
22572        ArraySet<String> result = new ArraySet<>();
22573        if (iviList.size() > 0) {
22574            for (IntentFilterVerificationInfo ivi : iviList) {
22575                for (String host : ivi.getDomains()) {
22576                    result.add(host);
22577                }
22578            }
22579        }
22580        if (filters != null && filters.size() > 0) {
22581            for (IntentFilter filter : filters) {
22582                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22583                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22584                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22585                    result.addAll(filter.getHostsList());
22586                }
22587            }
22588        }
22589
22590        StringBuilder sb = new StringBuilder(result.size() * 16);
22591        for (String domain : result) {
22592            if (sb.length() > 0) sb.append(" ");
22593            sb.append(domain);
22594        }
22595        return sb.toString();
22596    }
22597
22598    // ------- apps on sdcard specific code -------
22599    static final boolean DEBUG_SD_INSTALL = false;
22600
22601    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22602
22603    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22604
22605    private boolean mMediaMounted = false;
22606
22607    static String getEncryptKey() {
22608        try {
22609            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22610                    SD_ENCRYPTION_KEYSTORE_NAME);
22611            if (sdEncKey == null) {
22612                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22613                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22614                if (sdEncKey == null) {
22615                    Slog.e(TAG, "Failed to create encryption keys");
22616                    return null;
22617                }
22618            }
22619            return sdEncKey;
22620        } catch (NoSuchAlgorithmException nsae) {
22621            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22622            return null;
22623        } catch (IOException ioe) {
22624            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22625            return null;
22626        }
22627    }
22628
22629    /*
22630     * Update media status on PackageManager.
22631     */
22632    @Override
22633    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22634        enforceSystemOrRoot("Media status can only be updated by the system");
22635        // reader; this apparently protects mMediaMounted, but should probably
22636        // be a different lock in that case.
22637        synchronized (mPackages) {
22638            Log.i(TAG, "Updating external media status from "
22639                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
22640                    + (mediaStatus ? "mounted" : "unmounted"));
22641            if (DEBUG_SD_INSTALL)
22642                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22643                        + ", mMediaMounted=" + mMediaMounted);
22644            if (mediaStatus == mMediaMounted) {
22645                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22646                        : 0, -1);
22647                mHandler.sendMessage(msg);
22648                return;
22649            }
22650            mMediaMounted = mediaStatus;
22651        }
22652        // Queue up an async operation since the package installation may take a
22653        // little while.
22654        mHandler.post(new Runnable() {
22655            public void run() {
22656                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22657            }
22658        });
22659    }
22660
22661    /**
22662     * Called by StorageManagerService when the initial ASECs to scan are available.
22663     * Should block until all the ASEC containers are finished being scanned.
22664     */
22665    public void scanAvailableAsecs() {
22666        updateExternalMediaStatusInner(true, false, false);
22667    }
22668
22669    /*
22670     * Collect information of applications on external media, map them against
22671     * existing containers and update information based on current mount status.
22672     * Please note that we always have to report status if reportStatus has been
22673     * set to true especially when unloading packages.
22674     */
22675    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
22676            boolean externalStorage) {
22677        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
22678        int[] uidArr = EmptyArray.INT;
22679
22680        final String[] list = PackageHelper.getSecureContainerList();
22681        if (ArrayUtils.isEmpty(list)) {
22682            Log.i(TAG, "No secure containers found");
22683        } else {
22684            // Process list of secure containers and categorize them
22685            // as active or stale based on their package internal state.
22686
22687            // reader
22688            synchronized (mPackages) {
22689                for (String cid : list) {
22690                    // Leave stages untouched for now; installer service owns them
22691                    if (PackageInstallerService.isStageName(cid)) continue;
22692
22693                    if (DEBUG_SD_INSTALL)
22694                        Log.i(TAG, "Processing container " + cid);
22695                    String pkgName = getAsecPackageName(cid);
22696                    if (pkgName == null) {
22697                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
22698                        continue;
22699                    }
22700                    if (DEBUG_SD_INSTALL)
22701                        Log.i(TAG, "Looking for pkg : " + pkgName);
22702
22703                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
22704                    if (ps == null) {
22705                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
22706                        continue;
22707                    }
22708
22709                    /*
22710                     * Skip packages that are not external if we're unmounting
22711                     * external storage.
22712                     */
22713                    if (externalStorage && !isMounted && !isExternal(ps)) {
22714                        continue;
22715                    }
22716
22717                    final AsecInstallArgs args = new AsecInstallArgs(cid,
22718                            getAppDexInstructionSets(ps), ps.isForwardLocked());
22719                    // The package status is changed only if the code path
22720                    // matches between settings and the container id.
22721                    if (ps.codePathString != null
22722                            && ps.codePathString.startsWith(args.getCodePath())) {
22723                        if (DEBUG_SD_INSTALL) {
22724                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
22725                                    + " at code path: " + ps.codePathString);
22726                        }
22727
22728                        // We do have a valid package installed on sdcard
22729                        processCids.put(args, ps.codePathString);
22730                        final int uid = ps.appId;
22731                        if (uid != -1) {
22732                            uidArr = ArrayUtils.appendInt(uidArr, uid);
22733                        }
22734                    } else {
22735                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
22736                                + ps.codePathString);
22737                    }
22738                }
22739            }
22740
22741            Arrays.sort(uidArr);
22742        }
22743
22744        // Process packages with valid entries.
22745        if (isMounted) {
22746            if (DEBUG_SD_INSTALL)
22747                Log.i(TAG, "Loading packages");
22748            loadMediaPackages(processCids, uidArr, externalStorage);
22749            startCleaningPackages();
22750            mInstallerService.onSecureContainersAvailable();
22751        } else {
22752            if (DEBUG_SD_INSTALL)
22753                Log.i(TAG, "Unloading packages");
22754            unloadMediaPackages(processCids, uidArr, reportStatus);
22755        }
22756    }
22757
22758    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22759            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22760        final int size = infos.size();
22761        final String[] packageNames = new String[size];
22762        final int[] packageUids = new int[size];
22763        for (int i = 0; i < size; i++) {
22764            final ApplicationInfo info = infos.get(i);
22765            packageNames[i] = info.packageName;
22766            packageUids[i] = info.uid;
22767        }
22768        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22769                finishedReceiver);
22770    }
22771
22772    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22773            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22774        sendResourcesChangedBroadcast(mediaStatus, replacing,
22775                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22776    }
22777
22778    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22779            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22780        int size = pkgList.length;
22781        if (size > 0) {
22782            // Send broadcasts here
22783            Bundle extras = new Bundle();
22784            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22785            if (uidArr != null) {
22786                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22787            }
22788            if (replacing) {
22789                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22790            }
22791            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22792                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22793            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22794        }
22795    }
22796
22797   /*
22798     * Look at potentially valid container ids from processCids If package
22799     * information doesn't match the one on record or package scanning fails,
22800     * the cid is added to list of removeCids. We currently don't delete stale
22801     * containers.
22802     */
22803    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
22804            boolean externalStorage) {
22805        ArrayList<String> pkgList = new ArrayList<String>();
22806        Set<AsecInstallArgs> keys = processCids.keySet();
22807
22808        for (AsecInstallArgs args : keys) {
22809            String codePath = processCids.get(args);
22810            if (DEBUG_SD_INSTALL)
22811                Log.i(TAG, "Loading container : " + args.cid);
22812            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
22813            try {
22814                // Make sure there are no container errors first.
22815                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
22816                    Slog.e(TAG, "Failed to mount cid : " + args.cid
22817                            + " when installing from sdcard");
22818                    continue;
22819                }
22820                // Check code path here.
22821                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
22822                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
22823                            + " does not match one in settings " + codePath);
22824                    continue;
22825                }
22826                // Parse package
22827                int parseFlags = mDefParseFlags;
22828                if (args.isExternalAsec()) {
22829                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
22830                }
22831                if (args.isFwdLocked()) {
22832                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
22833                }
22834
22835                synchronized (mInstallLock) {
22836                    PackageParser.Package pkg = null;
22837                    try {
22838                        // Sadly we don't know the package name yet to freeze it
22839                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
22840                                SCAN_IGNORE_FROZEN, 0, null);
22841                    } catch (PackageManagerException e) {
22842                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
22843                    }
22844                    // Scan the package
22845                    if (pkg != null) {
22846                        /*
22847                         * TODO why is the lock being held? doPostInstall is
22848                         * called in other places without the lock. This needs
22849                         * to be straightened out.
22850                         */
22851                        // writer
22852                        synchronized (mPackages) {
22853                            retCode = PackageManager.INSTALL_SUCCEEDED;
22854                            pkgList.add(pkg.packageName);
22855                            // Post process args
22856                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
22857                                    pkg.applicationInfo.uid);
22858                        }
22859                    } else {
22860                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
22861                    }
22862                }
22863
22864            } finally {
22865                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
22866                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
22867                }
22868            }
22869        }
22870        // writer
22871        synchronized (mPackages) {
22872            // If the platform SDK has changed since the last time we booted,
22873            // we need to re-grant app permission to catch any new ones that
22874            // appear. This is really a hack, and means that apps can in some
22875            // cases get permissions that the user didn't initially explicitly
22876            // allow... it would be nice to have some better way to handle
22877            // this situation.
22878            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
22879                    : mSettings.getInternalVersion();
22880            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
22881                    : StorageManager.UUID_PRIVATE_INTERNAL;
22882
22883            int updateFlags = UPDATE_PERMISSIONS_ALL;
22884            if (ver.sdkVersion != mSdkVersion) {
22885                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22886                        + mSdkVersion + "; regranting permissions for external");
22887                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22888            }
22889            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22890
22891            // Yay, everything is now upgraded
22892            ver.forceCurrent();
22893
22894            // can downgrade to reader
22895            // Persist settings
22896            mSettings.writeLPr();
22897        }
22898        // Send a broadcast to let everyone know we are done processing
22899        if (pkgList.size() > 0) {
22900            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
22901        }
22902    }
22903
22904   /*
22905     * Utility method to unload a list of specified containers
22906     */
22907    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
22908        // Just unmount all valid containers.
22909        for (AsecInstallArgs arg : cidArgs) {
22910            synchronized (mInstallLock) {
22911                arg.doPostDeleteLI(false);
22912           }
22913       }
22914   }
22915
22916    /*
22917     * Unload packages mounted on external media. This involves deleting package
22918     * data from internal structures, sending broadcasts about disabled packages,
22919     * gc'ing to free up references, unmounting all secure containers
22920     * corresponding to packages on external media, and posting a
22921     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
22922     * that we always have to post this message if status has been requested no
22923     * matter what.
22924     */
22925    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
22926            final boolean reportStatus) {
22927        if (DEBUG_SD_INSTALL)
22928            Log.i(TAG, "unloading media packages");
22929        ArrayList<String> pkgList = new ArrayList<String>();
22930        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
22931        final Set<AsecInstallArgs> keys = processCids.keySet();
22932        for (AsecInstallArgs args : keys) {
22933            String pkgName = args.getPackageName();
22934            if (DEBUG_SD_INSTALL)
22935                Log.i(TAG, "Trying to unload pkg : " + pkgName);
22936            // Delete package internally
22937            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22938            synchronized (mInstallLock) {
22939                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22940                final boolean res;
22941                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
22942                        "unloadMediaPackages")) {
22943                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
22944                            null);
22945                }
22946                if (res) {
22947                    pkgList.add(pkgName);
22948                } else {
22949                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
22950                    failedList.add(args);
22951                }
22952            }
22953        }
22954
22955        // reader
22956        synchronized (mPackages) {
22957            // We didn't update the settings after removing each package;
22958            // write them now for all packages.
22959            mSettings.writeLPr();
22960        }
22961
22962        // We have to absolutely send UPDATED_MEDIA_STATUS only
22963        // after confirming that all the receivers processed the ordered
22964        // broadcast when packages get disabled, force a gc to clean things up.
22965        // and unload all the containers.
22966        if (pkgList.size() > 0) {
22967            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
22968                    new IIntentReceiver.Stub() {
22969                public void performReceive(Intent intent, int resultCode, String data,
22970                        Bundle extras, boolean ordered, boolean sticky,
22971                        int sendingUser) throws RemoteException {
22972                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
22973                            reportStatus ? 1 : 0, 1, keys);
22974                    mHandler.sendMessage(msg);
22975                }
22976            });
22977        } else {
22978            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
22979                    keys);
22980            mHandler.sendMessage(msg);
22981        }
22982    }
22983
22984    private void loadPrivatePackages(final VolumeInfo vol) {
22985        mHandler.post(new Runnable() {
22986            @Override
22987            public void run() {
22988                loadPrivatePackagesInner(vol);
22989            }
22990        });
22991    }
22992
22993    private void loadPrivatePackagesInner(VolumeInfo vol) {
22994        final String volumeUuid = vol.fsUuid;
22995        if (TextUtils.isEmpty(volumeUuid)) {
22996            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22997            return;
22998        }
22999
23000        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
23001        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
23002        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
23003
23004        final VersionInfo ver;
23005        final List<PackageSetting> packages;
23006        synchronized (mPackages) {
23007            ver = mSettings.findOrCreateVersion(volumeUuid);
23008            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23009        }
23010
23011        for (PackageSetting ps : packages) {
23012            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
23013            synchronized (mInstallLock) {
23014                final PackageParser.Package pkg;
23015                try {
23016                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
23017                    loaded.add(pkg.applicationInfo);
23018
23019                } catch (PackageManagerException e) {
23020                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
23021                }
23022
23023                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
23024                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
23025                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
23026                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
23027                }
23028            }
23029        }
23030
23031        // Reconcile app data for all started/unlocked users
23032        final StorageManager sm = mContext.getSystemService(StorageManager.class);
23033        final UserManager um = mContext.getSystemService(UserManager.class);
23034        UserManagerInternal umInternal = getUserManagerInternal();
23035        for (UserInfo user : um.getUsers()) {
23036            final int flags;
23037            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23038                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23039            } else if (umInternal.isUserRunning(user.id)) {
23040                flags = StorageManager.FLAG_STORAGE_DE;
23041            } else {
23042                continue;
23043            }
23044
23045            try {
23046                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
23047                synchronized (mInstallLock) {
23048                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
23049                }
23050            } catch (IllegalStateException e) {
23051                // Device was probably ejected, and we'll process that event momentarily
23052                Slog.w(TAG, "Failed to prepare storage: " + e);
23053            }
23054        }
23055
23056        synchronized (mPackages) {
23057            int updateFlags = UPDATE_PERMISSIONS_ALL;
23058            if (ver.sdkVersion != mSdkVersion) {
23059                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
23060                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
23061                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
23062            }
23063            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
23064
23065            // Yay, everything is now upgraded
23066            ver.forceCurrent();
23067
23068            mSettings.writeLPr();
23069        }
23070
23071        for (PackageFreezer freezer : freezers) {
23072            freezer.close();
23073        }
23074
23075        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
23076        sendResourcesChangedBroadcast(true, false, loaded, null);
23077    }
23078
23079    private void unloadPrivatePackages(final VolumeInfo vol) {
23080        mHandler.post(new Runnable() {
23081            @Override
23082            public void run() {
23083                unloadPrivatePackagesInner(vol);
23084            }
23085        });
23086    }
23087
23088    private void unloadPrivatePackagesInner(VolumeInfo vol) {
23089        final String volumeUuid = vol.fsUuid;
23090        if (TextUtils.isEmpty(volumeUuid)) {
23091            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
23092            return;
23093        }
23094
23095        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
23096        synchronized (mInstallLock) {
23097        synchronized (mPackages) {
23098            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
23099            for (PackageSetting ps : packages) {
23100                if (ps.pkg == null) continue;
23101
23102                final ApplicationInfo info = ps.pkg.applicationInfo;
23103                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
23104                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
23105
23106                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
23107                        "unloadPrivatePackagesInner")) {
23108                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
23109                            false, null)) {
23110                        unloaded.add(info);
23111                    } else {
23112                        Slog.w(TAG, "Failed to unload " + ps.codePath);
23113                    }
23114                }
23115
23116                // Try very hard to release any references to this package
23117                // so we don't risk the system server being killed due to
23118                // open FDs
23119                AttributeCache.instance().removePackage(ps.name);
23120            }
23121
23122            mSettings.writeLPr();
23123        }
23124        }
23125
23126        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23127        sendResourcesChangedBroadcast(false, false, unloaded, null);
23128
23129        // Try very hard to release any references to this path so we don't risk
23130        // the system server being killed due to open FDs
23131        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23132
23133        for (int i = 0; i < 3; i++) {
23134            System.gc();
23135            System.runFinalization();
23136        }
23137    }
23138
23139    private void assertPackageKnown(String volumeUuid, String packageName)
23140            throws PackageManagerException {
23141        synchronized (mPackages) {
23142            // Normalize package name to handle renamed packages
23143            packageName = normalizePackageNameLPr(packageName);
23144
23145            final PackageSetting ps = mSettings.mPackages.get(packageName);
23146            if (ps == null) {
23147                throw new PackageManagerException("Package " + packageName + " is unknown");
23148            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23149                throw new PackageManagerException(
23150                        "Package " + packageName + " found on unknown volume " + volumeUuid
23151                                + "; expected volume " + ps.volumeUuid);
23152            }
23153        }
23154    }
23155
23156    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23157            throws PackageManagerException {
23158        synchronized (mPackages) {
23159            // Normalize package name to handle renamed packages
23160            packageName = normalizePackageNameLPr(packageName);
23161
23162            final PackageSetting ps = mSettings.mPackages.get(packageName);
23163            if (ps == null) {
23164                throw new PackageManagerException("Package " + packageName + " is unknown");
23165            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23166                throw new PackageManagerException(
23167                        "Package " + packageName + " found on unknown volume " + volumeUuid
23168                                + "; expected volume " + ps.volumeUuid);
23169            } else if (!ps.getInstalled(userId)) {
23170                throw new PackageManagerException(
23171                        "Package " + packageName + " not installed for user " + userId);
23172            }
23173        }
23174    }
23175
23176    private List<String> collectAbsoluteCodePaths() {
23177        synchronized (mPackages) {
23178            List<String> codePaths = new ArrayList<>();
23179            final int packageCount = mSettings.mPackages.size();
23180            for (int i = 0; i < packageCount; i++) {
23181                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23182                codePaths.add(ps.codePath.getAbsolutePath());
23183            }
23184            return codePaths;
23185        }
23186    }
23187
23188    /**
23189     * Examine all apps present on given mounted volume, and destroy apps that
23190     * aren't expected, either due to uninstallation or reinstallation on
23191     * another volume.
23192     */
23193    private void reconcileApps(String volumeUuid) {
23194        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23195        List<File> filesToDelete = null;
23196
23197        final File[] files = FileUtils.listFilesOrEmpty(
23198                Environment.getDataAppDirectory(volumeUuid));
23199        for (File file : files) {
23200            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23201                    && !PackageInstallerService.isStageName(file.getName());
23202            if (!isPackage) {
23203                // Ignore entries which are not packages
23204                continue;
23205            }
23206
23207            String absolutePath = file.getAbsolutePath();
23208
23209            boolean pathValid = false;
23210            final int absoluteCodePathCount = absoluteCodePaths.size();
23211            for (int i = 0; i < absoluteCodePathCount; i++) {
23212                String absoluteCodePath = absoluteCodePaths.get(i);
23213                if (absolutePath.startsWith(absoluteCodePath)) {
23214                    pathValid = true;
23215                    break;
23216                }
23217            }
23218
23219            if (!pathValid) {
23220                if (filesToDelete == null) {
23221                    filesToDelete = new ArrayList<>();
23222                }
23223                filesToDelete.add(file);
23224            }
23225        }
23226
23227        if (filesToDelete != null) {
23228            final int fileToDeleteCount = filesToDelete.size();
23229            for (int i = 0; i < fileToDeleteCount; i++) {
23230                File fileToDelete = filesToDelete.get(i);
23231                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23232                synchronized (mInstallLock) {
23233                    removeCodePathLI(fileToDelete);
23234                }
23235            }
23236        }
23237    }
23238
23239    /**
23240     * Reconcile all app data for the given user.
23241     * <p>
23242     * Verifies that directories exist and that ownership and labeling is
23243     * correct for all installed apps on all mounted volumes.
23244     */
23245    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23246        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23247        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23248            final String volumeUuid = vol.getFsUuid();
23249            synchronized (mInstallLock) {
23250                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23251            }
23252        }
23253    }
23254
23255    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23256            boolean migrateAppData) {
23257        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23258    }
23259
23260    /**
23261     * Reconcile all app data on given mounted volume.
23262     * <p>
23263     * Destroys app data that isn't expected, either due to uninstallation or
23264     * reinstallation on another volume.
23265     * <p>
23266     * Verifies that directories exist and that ownership and labeling is
23267     * correct for all installed apps.
23268     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23269     */
23270    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23271            boolean migrateAppData, boolean onlyCoreApps) {
23272        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23273                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23274        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23275
23276        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23277        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23278
23279        // First look for stale data that doesn't belong, and check if things
23280        // have changed since we did our last restorecon
23281        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23282            if (StorageManager.isFileEncryptedNativeOrEmulated()
23283                    && !StorageManager.isUserKeyUnlocked(userId)) {
23284                throw new RuntimeException(
23285                        "Yikes, someone asked us to reconcile CE storage while " + userId
23286                                + " was still locked; this would have caused massive data loss!");
23287            }
23288
23289            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23290            for (File file : files) {
23291                final String packageName = file.getName();
23292                try {
23293                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23294                } catch (PackageManagerException e) {
23295                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23296                    try {
23297                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23298                                StorageManager.FLAG_STORAGE_CE, 0);
23299                    } catch (InstallerException e2) {
23300                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23301                    }
23302                }
23303            }
23304        }
23305        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23306            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23307            for (File file : files) {
23308                final String packageName = file.getName();
23309                try {
23310                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23311                } catch (PackageManagerException e) {
23312                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23313                    try {
23314                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23315                                StorageManager.FLAG_STORAGE_DE, 0);
23316                    } catch (InstallerException e2) {
23317                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23318                    }
23319                }
23320            }
23321        }
23322
23323        // Ensure that data directories are ready to roll for all packages
23324        // installed for this volume and user
23325        final List<PackageSetting> packages;
23326        synchronized (mPackages) {
23327            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23328        }
23329        int preparedCount = 0;
23330        for (PackageSetting ps : packages) {
23331            final String packageName = ps.name;
23332            if (ps.pkg == null) {
23333                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23334                // TODO: might be due to legacy ASEC apps; we should circle back
23335                // and reconcile again once they're scanned
23336                continue;
23337            }
23338            // Skip non-core apps if requested
23339            if (onlyCoreApps && !ps.pkg.coreApp) {
23340                result.add(packageName);
23341                continue;
23342            }
23343
23344            if (ps.getInstalled(userId)) {
23345                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23346                preparedCount++;
23347            }
23348        }
23349
23350        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23351        return result;
23352    }
23353
23354    /**
23355     * Prepare app data for the given app just after it was installed or
23356     * upgraded. This method carefully only touches users that it's installed
23357     * for, and it forces a restorecon to handle any seinfo changes.
23358     * <p>
23359     * Verifies that directories exist and that ownership and labeling is
23360     * correct for all installed apps. If there is an ownership mismatch, it
23361     * will try recovering system apps by wiping data; third-party app data is
23362     * left intact.
23363     * <p>
23364     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23365     */
23366    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23367        final PackageSetting ps;
23368        synchronized (mPackages) {
23369            ps = mSettings.mPackages.get(pkg.packageName);
23370            mSettings.writeKernelMappingLPr(ps);
23371        }
23372
23373        final UserManager um = mContext.getSystemService(UserManager.class);
23374        UserManagerInternal umInternal = getUserManagerInternal();
23375        for (UserInfo user : um.getUsers()) {
23376            final int flags;
23377            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23378                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23379            } else if (umInternal.isUserRunning(user.id)) {
23380                flags = StorageManager.FLAG_STORAGE_DE;
23381            } else {
23382                continue;
23383            }
23384
23385            if (ps.getInstalled(user.id)) {
23386                // TODO: when user data is locked, mark that we're still dirty
23387                prepareAppDataLIF(pkg, user.id, flags);
23388            }
23389        }
23390    }
23391
23392    /**
23393     * Prepare app data for the given app.
23394     * <p>
23395     * Verifies that directories exist and that ownership and labeling is
23396     * correct for all installed apps. If there is an ownership mismatch, this
23397     * will try recovering system apps by wiping data; third-party app data is
23398     * left intact.
23399     */
23400    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23401        if (pkg == null) {
23402            Slog.wtf(TAG, "Package was null!", new Throwable());
23403            return;
23404        }
23405        prepareAppDataLeafLIF(pkg, userId, flags);
23406        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23407        for (int i = 0; i < childCount; i++) {
23408            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23409        }
23410    }
23411
23412    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23413            boolean maybeMigrateAppData) {
23414        prepareAppDataLIF(pkg, userId, flags);
23415
23416        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23417            // We may have just shuffled around app data directories, so
23418            // prepare them one more time
23419            prepareAppDataLIF(pkg, userId, flags);
23420        }
23421    }
23422
23423    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23424        if (DEBUG_APP_DATA) {
23425            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23426                    + Integer.toHexString(flags));
23427        }
23428
23429        final String volumeUuid = pkg.volumeUuid;
23430        final String packageName = pkg.packageName;
23431        final ApplicationInfo app = pkg.applicationInfo;
23432        final int appId = UserHandle.getAppId(app.uid);
23433
23434        Preconditions.checkNotNull(app.seInfo);
23435
23436        long ceDataInode = -1;
23437        try {
23438            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23439                    appId, app.seInfo, app.targetSdkVersion);
23440        } catch (InstallerException e) {
23441            if (app.isSystemApp()) {
23442                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23443                        + ", but trying to recover: " + e);
23444                destroyAppDataLeafLIF(pkg, userId, flags);
23445                try {
23446                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23447                            appId, app.seInfo, app.targetSdkVersion);
23448                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23449                } catch (InstallerException e2) {
23450                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23451                }
23452            } else {
23453                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23454            }
23455        }
23456
23457        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23458            // TODO: mark this structure as dirty so we persist it!
23459            synchronized (mPackages) {
23460                final PackageSetting ps = mSettings.mPackages.get(packageName);
23461                if (ps != null) {
23462                    ps.setCeDataInode(ceDataInode, userId);
23463                }
23464            }
23465        }
23466
23467        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23468    }
23469
23470    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23471        if (pkg == null) {
23472            Slog.wtf(TAG, "Package was null!", new Throwable());
23473            return;
23474        }
23475        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23476        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23477        for (int i = 0; i < childCount; i++) {
23478            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23479        }
23480    }
23481
23482    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23483        final String volumeUuid = pkg.volumeUuid;
23484        final String packageName = pkg.packageName;
23485        final ApplicationInfo app = pkg.applicationInfo;
23486
23487        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23488            // Create a native library symlink only if we have native libraries
23489            // and if the native libraries are 32 bit libraries. We do not provide
23490            // this symlink for 64 bit libraries.
23491            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23492                final String nativeLibPath = app.nativeLibraryDir;
23493                try {
23494                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23495                            nativeLibPath, userId);
23496                } catch (InstallerException e) {
23497                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23498                }
23499            }
23500        }
23501    }
23502
23503    /**
23504     * For system apps on non-FBE devices, this method migrates any existing
23505     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23506     * requested by the app.
23507     */
23508    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23509        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23510                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23511            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23512                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23513            try {
23514                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23515                        storageTarget);
23516            } catch (InstallerException e) {
23517                logCriticalInfo(Log.WARN,
23518                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23519            }
23520            return true;
23521        } else {
23522            return false;
23523        }
23524    }
23525
23526    public PackageFreezer freezePackage(String packageName, String killReason) {
23527        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23528    }
23529
23530    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23531        return new PackageFreezer(packageName, userId, killReason);
23532    }
23533
23534    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23535            String killReason) {
23536        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23537    }
23538
23539    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23540            String killReason) {
23541        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23542            return new PackageFreezer();
23543        } else {
23544            return freezePackage(packageName, userId, killReason);
23545        }
23546    }
23547
23548    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23549            String killReason) {
23550        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23551    }
23552
23553    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23554            String killReason) {
23555        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23556            return new PackageFreezer();
23557        } else {
23558            return freezePackage(packageName, userId, killReason);
23559        }
23560    }
23561
23562    /**
23563     * Class that freezes and kills the given package upon creation, and
23564     * unfreezes it upon closing. This is typically used when doing surgery on
23565     * app code/data to prevent the app from running while you're working.
23566     */
23567    private class PackageFreezer implements AutoCloseable {
23568        private final String mPackageName;
23569        private final PackageFreezer[] mChildren;
23570
23571        private final boolean mWeFroze;
23572
23573        private final AtomicBoolean mClosed = new AtomicBoolean();
23574        private final CloseGuard mCloseGuard = CloseGuard.get();
23575
23576        /**
23577         * Create and return a stub freezer that doesn't actually do anything,
23578         * typically used when someone requested
23579         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23580         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23581         */
23582        public PackageFreezer() {
23583            mPackageName = null;
23584            mChildren = null;
23585            mWeFroze = false;
23586            mCloseGuard.open("close");
23587        }
23588
23589        public PackageFreezer(String packageName, int userId, String killReason) {
23590            synchronized (mPackages) {
23591                mPackageName = packageName;
23592                mWeFroze = mFrozenPackages.add(mPackageName);
23593
23594                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23595                if (ps != null) {
23596                    killApplication(ps.name, ps.appId, userId, killReason);
23597                }
23598
23599                final PackageParser.Package p = mPackages.get(packageName);
23600                if (p != null && p.childPackages != null) {
23601                    final int N = p.childPackages.size();
23602                    mChildren = new PackageFreezer[N];
23603                    for (int i = 0; i < N; i++) {
23604                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23605                                userId, killReason);
23606                    }
23607                } else {
23608                    mChildren = null;
23609                }
23610            }
23611            mCloseGuard.open("close");
23612        }
23613
23614        @Override
23615        protected void finalize() throws Throwable {
23616            try {
23617                if (mCloseGuard != null) {
23618                    mCloseGuard.warnIfOpen();
23619                }
23620
23621                close();
23622            } finally {
23623                super.finalize();
23624            }
23625        }
23626
23627        @Override
23628        public void close() {
23629            mCloseGuard.close();
23630            if (mClosed.compareAndSet(false, true)) {
23631                synchronized (mPackages) {
23632                    if (mWeFroze) {
23633                        mFrozenPackages.remove(mPackageName);
23634                    }
23635
23636                    if (mChildren != null) {
23637                        for (PackageFreezer freezer : mChildren) {
23638                            freezer.close();
23639                        }
23640                    }
23641                }
23642            }
23643        }
23644    }
23645
23646    /**
23647     * Verify that given package is currently frozen.
23648     */
23649    private void checkPackageFrozen(String packageName) {
23650        synchronized (mPackages) {
23651            if (!mFrozenPackages.contains(packageName)) {
23652                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23653            }
23654        }
23655    }
23656
23657    @Override
23658    public int movePackage(final String packageName, final String volumeUuid) {
23659        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23660
23661        final int callingUid = Binder.getCallingUid();
23662        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23663        final int moveId = mNextMoveId.getAndIncrement();
23664        mHandler.post(new Runnable() {
23665            @Override
23666            public void run() {
23667                try {
23668                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23669                } catch (PackageManagerException e) {
23670                    Slog.w(TAG, "Failed to move " + packageName, e);
23671                    mMoveCallbacks.notifyStatusChanged(moveId,
23672                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23673                }
23674            }
23675        });
23676        return moveId;
23677    }
23678
23679    private void movePackageInternal(final String packageName, final String volumeUuid,
23680            final int moveId, final int callingUid, UserHandle user)
23681                    throws PackageManagerException {
23682        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23683        final PackageManager pm = mContext.getPackageManager();
23684
23685        final boolean currentAsec;
23686        final String currentVolumeUuid;
23687        final File codeFile;
23688        final String installerPackageName;
23689        final String packageAbiOverride;
23690        final int appId;
23691        final String seinfo;
23692        final String label;
23693        final int targetSdkVersion;
23694        final PackageFreezer freezer;
23695        final int[] installedUserIds;
23696
23697        // reader
23698        synchronized (mPackages) {
23699            final PackageParser.Package pkg = mPackages.get(packageName);
23700            final PackageSetting ps = mSettings.mPackages.get(packageName);
23701            if (pkg == null
23702                    || ps == null
23703                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
23704                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23705            }
23706            if (pkg.applicationInfo.isSystemApp()) {
23707                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23708                        "Cannot move system application");
23709            }
23710
23711            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23712            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23713                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23714            if (isInternalStorage && !allow3rdPartyOnInternal) {
23715                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23716                        "3rd party apps are not allowed on internal storage");
23717            }
23718
23719            if (pkg.applicationInfo.isExternalAsec()) {
23720                currentAsec = true;
23721                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23722            } else if (pkg.applicationInfo.isForwardLocked()) {
23723                currentAsec = true;
23724                currentVolumeUuid = "forward_locked";
23725            } else {
23726                currentAsec = false;
23727                currentVolumeUuid = ps.volumeUuid;
23728
23729                final File probe = new File(pkg.codePath);
23730                final File probeOat = new File(probe, "oat");
23731                if (!probe.isDirectory() || !probeOat.isDirectory()) {
23732                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23733                            "Move only supported for modern cluster style installs");
23734                }
23735            }
23736
23737            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23738                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23739                        "Package already moved to " + volumeUuid);
23740            }
23741            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23742                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23743                        "Device admin cannot be moved");
23744            }
23745
23746            if (mFrozenPackages.contains(packageName)) {
23747                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23748                        "Failed to move already frozen package");
23749            }
23750
23751            codeFile = new File(pkg.codePath);
23752            installerPackageName = ps.installerPackageName;
23753            packageAbiOverride = ps.cpuAbiOverrideString;
23754            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23755            seinfo = pkg.applicationInfo.seInfo;
23756            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23757            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23758            freezer = freezePackage(packageName, "movePackageInternal");
23759            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23760        }
23761
23762        final Bundle extras = new Bundle();
23763        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23764        extras.putString(Intent.EXTRA_TITLE, label);
23765        mMoveCallbacks.notifyCreated(moveId, extras);
23766
23767        int installFlags;
23768        final boolean moveCompleteApp;
23769        final File measurePath;
23770
23771        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23772            installFlags = INSTALL_INTERNAL;
23773            moveCompleteApp = !currentAsec;
23774            measurePath = Environment.getDataAppDirectory(volumeUuid);
23775        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23776            installFlags = INSTALL_EXTERNAL;
23777            moveCompleteApp = false;
23778            measurePath = storage.getPrimaryPhysicalVolume().getPath();
23779        } else {
23780            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23781            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23782                    || !volume.isMountedWritable()) {
23783                freezer.close();
23784                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23785                        "Move location not mounted private volume");
23786            }
23787
23788            Preconditions.checkState(!currentAsec);
23789
23790            installFlags = INSTALL_INTERNAL;
23791            moveCompleteApp = true;
23792            measurePath = Environment.getDataAppDirectory(volumeUuid);
23793        }
23794
23795        final PackageStats stats = new PackageStats(null, -1);
23796        synchronized (mInstaller) {
23797            for (int userId : installedUserIds) {
23798                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23799                    freezer.close();
23800                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23801                            "Failed to measure package size");
23802                }
23803            }
23804        }
23805
23806        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23807                + stats.dataSize);
23808
23809        final long startFreeBytes = measurePath.getUsableSpace();
23810        final long sizeBytes;
23811        if (moveCompleteApp) {
23812            sizeBytes = stats.codeSize + stats.dataSize;
23813        } else {
23814            sizeBytes = stats.codeSize;
23815        }
23816
23817        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23818            freezer.close();
23819            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23820                    "Not enough free space to move");
23821        }
23822
23823        mMoveCallbacks.notifyStatusChanged(moveId, 10);
23824
23825        final CountDownLatch installedLatch = new CountDownLatch(1);
23826        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23827            @Override
23828            public void onUserActionRequired(Intent intent) throws RemoteException {
23829                throw new IllegalStateException();
23830            }
23831
23832            @Override
23833            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23834                    Bundle extras) throws RemoteException {
23835                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23836                        + PackageManager.installStatusToString(returnCode, msg));
23837
23838                installedLatch.countDown();
23839                freezer.close();
23840
23841                final int status = PackageManager.installStatusToPublicStatus(returnCode);
23842                switch (status) {
23843                    case PackageInstaller.STATUS_SUCCESS:
23844                        mMoveCallbacks.notifyStatusChanged(moveId,
23845                                PackageManager.MOVE_SUCCEEDED);
23846                        break;
23847                    case PackageInstaller.STATUS_FAILURE_STORAGE:
23848                        mMoveCallbacks.notifyStatusChanged(moveId,
23849                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23850                        break;
23851                    default:
23852                        mMoveCallbacks.notifyStatusChanged(moveId,
23853                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23854                        break;
23855                }
23856            }
23857        };
23858
23859        final MoveInfo move;
23860        if (moveCompleteApp) {
23861            // Kick off a thread to report progress estimates
23862            new Thread() {
23863                @Override
23864                public void run() {
23865                    while (true) {
23866                        try {
23867                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
23868                                break;
23869                            }
23870                        } catch (InterruptedException ignored) {
23871                        }
23872
23873                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23874                        final int progress = 10 + (int) MathUtils.constrain(
23875                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23876                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23877                    }
23878                }
23879            }.start();
23880
23881            final String dataAppName = codeFile.getName();
23882            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23883                    dataAppName, appId, seinfo, targetSdkVersion);
23884        } else {
23885            move = null;
23886        }
23887
23888        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23889
23890        final Message msg = mHandler.obtainMessage(INIT_COPY);
23891        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23892        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23893                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23894                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23895                PackageManager.INSTALL_REASON_UNKNOWN);
23896        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23897        msg.obj = params;
23898
23899        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23900                System.identityHashCode(msg.obj));
23901        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23902                System.identityHashCode(msg.obj));
23903
23904        mHandler.sendMessage(msg);
23905    }
23906
23907    @Override
23908    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23909        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23910
23911        final int realMoveId = mNextMoveId.getAndIncrement();
23912        final Bundle extras = new Bundle();
23913        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23914        mMoveCallbacks.notifyCreated(realMoveId, extras);
23915
23916        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23917            @Override
23918            public void onCreated(int moveId, Bundle extras) {
23919                // Ignored
23920            }
23921
23922            @Override
23923            public void onStatusChanged(int moveId, int status, long estMillis) {
23924                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23925            }
23926        };
23927
23928        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23929        storage.setPrimaryStorageUuid(volumeUuid, callback);
23930        return realMoveId;
23931    }
23932
23933    @Override
23934    public int getMoveStatus(int moveId) {
23935        mContext.enforceCallingOrSelfPermission(
23936                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23937        return mMoveCallbacks.mLastStatus.get(moveId);
23938    }
23939
23940    @Override
23941    public void registerMoveCallback(IPackageMoveObserver callback) {
23942        mContext.enforceCallingOrSelfPermission(
23943                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23944        mMoveCallbacks.register(callback);
23945    }
23946
23947    @Override
23948    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23949        mContext.enforceCallingOrSelfPermission(
23950                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23951        mMoveCallbacks.unregister(callback);
23952    }
23953
23954    @Override
23955    public boolean setInstallLocation(int loc) {
23956        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23957                null);
23958        if (getInstallLocation() == loc) {
23959            return true;
23960        }
23961        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23962                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23963            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23964                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23965            return true;
23966        }
23967        return false;
23968   }
23969
23970    @Override
23971    public int getInstallLocation() {
23972        // allow instant app access
23973        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23974                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23975                PackageHelper.APP_INSTALL_AUTO);
23976    }
23977
23978    /** Called by UserManagerService */
23979    void cleanUpUser(UserManagerService userManager, int userHandle) {
23980        synchronized (mPackages) {
23981            mDirtyUsers.remove(userHandle);
23982            mUserNeedsBadging.delete(userHandle);
23983            mSettings.removeUserLPw(userHandle);
23984            mPendingBroadcasts.remove(userHandle);
23985            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23986            removeUnusedPackagesLPw(userManager, userHandle);
23987        }
23988    }
23989
23990    /**
23991     * We're removing userHandle and would like to remove any downloaded packages
23992     * that are no longer in use by any other user.
23993     * @param userHandle the user being removed
23994     */
23995    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23996        final boolean DEBUG_CLEAN_APKS = false;
23997        int [] users = userManager.getUserIds();
23998        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23999        while (psit.hasNext()) {
24000            PackageSetting ps = psit.next();
24001            if (ps.pkg == null) {
24002                continue;
24003            }
24004            final String packageName = ps.pkg.packageName;
24005            // Skip over if system app
24006            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24007                continue;
24008            }
24009            if (DEBUG_CLEAN_APKS) {
24010                Slog.i(TAG, "Checking package " + packageName);
24011            }
24012            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
24013            if (keep) {
24014                if (DEBUG_CLEAN_APKS) {
24015                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
24016                }
24017            } else {
24018                for (int i = 0; i < users.length; i++) {
24019                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
24020                        keep = true;
24021                        if (DEBUG_CLEAN_APKS) {
24022                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
24023                                    + users[i]);
24024                        }
24025                        break;
24026                    }
24027                }
24028            }
24029            if (!keep) {
24030                if (DEBUG_CLEAN_APKS) {
24031                    Slog.i(TAG, "  Removing package " + packageName);
24032                }
24033                mHandler.post(new Runnable() {
24034                    public void run() {
24035                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24036                                userHandle, 0);
24037                    } //end run
24038                });
24039            }
24040        }
24041    }
24042
24043    /** Called by UserManagerService */
24044    void createNewUser(int userId, String[] disallowedPackages) {
24045        synchronized (mInstallLock) {
24046            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
24047        }
24048        synchronized (mPackages) {
24049            scheduleWritePackageRestrictionsLocked(userId);
24050            scheduleWritePackageListLocked(userId);
24051            applyFactoryDefaultBrowserLPw(userId);
24052            primeDomainVerificationsLPw(userId);
24053        }
24054    }
24055
24056    void onNewUserCreated(final int userId) {
24057        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
24058        // If permission review for legacy apps is required, we represent
24059        // dagerous permissions for such apps as always granted runtime
24060        // permissions to keep per user flag state whether review is needed.
24061        // Hence, if a new user is added we have to propagate dangerous
24062        // permission grants for these legacy apps.
24063        if (mPermissionReviewRequired) {
24064            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
24065                    | UPDATE_PERMISSIONS_REPLACE_ALL);
24066        }
24067    }
24068
24069    @Override
24070    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
24071        mContext.enforceCallingOrSelfPermission(
24072                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
24073                "Only package verification agents can read the verifier device identity");
24074
24075        synchronized (mPackages) {
24076            return mSettings.getVerifierDeviceIdentityLPw();
24077        }
24078    }
24079
24080    @Override
24081    public void setPermissionEnforced(String permission, boolean enforced) {
24082        // TODO: Now that we no longer change GID for storage, this should to away.
24083        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
24084                "setPermissionEnforced");
24085        if (READ_EXTERNAL_STORAGE.equals(permission)) {
24086            synchronized (mPackages) {
24087                if (mSettings.mReadExternalStorageEnforced == null
24088                        || mSettings.mReadExternalStorageEnforced != enforced) {
24089                    mSettings.mReadExternalStorageEnforced = enforced;
24090                    mSettings.writeLPr();
24091                }
24092            }
24093            // kill any non-foreground processes so we restart them and
24094            // grant/revoke the GID.
24095            final IActivityManager am = ActivityManager.getService();
24096            if (am != null) {
24097                final long token = Binder.clearCallingIdentity();
24098                try {
24099                    am.killProcessesBelowForeground("setPermissionEnforcement");
24100                } catch (RemoteException e) {
24101                } finally {
24102                    Binder.restoreCallingIdentity(token);
24103                }
24104            }
24105        } else {
24106            throw new IllegalArgumentException("No selective enforcement for " + permission);
24107        }
24108    }
24109
24110    @Override
24111    @Deprecated
24112    public boolean isPermissionEnforced(String permission) {
24113        // allow instant applications
24114        return true;
24115    }
24116
24117    @Override
24118    public boolean isStorageLow() {
24119        // allow instant applications
24120        final long token = Binder.clearCallingIdentity();
24121        try {
24122            final DeviceStorageMonitorInternal
24123                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
24124            if (dsm != null) {
24125                return dsm.isMemoryLow();
24126            } else {
24127                return false;
24128            }
24129        } finally {
24130            Binder.restoreCallingIdentity(token);
24131        }
24132    }
24133
24134    @Override
24135    public IPackageInstaller getPackageInstaller() {
24136        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24137            return null;
24138        }
24139        return mInstallerService;
24140    }
24141
24142    private boolean userNeedsBadging(int userId) {
24143        int index = mUserNeedsBadging.indexOfKey(userId);
24144        if (index < 0) {
24145            final UserInfo userInfo;
24146            final long token = Binder.clearCallingIdentity();
24147            try {
24148                userInfo = sUserManager.getUserInfo(userId);
24149            } finally {
24150                Binder.restoreCallingIdentity(token);
24151            }
24152            final boolean b;
24153            if (userInfo != null && userInfo.isManagedProfile()) {
24154                b = true;
24155            } else {
24156                b = false;
24157            }
24158            mUserNeedsBadging.put(userId, b);
24159            return b;
24160        }
24161        return mUserNeedsBadging.valueAt(index);
24162    }
24163
24164    @Override
24165    public KeySet getKeySetByAlias(String packageName, String alias) {
24166        if (packageName == null || alias == null) {
24167            return null;
24168        }
24169        synchronized(mPackages) {
24170            final PackageParser.Package pkg = mPackages.get(packageName);
24171            if (pkg == null) {
24172                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24173                throw new IllegalArgumentException("Unknown package: " + packageName);
24174            }
24175            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24176            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24177                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24178                throw new IllegalArgumentException("Unknown package: " + packageName);
24179            }
24180            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24181            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24182        }
24183    }
24184
24185    @Override
24186    public KeySet getSigningKeySet(String packageName) {
24187        if (packageName == null) {
24188            return null;
24189        }
24190        synchronized(mPackages) {
24191            final int callingUid = Binder.getCallingUid();
24192            final int callingUserId = UserHandle.getUserId(callingUid);
24193            final PackageParser.Package pkg = mPackages.get(packageName);
24194            if (pkg == null) {
24195                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24196                throw new IllegalArgumentException("Unknown package: " + packageName);
24197            }
24198            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24199            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24200                // filter and pretend the package doesn't exist
24201                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24202                        + ", uid:" + callingUid);
24203                throw new IllegalArgumentException("Unknown package: " + packageName);
24204            }
24205            if (pkg.applicationInfo.uid != callingUid
24206                    && Process.SYSTEM_UID != callingUid) {
24207                throw new SecurityException("May not access signing KeySet of other apps.");
24208            }
24209            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24210            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24211        }
24212    }
24213
24214    @Override
24215    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24216        final int callingUid = Binder.getCallingUid();
24217        if (getInstantAppPackageName(callingUid) != null) {
24218            return false;
24219        }
24220        if (packageName == null || ks == null) {
24221            return false;
24222        }
24223        synchronized(mPackages) {
24224            final PackageParser.Package pkg = mPackages.get(packageName);
24225            if (pkg == null
24226                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24227                            UserHandle.getUserId(callingUid))) {
24228                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24229                throw new IllegalArgumentException("Unknown package: " + packageName);
24230            }
24231            IBinder ksh = ks.getToken();
24232            if (ksh instanceof KeySetHandle) {
24233                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24234                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24235            }
24236            return false;
24237        }
24238    }
24239
24240    @Override
24241    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24242        final int callingUid = Binder.getCallingUid();
24243        if (getInstantAppPackageName(callingUid) != null) {
24244            return false;
24245        }
24246        if (packageName == null || ks == null) {
24247            return false;
24248        }
24249        synchronized(mPackages) {
24250            final PackageParser.Package pkg = mPackages.get(packageName);
24251            if (pkg == null
24252                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
24253                            UserHandle.getUserId(callingUid))) {
24254                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24255                throw new IllegalArgumentException("Unknown package: " + packageName);
24256            }
24257            IBinder ksh = ks.getToken();
24258            if (ksh instanceof KeySetHandle) {
24259                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24260                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24261            }
24262            return false;
24263        }
24264    }
24265
24266    private void deletePackageIfUnusedLPr(final String packageName) {
24267        PackageSetting ps = mSettings.mPackages.get(packageName);
24268        if (ps == null) {
24269            return;
24270        }
24271        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24272            // TODO Implement atomic delete if package is unused
24273            // It is currently possible that the package will be deleted even if it is installed
24274            // after this method returns.
24275            mHandler.post(new Runnable() {
24276                public void run() {
24277                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24278                            0, PackageManager.DELETE_ALL_USERS);
24279                }
24280            });
24281        }
24282    }
24283
24284    /**
24285     * Check and throw if the given before/after packages would be considered a
24286     * downgrade.
24287     */
24288    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24289            throws PackageManagerException {
24290        if (after.versionCode < before.mVersionCode) {
24291            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24292                    "Update version code " + after.versionCode + " is older than current "
24293                    + before.mVersionCode);
24294        } else if (after.versionCode == before.mVersionCode) {
24295            if (after.baseRevisionCode < before.baseRevisionCode) {
24296                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24297                        "Update base revision code " + after.baseRevisionCode
24298                        + " is older than current " + before.baseRevisionCode);
24299            }
24300
24301            if (!ArrayUtils.isEmpty(after.splitNames)) {
24302                for (int i = 0; i < after.splitNames.length; i++) {
24303                    final String splitName = after.splitNames[i];
24304                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24305                    if (j != -1) {
24306                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24307                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24308                                    "Update split " + splitName + " revision code "
24309                                    + after.splitRevisionCodes[i] + " is older than current "
24310                                    + before.splitRevisionCodes[j]);
24311                        }
24312                    }
24313                }
24314            }
24315        }
24316    }
24317
24318    private static class MoveCallbacks extends Handler {
24319        private static final int MSG_CREATED = 1;
24320        private static final int MSG_STATUS_CHANGED = 2;
24321
24322        private final RemoteCallbackList<IPackageMoveObserver>
24323                mCallbacks = new RemoteCallbackList<>();
24324
24325        private final SparseIntArray mLastStatus = new SparseIntArray();
24326
24327        public MoveCallbacks(Looper looper) {
24328            super(looper);
24329        }
24330
24331        public void register(IPackageMoveObserver callback) {
24332            mCallbacks.register(callback);
24333        }
24334
24335        public void unregister(IPackageMoveObserver callback) {
24336            mCallbacks.unregister(callback);
24337        }
24338
24339        @Override
24340        public void handleMessage(Message msg) {
24341            final SomeArgs args = (SomeArgs) msg.obj;
24342            final int n = mCallbacks.beginBroadcast();
24343            for (int i = 0; i < n; i++) {
24344                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24345                try {
24346                    invokeCallback(callback, msg.what, args);
24347                } catch (RemoteException ignored) {
24348                }
24349            }
24350            mCallbacks.finishBroadcast();
24351            args.recycle();
24352        }
24353
24354        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24355                throws RemoteException {
24356            switch (what) {
24357                case MSG_CREATED: {
24358                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24359                    break;
24360                }
24361                case MSG_STATUS_CHANGED: {
24362                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24363                    break;
24364                }
24365            }
24366        }
24367
24368        private void notifyCreated(int moveId, Bundle extras) {
24369            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24370
24371            final SomeArgs args = SomeArgs.obtain();
24372            args.argi1 = moveId;
24373            args.arg2 = extras;
24374            obtainMessage(MSG_CREATED, args).sendToTarget();
24375        }
24376
24377        private void notifyStatusChanged(int moveId, int status) {
24378            notifyStatusChanged(moveId, status, -1);
24379        }
24380
24381        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24382            Slog.v(TAG, "Move " + moveId + " status " + status);
24383
24384            final SomeArgs args = SomeArgs.obtain();
24385            args.argi1 = moveId;
24386            args.argi2 = status;
24387            args.arg3 = estMillis;
24388            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24389
24390            synchronized (mLastStatus) {
24391                mLastStatus.put(moveId, status);
24392            }
24393        }
24394    }
24395
24396    private final static class OnPermissionChangeListeners extends Handler {
24397        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24398
24399        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24400                new RemoteCallbackList<>();
24401
24402        public OnPermissionChangeListeners(Looper looper) {
24403            super(looper);
24404        }
24405
24406        @Override
24407        public void handleMessage(Message msg) {
24408            switch (msg.what) {
24409                case MSG_ON_PERMISSIONS_CHANGED: {
24410                    final int uid = msg.arg1;
24411                    handleOnPermissionsChanged(uid);
24412                } break;
24413            }
24414        }
24415
24416        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24417            mPermissionListeners.register(listener);
24418
24419        }
24420
24421        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24422            mPermissionListeners.unregister(listener);
24423        }
24424
24425        public void onPermissionsChanged(int uid) {
24426            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24427                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24428            }
24429        }
24430
24431        private void handleOnPermissionsChanged(int uid) {
24432            final int count = mPermissionListeners.beginBroadcast();
24433            try {
24434                for (int i = 0; i < count; i++) {
24435                    IOnPermissionsChangeListener callback = mPermissionListeners
24436                            .getBroadcastItem(i);
24437                    try {
24438                        callback.onPermissionsChanged(uid);
24439                    } catch (RemoteException e) {
24440                        Log.e(TAG, "Permission listener is dead", e);
24441                    }
24442                }
24443            } finally {
24444                mPermissionListeners.finishBroadcast();
24445            }
24446        }
24447    }
24448
24449    private class PackageManagerInternalImpl extends PackageManagerInternal {
24450        @Override
24451        public void setLocationPackagesProvider(PackagesProvider provider) {
24452            synchronized (mPackages) {
24453                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24454            }
24455        }
24456
24457        @Override
24458        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24459            synchronized (mPackages) {
24460                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24461            }
24462        }
24463
24464        @Override
24465        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24466            synchronized (mPackages) {
24467                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24468            }
24469        }
24470
24471        @Override
24472        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24473            synchronized (mPackages) {
24474                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24475            }
24476        }
24477
24478        @Override
24479        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24480            synchronized (mPackages) {
24481                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24482            }
24483        }
24484
24485        @Override
24486        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24487            synchronized (mPackages) {
24488                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24489            }
24490        }
24491
24492        @Override
24493        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24494            synchronized (mPackages) {
24495                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24496                        packageName, userId);
24497            }
24498        }
24499
24500        @Override
24501        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24502            synchronized (mPackages) {
24503                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24504                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24505                        packageName, userId);
24506            }
24507        }
24508
24509        @Override
24510        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24511            synchronized (mPackages) {
24512                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24513                        packageName, userId);
24514            }
24515        }
24516
24517        @Override
24518        public void setKeepUninstalledPackages(final List<String> packageList) {
24519            Preconditions.checkNotNull(packageList);
24520            List<String> removedFromList = null;
24521            synchronized (mPackages) {
24522                if (mKeepUninstalledPackages != null) {
24523                    final int packagesCount = mKeepUninstalledPackages.size();
24524                    for (int i = 0; i < packagesCount; i++) {
24525                        String oldPackage = mKeepUninstalledPackages.get(i);
24526                        if (packageList != null && packageList.contains(oldPackage)) {
24527                            continue;
24528                        }
24529                        if (removedFromList == null) {
24530                            removedFromList = new ArrayList<>();
24531                        }
24532                        removedFromList.add(oldPackage);
24533                    }
24534                }
24535                mKeepUninstalledPackages = new ArrayList<>(packageList);
24536                if (removedFromList != null) {
24537                    final int removedCount = removedFromList.size();
24538                    for (int i = 0; i < removedCount; i++) {
24539                        deletePackageIfUnusedLPr(removedFromList.get(i));
24540                    }
24541                }
24542            }
24543        }
24544
24545        @Override
24546        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24547            synchronized (mPackages) {
24548                // If we do not support permission review, done.
24549                if (!mPermissionReviewRequired) {
24550                    return false;
24551                }
24552
24553                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24554                if (packageSetting == null) {
24555                    return false;
24556                }
24557
24558                // Permission review applies only to apps not supporting the new permission model.
24559                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24560                    return false;
24561                }
24562
24563                // Legacy apps have the permission and get user consent on launch.
24564                PermissionsState permissionsState = packageSetting.getPermissionsState();
24565                return permissionsState.isPermissionReviewRequired(userId);
24566            }
24567        }
24568
24569        @Override
24570        public PackageInfo getPackageInfo(
24571                String packageName, int flags, int filterCallingUid, int userId) {
24572            return PackageManagerService.this
24573                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24574                            flags, filterCallingUid, userId);
24575        }
24576
24577        @Override
24578        public ApplicationInfo getApplicationInfo(
24579                String packageName, int flags, int filterCallingUid, int userId) {
24580            return PackageManagerService.this
24581                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24582        }
24583
24584        @Override
24585        public ActivityInfo getActivityInfo(
24586                ComponentName component, int flags, int filterCallingUid, int userId) {
24587            return PackageManagerService.this
24588                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24589        }
24590
24591        @Override
24592        public List<ResolveInfo> queryIntentActivities(
24593                Intent intent, int flags, int filterCallingUid, int userId) {
24594            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24595            return PackageManagerService.this
24596                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24597                            userId, false /*resolveForStart*/);
24598        }
24599
24600        @Override
24601        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24602                int userId) {
24603            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24604        }
24605
24606        @Override
24607        public void setDeviceAndProfileOwnerPackages(
24608                int deviceOwnerUserId, String deviceOwnerPackage,
24609                SparseArray<String> profileOwnerPackages) {
24610            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24611                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24612        }
24613
24614        @Override
24615        public boolean isPackageDataProtected(int userId, String packageName) {
24616            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24617        }
24618
24619        @Override
24620        public boolean isPackageEphemeral(int userId, String packageName) {
24621            synchronized (mPackages) {
24622                final PackageSetting ps = mSettings.mPackages.get(packageName);
24623                return ps != null ? ps.getInstantApp(userId) : false;
24624            }
24625        }
24626
24627        @Override
24628        public boolean wasPackageEverLaunched(String packageName, int userId) {
24629            synchronized (mPackages) {
24630                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24631            }
24632        }
24633
24634        @Override
24635        public void grantRuntimePermission(String packageName, String name, int userId,
24636                boolean overridePolicy) {
24637            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24638                    overridePolicy);
24639        }
24640
24641        @Override
24642        public void revokeRuntimePermission(String packageName, String name, int userId,
24643                boolean overridePolicy) {
24644            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24645                    overridePolicy);
24646        }
24647
24648        @Override
24649        public String getNameForUid(int uid) {
24650            return PackageManagerService.this.getNameForUid(uid);
24651        }
24652
24653        @Override
24654        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24655                Intent origIntent, String resolvedType, String callingPackage,
24656                Bundle verificationBundle, int userId) {
24657            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24658                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24659                    userId);
24660        }
24661
24662        @Override
24663        public void grantEphemeralAccess(int userId, Intent intent,
24664                int targetAppId, int ephemeralAppId) {
24665            synchronized (mPackages) {
24666                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24667                        targetAppId, ephemeralAppId);
24668            }
24669        }
24670
24671        @Override
24672        public boolean isInstantAppInstallerComponent(ComponentName component) {
24673            synchronized (mPackages) {
24674                return mInstantAppInstallerActivity != null
24675                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24676            }
24677        }
24678
24679        @Override
24680        public void pruneInstantApps() {
24681            mInstantAppRegistry.pruneInstantApps();
24682        }
24683
24684        @Override
24685        public String getSetupWizardPackageName() {
24686            return mSetupWizardPackage;
24687        }
24688
24689        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24690            if (policy != null) {
24691                mExternalSourcesPolicy = policy;
24692            }
24693        }
24694
24695        @Override
24696        public boolean isPackagePersistent(String packageName) {
24697            synchronized (mPackages) {
24698                PackageParser.Package pkg = mPackages.get(packageName);
24699                return pkg != null
24700                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24701                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24702                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24703                        : false;
24704            }
24705        }
24706
24707        @Override
24708        public List<PackageInfo> getOverlayPackages(int userId) {
24709            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24710            synchronized (mPackages) {
24711                for (PackageParser.Package p : mPackages.values()) {
24712                    if (p.mOverlayTarget != null) {
24713                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24714                        if (pkg != null) {
24715                            overlayPackages.add(pkg);
24716                        }
24717                    }
24718                }
24719            }
24720            return overlayPackages;
24721        }
24722
24723        @Override
24724        public List<String> getTargetPackageNames(int userId) {
24725            List<String> targetPackages = new ArrayList<>();
24726            synchronized (mPackages) {
24727                for (PackageParser.Package p : mPackages.values()) {
24728                    if (p.mOverlayTarget == null) {
24729                        targetPackages.add(p.packageName);
24730                    }
24731                }
24732            }
24733            return targetPackages;
24734        }
24735
24736        @Override
24737        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24738                @Nullable List<String> overlayPackageNames) {
24739            synchronized (mPackages) {
24740                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24741                    Slog.e(TAG, "failed to find package " + targetPackageName);
24742                    return false;
24743                }
24744
24745                ArrayList<String> paths = null;
24746                if (overlayPackageNames != null) {
24747                    final int N = overlayPackageNames.size();
24748                    paths = new ArrayList<>(N);
24749                    for (int i = 0; i < N; i++) {
24750                        final String packageName = overlayPackageNames.get(i);
24751                        final PackageParser.Package pkg = mPackages.get(packageName);
24752                        if (pkg == null) {
24753                            Slog.e(TAG, "failed to find package " + packageName);
24754                            return false;
24755                        }
24756                        paths.add(pkg.baseCodePath);
24757                    }
24758                }
24759
24760                ArrayMap<String, ArrayList<String>> userSpecificOverlays =
24761                    mEnabledOverlayPaths.get(userId);
24762                if (userSpecificOverlays == null) {
24763                    userSpecificOverlays = new ArrayMap<>();
24764                    mEnabledOverlayPaths.put(userId, userSpecificOverlays);
24765                }
24766
24767                if (paths != null && paths.size() > 0) {
24768                    userSpecificOverlays.put(targetPackageName, paths);
24769                } else {
24770                    userSpecificOverlays.remove(targetPackageName);
24771                }
24772                return true;
24773            }
24774        }
24775
24776        @Override
24777        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24778                int flags, int userId) {
24779            return resolveIntentInternal(
24780                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
24781        }
24782
24783        @Override
24784        public ResolveInfo resolveService(Intent intent, String resolvedType,
24785                int flags, int userId, int callingUid) {
24786            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24787        }
24788
24789        @Override
24790        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24791            synchronized (mPackages) {
24792                mIsolatedOwners.put(isolatedUid, ownerUid);
24793            }
24794        }
24795
24796        @Override
24797        public void removeIsolatedUid(int isolatedUid) {
24798            synchronized (mPackages) {
24799                mIsolatedOwners.delete(isolatedUid);
24800            }
24801        }
24802
24803        @Override
24804        public int getUidTargetSdkVersion(int uid) {
24805            synchronized (mPackages) {
24806                return getUidTargetSdkVersionLockedLPr(uid);
24807            }
24808        }
24809
24810        @Override
24811        public boolean canAccessInstantApps(int callingUid, int userId) {
24812            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24813        }
24814    }
24815
24816    @Override
24817    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24818        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24819        synchronized (mPackages) {
24820            final long identity = Binder.clearCallingIdentity();
24821            try {
24822                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
24823                        packageNames, userId);
24824            } finally {
24825                Binder.restoreCallingIdentity(identity);
24826            }
24827        }
24828    }
24829
24830    @Override
24831    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24832        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24833        synchronized (mPackages) {
24834            final long identity = Binder.clearCallingIdentity();
24835            try {
24836                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
24837                        packageNames, userId);
24838            } finally {
24839                Binder.restoreCallingIdentity(identity);
24840            }
24841        }
24842    }
24843
24844    private static void enforceSystemOrPhoneCaller(String tag) {
24845        int callingUid = Binder.getCallingUid();
24846        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24847            throw new SecurityException(
24848                    "Cannot call " + tag + " from UID " + callingUid);
24849        }
24850    }
24851
24852    boolean isHistoricalPackageUsageAvailable() {
24853        return mPackageUsage.isHistoricalPackageUsageAvailable();
24854    }
24855
24856    /**
24857     * Return a <b>copy</b> of the collection of packages known to the package manager.
24858     * @return A copy of the values of mPackages.
24859     */
24860    Collection<PackageParser.Package> getPackages() {
24861        synchronized (mPackages) {
24862            return new ArrayList<>(mPackages.values());
24863        }
24864    }
24865
24866    /**
24867     * Logs process start information (including base APK hash) to the security log.
24868     * @hide
24869     */
24870    @Override
24871    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24872            String apkFile, int pid) {
24873        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24874            return;
24875        }
24876        if (!SecurityLog.isLoggingEnabled()) {
24877            return;
24878        }
24879        Bundle data = new Bundle();
24880        data.putLong("startTimestamp", System.currentTimeMillis());
24881        data.putString("processName", processName);
24882        data.putInt("uid", uid);
24883        data.putString("seinfo", seinfo);
24884        data.putString("apkFile", apkFile);
24885        data.putInt("pid", pid);
24886        Message msg = mProcessLoggingHandler.obtainMessage(
24887                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24888        msg.setData(data);
24889        mProcessLoggingHandler.sendMessage(msg);
24890    }
24891
24892    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24893        return mCompilerStats.getPackageStats(pkgName);
24894    }
24895
24896    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24897        return getOrCreateCompilerPackageStats(pkg.packageName);
24898    }
24899
24900    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24901        return mCompilerStats.getOrCreatePackageStats(pkgName);
24902    }
24903
24904    public void deleteCompilerPackageStats(String pkgName) {
24905        mCompilerStats.deletePackageStats(pkgName);
24906    }
24907
24908    @Override
24909    public int getInstallReason(String packageName, int userId) {
24910        final int callingUid = Binder.getCallingUid();
24911        enforceCrossUserPermission(callingUid, userId,
24912                true /* requireFullPermission */, false /* checkShell */,
24913                "get install reason");
24914        synchronized (mPackages) {
24915            final PackageSetting ps = mSettings.mPackages.get(packageName);
24916            if (filterAppAccessLPr(ps, callingUid, userId)) {
24917                return PackageManager.INSTALL_REASON_UNKNOWN;
24918            }
24919            if (ps != null) {
24920                return ps.getInstallReason(userId);
24921            }
24922        }
24923        return PackageManager.INSTALL_REASON_UNKNOWN;
24924    }
24925
24926    @Override
24927    public boolean canRequestPackageInstalls(String packageName, int userId) {
24928        return canRequestPackageInstallsInternal(packageName, 0, userId,
24929                true /* throwIfPermNotDeclared*/);
24930    }
24931
24932    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24933            boolean throwIfPermNotDeclared) {
24934        int callingUid = Binder.getCallingUid();
24935        int uid = getPackageUid(packageName, 0, userId);
24936        if (callingUid != uid && callingUid != Process.ROOT_UID
24937                && callingUid != Process.SYSTEM_UID) {
24938            throw new SecurityException(
24939                    "Caller uid " + callingUid + " does not own package " + packageName);
24940        }
24941        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24942        if (info == null) {
24943            return false;
24944        }
24945        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24946            return false;
24947        }
24948        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24949        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24950        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24951            if (throwIfPermNotDeclared) {
24952                throw new SecurityException("Need to declare " + appOpPermission
24953                        + " to call this api");
24954            } else {
24955                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24956                return false;
24957            }
24958        }
24959        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24960            return false;
24961        }
24962        if (mExternalSourcesPolicy != null) {
24963            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24964            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24965                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24966            }
24967        }
24968        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24969    }
24970
24971    @Override
24972    public ComponentName getInstantAppResolverSettingsComponent() {
24973        return mInstantAppResolverSettingsComponent;
24974    }
24975
24976    @Override
24977    public ComponentName getInstantAppInstallerComponent() {
24978        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24979            return null;
24980        }
24981        return mInstantAppInstallerActivity == null
24982                ? null : mInstantAppInstallerActivity.getComponentName();
24983    }
24984
24985    @Override
24986    public String getInstantAppAndroidId(String packageName, int userId) {
24987        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24988                "getInstantAppAndroidId");
24989        enforceCrossUserPermission(Binder.getCallingUid(), userId,
24990                true /* requireFullPermission */, false /* checkShell */,
24991                "getInstantAppAndroidId");
24992        // Make sure the target is an Instant App.
24993        if (!isInstantApp(packageName, userId)) {
24994            return null;
24995        }
24996        synchronized (mPackages) {
24997            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24998        }
24999    }
25000}
25001
25002interface PackageSender {
25003    void sendPackageBroadcast(final String action, final String pkg,
25004        final Bundle extras, final int flags, final String targetPkg,
25005        final IIntentReceiver finishedReceiver, final int[] userIds);
25006    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
25007        int appId, int... userIds);
25008}
25009