PackageManagerService.java revision e3b676763f0889c3f3202ca7dab94f927a24ad1f
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.NonNull;
107import android.annotation.Nullable;
108import android.app.ActivityManager;
109import android.app.AppOpsManager;
110import android.app.IActivityManager;
111import android.app.ResourcesManager;
112import android.app.admin.IDevicePolicyManager;
113import android.app.admin.SecurityLog;
114import android.app.backup.IBackupManager;
115import android.content.BroadcastReceiver;
116import android.content.ComponentName;
117import android.content.ContentResolver;
118import android.content.Context;
119import android.content.IIntentReceiver;
120import android.content.Intent;
121import android.content.IntentFilter;
122import android.content.IntentSender;
123import android.content.IntentSender.SendIntentException;
124import android.content.ServiceConnection;
125import android.content.pm.ActivityInfo;
126import android.content.pm.ApplicationInfo;
127import android.content.pm.AppsQueryHelper;
128import android.content.pm.AuxiliaryResolveInfo;
129import android.content.pm.ChangedPackages;
130import android.content.pm.FallbackCategoryProvider;
131import android.content.pm.FeatureInfo;
132import android.content.pm.IDexModuleRegisterCallback;
133import android.content.pm.IOnPermissionsChangeListener;
134import android.content.pm.IPackageDataObserver;
135import android.content.pm.IPackageDeleteObserver;
136import android.content.pm.IPackageDeleteObserver2;
137import android.content.pm.IPackageInstallObserver2;
138import android.content.pm.IPackageInstaller;
139import android.content.pm.IPackageManager;
140import android.content.pm.IPackageMoveObserver;
141import android.content.pm.IPackageStatsObserver;
142import android.content.pm.InstantAppInfo;
143import android.content.pm.InstantAppRequest;
144import android.content.pm.InstantAppResolveInfo;
145import android.content.pm.InstrumentationInfo;
146import android.content.pm.IntentFilterVerificationInfo;
147import android.content.pm.KeySet;
148import android.content.pm.PackageCleanItem;
149import android.content.pm.PackageInfo;
150import android.content.pm.PackageInfoLite;
151import android.content.pm.PackageInstaller;
152import android.content.pm.PackageManager;
153import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
154import android.content.pm.PackageManagerInternal;
155import android.content.pm.PackageParser;
156import android.content.pm.PackageParser.ActivityIntentInfo;
157import android.content.pm.PackageParser.PackageLite;
158import android.content.pm.PackageParser.PackageParserException;
159import android.content.pm.PackageStats;
160import android.content.pm.PackageUserState;
161import android.content.pm.ParceledListSlice;
162import android.content.pm.PermissionGroupInfo;
163import android.content.pm.PermissionInfo;
164import android.content.pm.ProviderInfo;
165import android.content.pm.ResolveInfo;
166import android.content.pm.ServiceInfo;
167import android.content.pm.SharedLibraryInfo;
168import android.content.pm.Signature;
169import android.content.pm.UserInfo;
170import android.content.pm.VerifierDeviceIdentity;
171import android.content.pm.VerifierInfo;
172import android.content.pm.VersionedPackage;
173import android.content.res.Resources;
174import android.database.ContentObserver;
175import android.graphics.Bitmap;
176import android.hardware.display.DisplayManager;
177import android.net.Uri;
178import android.os.Binder;
179import android.os.Build;
180import android.os.Bundle;
181import android.os.Debug;
182import android.os.Environment;
183import android.os.Environment.UserEnvironment;
184import android.os.FileUtils;
185import android.os.Handler;
186import android.os.IBinder;
187import android.os.Looper;
188import android.os.Message;
189import android.os.Parcel;
190import android.os.ParcelFileDescriptor;
191import android.os.PatternMatcher;
192import android.os.Process;
193import android.os.RemoteCallbackList;
194import android.os.RemoteException;
195import android.os.ResultReceiver;
196import android.os.SELinux;
197import android.os.ServiceManager;
198import android.os.ShellCallback;
199import android.os.SystemClock;
200import android.os.SystemProperties;
201import android.os.Trace;
202import android.os.UserHandle;
203import android.os.UserManager;
204import android.os.UserManagerInternal;
205import android.os.storage.IStorageManager;
206import android.os.storage.StorageEventListener;
207import android.os.storage.StorageManager;
208import android.os.storage.StorageManagerInternal;
209import android.os.storage.VolumeInfo;
210import android.os.storage.VolumeRecord;
211import android.provider.Settings.Global;
212import android.provider.Settings.Secure;
213import android.security.KeyStore;
214import android.security.SystemKeyStore;
215import android.service.pm.PackageServiceDumpProto;
216import android.system.ErrnoException;
217import android.system.Os;
218import android.text.TextUtils;
219import android.text.format.DateUtils;
220import android.util.ArrayMap;
221import android.util.ArraySet;
222import android.util.Base64;
223import android.util.BootTimingsTraceLog;
224import android.util.DisplayMetrics;
225import android.util.EventLog;
226import android.util.ExceptionUtils;
227import android.util.Log;
228import android.util.LogPrinter;
229import android.util.MathUtils;
230import android.util.PackageUtils;
231import android.util.Pair;
232import android.util.PrintStreamPrinter;
233import android.util.Slog;
234import android.util.SparseArray;
235import android.util.SparseBooleanArray;
236import android.util.SparseIntArray;
237import android.util.Xml;
238import android.util.jar.StrictJarFile;
239import android.util.proto.ProtoOutputStream;
240import android.view.Display;
241
242import com.android.internal.R;
243import com.android.internal.annotations.GuardedBy;
244import com.android.internal.app.IMediaContainerService;
245import com.android.internal.app.ResolverActivity;
246import com.android.internal.content.NativeLibraryHelper;
247import com.android.internal.content.PackageHelper;
248import com.android.internal.logging.MetricsLogger;
249import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
250import com.android.internal.os.IParcelFileDescriptorFactory;
251import com.android.internal.os.RoSystemProperties;
252import com.android.internal.os.SomeArgs;
253import com.android.internal.os.Zygote;
254import com.android.internal.telephony.CarrierAppUtils;
255import com.android.internal.util.ArrayUtils;
256import com.android.internal.util.ConcurrentUtils;
257import com.android.internal.util.DumpUtils;
258import com.android.internal.util.FastPrintWriter;
259import com.android.internal.util.FastXmlSerializer;
260import com.android.internal.util.IndentingPrintWriter;
261import com.android.internal.util.Preconditions;
262import com.android.internal.util.XmlUtils;
263import com.android.server.AttributeCache;
264import com.android.server.DeviceIdleController;
265import com.android.server.EventLogTags;
266import com.android.server.FgThread;
267import com.android.server.IntentResolver;
268import com.android.server.LocalServices;
269import com.android.server.LockGuard;
270import com.android.server.ServiceThread;
271import com.android.server.SystemConfig;
272import com.android.server.SystemServerInitThreadPool;
273import com.android.server.Watchdog;
274import com.android.server.net.NetworkPolicyManagerInternal;
275import com.android.server.pm.Installer.InstallerException;
276import com.android.server.pm.PermissionsState.PermissionState;
277import com.android.server.pm.Settings.DatabaseVersion;
278import com.android.server.pm.Settings.VersionInfo;
279import com.android.server.pm.dex.DexManager;
280import com.android.server.storage.DeviceStorageMonitorInternal;
281
282import dalvik.system.CloseGuard;
283import dalvik.system.DexFile;
284import dalvik.system.VMRuntime;
285
286import libcore.io.IoUtils;
287import libcore.util.EmptyArray;
288
289import org.xmlpull.v1.XmlPullParser;
290import org.xmlpull.v1.XmlPullParserException;
291import org.xmlpull.v1.XmlSerializer;
292
293import java.io.BufferedOutputStream;
294import java.io.BufferedReader;
295import java.io.ByteArrayInputStream;
296import java.io.ByteArrayOutputStream;
297import java.io.File;
298import java.io.FileDescriptor;
299import java.io.FileInputStream;
300import java.io.FileOutputStream;
301import java.io.FileReader;
302import java.io.FilenameFilter;
303import java.io.IOException;
304import java.io.PrintWriter;
305import java.nio.charset.StandardCharsets;
306import java.security.DigestInputStream;
307import java.security.MessageDigest;
308import java.security.NoSuchAlgorithmException;
309import java.security.PublicKey;
310import java.security.SecureRandom;
311import java.security.cert.Certificate;
312import java.security.cert.CertificateEncodingException;
313import java.security.cert.CertificateException;
314import java.text.SimpleDateFormat;
315import java.util.ArrayList;
316import java.util.Arrays;
317import java.util.Collection;
318import java.util.Collections;
319import java.util.Comparator;
320import java.util.Date;
321import java.util.HashMap;
322import java.util.HashSet;
323import java.util.Iterator;
324import java.util.List;
325import java.util.Map;
326import java.util.Objects;
327import java.util.Set;
328import java.util.concurrent.CountDownLatch;
329import java.util.concurrent.Future;
330import java.util.concurrent.TimeUnit;
331import java.util.concurrent.atomic.AtomicBoolean;
332import java.util.concurrent.atomic.AtomicInteger;
333
334/**
335 * Keep track of all those APKs everywhere.
336 * <p>
337 * Internally there are two important locks:
338 * <ul>
339 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
340 * and other related state. It is a fine-grained lock that should only be held
341 * momentarily, as it's one of the most contended locks in the system.
342 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
343 * operations typically involve heavy lifting of application data on disk. Since
344 * {@code installd} is single-threaded, and it's operations can often be slow,
345 * this lock should never be acquired while already holding {@link #mPackages}.
346 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
347 * holding {@link #mInstallLock}.
348 * </ul>
349 * Many internal methods rely on the caller to hold the appropriate locks, and
350 * this contract is expressed through method name suffixes:
351 * <ul>
352 * <li>fooLI(): the caller must hold {@link #mInstallLock}
353 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
354 * being modified must be frozen
355 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
356 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
357 * </ul>
358 * <p>
359 * Because this class is very central to the platform's security; please run all
360 * CTS and unit tests whenever making modifications:
361 *
362 * <pre>
363 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
364 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
365 * </pre>
366 */
367public class PackageManagerService extends IPackageManager.Stub
368        implements PackageSender {
369    static final String TAG = "PackageManager";
370    static final boolean DEBUG_SETTINGS = false;
371    static final boolean DEBUG_PREFERRED = false;
372    static final boolean DEBUG_UPGRADE = false;
373    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
374    private static final boolean DEBUG_BACKUP = false;
375    private static final boolean DEBUG_INSTALL = false;
376    private static final boolean DEBUG_REMOVE = false;
377    private static final boolean DEBUG_BROADCASTS = false;
378    private static final boolean DEBUG_SHOW_INFO = false;
379    private static final boolean DEBUG_PACKAGE_INFO = false;
380    private static final boolean DEBUG_INTENT_MATCHING = false;
381    private static final boolean DEBUG_PACKAGE_SCANNING = false;
382    private static final boolean DEBUG_VERIFY = false;
383    private static final boolean DEBUG_FILTERS = false;
384    private static final boolean DEBUG_PERMISSIONS = false;
385    private static final boolean DEBUG_SHARED_LIBRARIES = false;
386
387    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
388    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
389    // user, but by default initialize to this.
390    public static final boolean DEBUG_DEXOPT = false;
391
392    private static final boolean DEBUG_ABI_SELECTION = false;
393    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
394    private static final boolean DEBUG_TRIAGED_MISSING = false;
395    private static final boolean DEBUG_APP_DATA = false;
396
397    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
398    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
399
400    private static final boolean HIDE_EPHEMERAL_APIS = false;
401
402    private static final boolean ENABLE_FREE_CACHE_V2 =
403            SystemProperties.getBoolean("fw.free_cache_v2", true);
404
405    private static final int RADIO_UID = Process.PHONE_UID;
406    private static final int LOG_UID = Process.LOG_UID;
407    private static final int NFC_UID = Process.NFC_UID;
408    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
409    private static final int SHELL_UID = Process.SHELL_UID;
410
411    // Cap the size of permission trees that 3rd party apps can define
412    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
413
414    // Suffix used during package installation when copying/moving
415    // package apks to install directory.
416    private static final String INSTALL_PACKAGE_SUFFIX = "-";
417
418    static final int SCAN_NO_DEX = 1<<1;
419    static final int SCAN_FORCE_DEX = 1<<2;
420    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
421    static final int SCAN_NEW_INSTALL = 1<<4;
422    static final int SCAN_UPDATE_TIME = 1<<5;
423    static final int SCAN_BOOTING = 1<<6;
424    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
425    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
426    static final int SCAN_REPLACING = 1<<9;
427    static final int SCAN_REQUIRE_KNOWN = 1<<10;
428    static final int SCAN_MOVE = 1<<11;
429    static final int SCAN_INITIAL = 1<<12;
430    static final int SCAN_CHECK_ONLY = 1<<13;
431    static final int SCAN_DONT_KILL_APP = 1<<14;
432    static final int SCAN_IGNORE_FROZEN = 1<<15;
433    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
434    static final int SCAN_AS_INSTANT_APP = 1<<17;
435    static final int SCAN_AS_FULL_APP = 1<<18;
436    /** Should not be with the scan flags */
437    static final int FLAGS_REMOVE_CHATTY = 1<<31;
438
439    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
440
441    private static final int[] EMPTY_INT_ARRAY = new int[0];
442
443    /**
444     * Timeout (in milliseconds) after which the watchdog should declare that
445     * our handler thread is wedged.  The usual default for such things is one
446     * minute but we sometimes do very lengthy I/O operations on this thread,
447     * such as installing multi-gigabyte applications, so ours needs to be longer.
448     */
449    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
450
451    /**
452     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
453     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
454     * settings entry if available, otherwise we use the hardcoded default.  If it's been
455     * more than this long since the last fstrim, we force one during the boot sequence.
456     *
457     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
458     * one gets run at the next available charging+idle time.  This final mandatory
459     * no-fstrim check kicks in only of the other scheduling criteria is never met.
460     */
461    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
462
463    /**
464     * Whether verification is enabled by default.
465     */
466    private static final boolean DEFAULT_VERIFY_ENABLE = true;
467
468    /**
469     * The default maximum time to wait for the verification agent to return in
470     * milliseconds.
471     */
472    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
473
474    /**
475     * The default response for package verification timeout.
476     *
477     * This can be either PackageManager.VERIFICATION_ALLOW or
478     * PackageManager.VERIFICATION_REJECT.
479     */
480    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
481
482    static final String PLATFORM_PACKAGE_NAME = "android";
483
484    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
485
486    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
487            DEFAULT_CONTAINER_PACKAGE,
488            "com.android.defcontainer.DefaultContainerService");
489
490    private static final String KILL_APP_REASON_GIDS_CHANGED =
491            "permission grant or revoke changed gids";
492
493    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
494            "permissions revoked";
495
496    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
497
498    private static final String PACKAGE_SCHEME = "package";
499
500    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
501
502    /** Permission grant: not grant the permission. */
503    private static final int GRANT_DENIED = 1;
504
505    /** Permission grant: grant the permission as an install permission. */
506    private static final int GRANT_INSTALL = 2;
507
508    /** Permission grant: grant the permission as a runtime one. */
509    private static final int GRANT_RUNTIME = 3;
510
511    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
512    private static final int GRANT_UPGRADE = 4;
513
514    /** Canonical intent used to identify what counts as a "web browser" app */
515    private static final Intent sBrowserIntent;
516    static {
517        sBrowserIntent = new Intent();
518        sBrowserIntent.setAction(Intent.ACTION_VIEW);
519        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
520        sBrowserIntent.setData(Uri.parse("http:"));
521    }
522
523    /**
524     * The set of all protected actions [i.e. those actions for which a high priority
525     * intent filter is disallowed].
526     */
527    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
528    static {
529        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
530        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
531        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
532        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
533    }
534
535    // Compilation reasons.
536    public static final int REASON_FIRST_BOOT = 0;
537    public static final int REASON_BOOT = 1;
538    public static final int REASON_INSTALL = 2;
539    public static final int REASON_BACKGROUND_DEXOPT = 3;
540    public static final int REASON_AB_OTA = 4;
541
542    public static final int REASON_LAST = REASON_AB_OTA;
543
544    /** All dangerous permission names in the same order as the events in MetricsEvent */
545    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
546            Manifest.permission.READ_CALENDAR,
547            Manifest.permission.WRITE_CALENDAR,
548            Manifest.permission.CAMERA,
549            Manifest.permission.READ_CONTACTS,
550            Manifest.permission.WRITE_CONTACTS,
551            Manifest.permission.GET_ACCOUNTS,
552            Manifest.permission.ACCESS_FINE_LOCATION,
553            Manifest.permission.ACCESS_COARSE_LOCATION,
554            Manifest.permission.RECORD_AUDIO,
555            Manifest.permission.READ_PHONE_STATE,
556            Manifest.permission.CALL_PHONE,
557            Manifest.permission.READ_CALL_LOG,
558            Manifest.permission.WRITE_CALL_LOG,
559            Manifest.permission.ADD_VOICEMAIL,
560            Manifest.permission.USE_SIP,
561            Manifest.permission.PROCESS_OUTGOING_CALLS,
562            Manifest.permission.READ_CELL_BROADCASTS,
563            Manifest.permission.BODY_SENSORS,
564            Manifest.permission.SEND_SMS,
565            Manifest.permission.RECEIVE_SMS,
566            Manifest.permission.READ_SMS,
567            Manifest.permission.RECEIVE_WAP_PUSH,
568            Manifest.permission.RECEIVE_MMS,
569            Manifest.permission.READ_EXTERNAL_STORAGE,
570            Manifest.permission.WRITE_EXTERNAL_STORAGE,
571            Manifest.permission.READ_PHONE_NUMBERS,
572            Manifest.permission.ANSWER_PHONE_CALLS);
573
574
575    /**
576     * Version number for the package parser cache. Increment this whenever the format or
577     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
578     */
579    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
580
581    /**
582     * Whether the package parser cache is enabled.
583     */
584    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
585
586    final ServiceThread mHandlerThread;
587
588    final PackageHandler mHandler;
589
590    private final ProcessLoggingHandler mProcessLoggingHandler;
591
592    /**
593     * Messages for {@link #mHandler} that need to wait for system ready before
594     * being dispatched.
595     */
596    private ArrayList<Message> mPostSystemReadyMessages;
597
598    final int mSdkVersion = Build.VERSION.SDK_INT;
599
600    final Context mContext;
601    final boolean mFactoryTest;
602    final boolean mOnlyCore;
603    final DisplayMetrics mMetrics;
604    final int mDefParseFlags;
605    final String[] mSeparateProcesses;
606    final boolean mIsUpgrade;
607    final boolean mIsPreNUpgrade;
608    final boolean mIsPreNMR1Upgrade;
609
610    // Have we told the Activity Manager to whitelist the default container service by uid yet?
611    @GuardedBy("mPackages")
612    boolean mDefaultContainerWhitelisted = false;
613
614    @GuardedBy("mPackages")
615    private boolean mDexOptDialogShown;
616
617    /** The location for ASEC container files on internal storage. */
618    final String mAsecInternalPath;
619
620    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
621    // LOCK HELD.  Can be called with mInstallLock held.
622    @GuardedBy("mInstallLock")
623    final Installer mInstaller;
624
625    /** Directory where installed third-party apps stored */
626    final File mAppInstallDir;
627
628    /**
629     * Directory to which applications installed internally have their
630     * 32 bit native libraries copied.
631     */
632    private File mAppLib32InstallDir;
633
634    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
635    // apps.
636    final File mDrmAppPrivateInstallDir;
637
638    // ----------------------------------------------------------------
639
640    // Lock for state used when installing and doing other long running
641    // operations.  Methods that must be called with this lock held have
642    // the suffix "LI".
643    final Object mInstallLock = new Object();
644
645    // ----------------------------------------------------------------
646
647    // Keys are String (package name), values are Package.  This also serves
648    // as the lock for the global state.  Methods that must be called with
649    // this lock held have the prefix "LP".
650    @GuardedBy("mPackages")
651    final ArrayMap<String, PackageParser.Package> mPackages =
652            new ArrayMap<String, PackageParser.Package>();
653
654    final ArrayMap<String, Set<String>> mKnownCodebase =
655            new ArrayMap<String, Set<String>>();
656
657    // Keys are isolated uids and values are the uid of the application
658    // that created the isolated proccess.
659    @GuardedBy("mPackages")
660    final SparseIntArray mIsolatedOwners = new SparseIntArray();
661
662    // List of APK paths to load for each user and package. This data is never
663    // persisted by the package manager. Instead, the overlay manager will
664    // ensure the data is up-to-date in runtime.
665    @GuardedBy("mPackages")
666    final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths =
667        new SparseArray<ArrayMap<String, ArrayList<String>>>();
668
669    /**
670     * Tracks new system packages [received in an OTA] that we expect to
671     * find updated user-installed versions. Keys are package name, values
672     * are package location.
673     */
674    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
675    /**
676     * Tracks high priority intent filters for protected actions. During boot, certain
677     * filter actions are protected and should never be allowed to have a high priority
678     * intent filter for them. However, there is one, and only one exception -- the
679     * setup wizard. It must be able to define a high priority intent filter for these
680     * actions to ensure there are no escapes from the wizard. We need to delay processing
681     * of these during boot as we need to look at all of the system packages in order
682     * to know which component is the setup wizard.
683     */
684    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
685    /**
686     * Whether or not processing protected filters should be deferred.
687     */
688    private boolean mDeferProtectedFilters = true;
689
690    /**
691     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
692     */
693    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
694    /**
695     * Whether or not system app permissions should be promoted from install to runtime.
696     */
697    boolean mPromoteSystemApps;
698
699    @GuardedBy("mPackages")
700    final Settings mSettings;
701
702    /**
703     * Set of package names that are currently "frozen", which means active
704     * surgery is being done on the code/data for that package. The platform
705     * will refuse to launch frozen packages to avoid race conditions.
706     *
707     * @see PackageFreezer
708     */
709    @GuardedBy("mPackages")
710    final ArraySet<String> mFrozenPackages = new ArraySet<>();
711
712    final ProtectedPackages mProtectedPackages;
713
714    boolean mFirstBoot;
715
716    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
717
718    // System configuration read by SystemConfig.
719    final int[] mGlobalGids;
720    final SparseArray<ArraySet<String>> mSystemPermissions;
721    @GuardedBy("mAvailableFeatures")
722    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
723
724    // If mac_permissions.xml was found for seinfo labeling.
725    boolean mFoundPolicyFile;
726
727    private final InstantAppRegistry mInstantAppRegistry;
728
729    @GuardedBy("mPackages")
730    int mChangedPackagesSequenceNumber;
731    /**
732     * List of changed [installed, removed or updated] packages.
733     * mapping from user id -> sequence number -> package name
734     */
735    @GuardedBy("mPackages")
736    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
737    /**
738     * The sequence number of the last change to a package.
739     * mapping from user id -> package name -> sequence number
740     */
741    @GuardedBy("mPackages")
742    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
743
744    class PackageParserCallback implements PackageParser.Callback {
745        @Override public final boolean hasFeature(String feature) {
746            return PackageManagerService.this.hasSystemFeature(feature, 0);
747        }
748
749        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
750                Collection<PackageParser.Package> allPackages, String targetPackageName) {
751            List<PackageParser.Package> overlayPackages = null;
752            for (PackageParser.Package p : allPackages) {
753                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
754                    if (overlayPackages == null) {
755                        overlayPackages = new ArrayList<PackageParser.Package>();
756                    }
757                    overlayPackages.add(p);
758                }
759            }
760            if (overlayPackages != null) {
761                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
762                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
763                        return p1.mOverlayPriority - p2.mOverlayPriority;
764                    }
765                };
766                Collections.sort(overlayPackages, cmp);
767            }
768            return overlayPackages;
769        }
770
771        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
772                String targetPackageName, String targetPath) {
773            if ("android".equals(targetPackageName)) {
774                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
775                // native AssetManager.
776                return null;
777            }
778            List<PackageParser.Package> overlayPackages =
779                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
780            if (overlayPackages == null || overlayPackages.isEmpty()) {
781                return null;
782            }
783            List<String> overlayPathList = null;
784            for (PackageParser.Package overlayPackage : overlayPackages) {
785                if (targetPath == null) {
786                    if (overlayPathList == null) {
787                        overlayPathList = new ArrayList<String>();
788                    }
789                    overlayPathList.add(overlayPackage.baseCodePath);
790                    continue;
791                }
792
793                try {
794                    // Creates idmaps for system to parse correctly the Android manifest of the
795                    // target package.
796                    //
797                    // OverlayManagerService will update each of them with a correct gid from its
798                    // target package app id.
799                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
800                            UserHandle.getSharedAppGid(
801                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
802                    if (overlayPathList == null) {
803                        overlayPathList = new ArrayList<String>();
804                    }
805                    overlayPathList.add(overlayPackage.baseCodePath);
806                } catch (InstallerException e) {
807                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
808                            overlayPackage.baseCodePath);
809                }
810            }
811            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
812        }
813
814        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
815            synchronized (mPackages) {
816                return getStaticOverlayPathsLocked(
817                        mPackages.values(), targetPackageName, targetPath);
818            }
819        }
820
821        @Override public final String[] getOverlayApks(String targetPackageName) {
822            return getStaticOverlayPaths(targetPackageName, null);
823        }
824
825        @Override public final String[] getOverlayPaths(String targetPackageName,
826                String targetPath) {
827            return getStaticOverlayPaths(targetPackageName, targetPath);
828        }
829    };
830
831    class ParallelPackageParserCallback extends PackageParserCallback {
832        List<PackageParser.Package> mOverlayPackages = null;
833
834        void findStaticOverlayPackages() {
835            synchronized (mPackages) {
836                for (PackageParser.Package p : mPackages.values()) {
837                    if (p.mIsStaticOverlay) {
838                        if (mOverlayPackages == null) {
839                            mOverlayPackages = new ArrayList<PackageParser.Package>();
840                        }
841                        mOverlayPackages.add(p);
842                    }
843                }
844            }
845        }
846
847        @Override
848        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
849            // We can trust mOverlayPackages without holding mPackages because package uninstall
850            // can't happen while running parallel parsing.
851            // Moreover holding mPackages on each parsing thread causes dead-lock.
852            return mOverlayPackages == null ? null :
853                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
854        }
855    }
856
857    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
858    final ParallelPackageParserCallback mParallelPackageParserCallback =
859            new ParallelPackageParserCallback();
860
861    public static final class SharedLibraryEntry {
862        public final String path;
863        public final String apk;
864        public final SharedLibraryInfo info;
865
866        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
867                String declaringPackageName, int declaringPackageVersionCode) {
868            path = _path;
869            apk = _apk;
870            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
871                    declaringPackageName, declaringPackageVersionCode), null);
872        }
873    }
874
875    // Currently known shared libraries.
876    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
877    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
878            new ArrayMap<>();
879
880    // All available activities, for your resolving pleasure.
881    final ActivityIntentResolver mActivities =
882            new ActivityIntentResolver();
883
884    // All available receivers, for your resolving pleasure.
885    final ActivityIntentResolver mReceivers =
886            new ActivityIntentResolver();
887
888    // All available services, for your resolving pleasure.
889    final ServiceIntentResolver mServices = new ServiceIntentResolver();
890
891    // All available providers, for your resolving pleasure.
892    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
893
894    // Mapping from provider base names (first directory in content URI codePath)
895    // to the provider information.
896    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
897            new ArrayMap<String, PackageParser.Provider>();
898
899    // Mapping from instrumentation class names to info about them.
900    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
901            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
902
903    // Mapping from permission names to info about them.
904    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
905            new ArrayMap<String, PackageParser.PermissionGroup>();
906
907    // Packages whose data we have transfered into another package, thus
908    // should no longer exist.
909    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
910
911    // Broadcast actions that are only available to the system.
912    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
913
914    /** List of packages waiting for verification. */
915    final SparseArray<PackageVerificationState> mPendingVerification
916            = new SparseArray<PackageVerificationState>();
917
918    /** Set of packages associated with each app op permission. */
919    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
920
921    final PackageInstallerService mInstallerService;
922
923    private final PackageDexOptimizer mPackageDexOptimizer;
924    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
925    // is used by other apps).
926    private final DexManager mDexManager;
927
928    private AtomicInteger mNextMoveId = new AtomicInteger();
929    private final MoveCallbacks mMoveCallbacks;
930
931    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
932
933    // Cache of users who need badging.
934    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
935
936    /** Token for keys in mPendingVerification. */
937    private int mPendingVerificationToken = 0;
938
939    volatile boolean mSystemReady;
940    volatile boolean mSafeMode;
941    volatile boolean mHasSystemUidErrors;
942    private volatile boolean mEphemeralAppsDisabled;
943
944    ApplicationInfo mAndroidApplication;
945    final ActivityInfo mResolveActivity = new ActivityInfo();
946    final ResolveInfo mResolveInfo = new ResolveInfo();
947    ComponentName mResolveComponentName;
948    PackageParser.Package mPlatformPackage;
949    ComponentName mCustomResolverComponentName;
950
951    boolean mResolverReplaced = false;
952
953    private final @Nullable ComponentName mIntentFilterVerifierComponent;
954    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
955
956    private int mIntentFilterVerificationToken = 0;
957
958    /** The service connection to the ephemeral resolver */
959    final EphemeralResolverConnection mInstantAppResolverConnection;
960    /** Component used to show resolver settings for Instant Apps */
961    final ComponentName mInstantAppResolverSettingsComponent;
962
963    /** Activity used to install instant applications */
964    ActivityInfo mInstantAppInstallerActivity;
965    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
966
967    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
968            = new SparseArray<IntentFilterVerificationState>();
969
970    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
971
972    // List of packages names to keep cached, even if they are uninstalled for all users
973    private List<String> mKeepUninstalledPackages;
974
975    private UserManagerInternal mUserManagerInternal;
976
977    private DeviceIdleController.LocalService mDeviceIdleController;
978
979    private File mCacheDir;
980
981    private ArraySet<String> mPrivappPermissionsViolations;
982
983    private Future<?> mPrepareAppDataFuture;
984
985    private static class IFVerificationParams {
986        PackageParser.Package pkg;
987        boolean replacing;
988        int userId;
989        int verifierUid;
990
991        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
992                int _userId, int _verifierUid) {
993            pkg = _pkg;
994            replacing = _replacing;
995            userId = _userId;
996            replacing = _replacing;
997            verifierUid = _verifierUid;
998        }
999    }
1000
1001    private interface IntentFilterVerifier<T extends IntentFilter> {
1002        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1003                                               T filter, String packageName);
1004        void startVerifications(int userId);
1005        void receiveVerificationResponse(int verificationId);
1006    }
1007
1008    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1009        private Context mContext;
1010        private ComponentName mIntentFilterVerifierComponent;
1011        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1012
1013        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1014            mContext = context;
1015            mIntentFilterVerifierComponent = verifierComponent;
1016        }
1017
1018        private String getDefaultScheme() {
1019            return IntentFilter.SCHEME_HTTPS;
1020        }
1021
1022        @Override
1023        public void startVerifications(int userId) {
1024            // Launch verifications requests
1025            int count = mCurrentIntentFilterVerifications.size();
1026            for (int n=0; n<count; n++) {
1027                int verificationId = mCurrentIntentFilterVerifications.get(n);
1028                final IntentFilterVerificationState ivs =
1029                        mIntentFilterVerificationStates.get(verificationId);
1030
1031                String packageName = ivs.getPackageName();
1032
1033                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1034                final int filterCount = filters.size();
1035                ArraySet<String> domainsSet = new ArraySet<>();
1036                for (int m=0; m<filterCount; m++) {
1037                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1038                    domainsSet.addAll(filter.getHostsList());
1039                }
1040                synchronized (mPackages) {
1041                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1042                            packageName, domainsSet) != null) {
1043                        scheduleWriteSettingsLocked();
1044                    }
1045                }
1046                sendVerificationRequest(userId, verificationId, ivs);
1047            }
1048            mCurrentIntentFilterVerifications.clear();
1049        }
1050
1051        private void sendVerificationRequest(int userId, int verificationId,
1052                IntentFilterVerificationState ivs) {
1053
1054            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1055            verificationIntent.putExtra(
1056                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1057                    verificationId);
1058            verificationIntent.putExtra(
1059                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1060                    getDefaultScheme());
1061            verificationIntent.putExtra(
1062                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1063                    ivs.getHostsString());
1064            verificationIntent.putExtra(
1065                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1066                    ivs.getPackageName());
1067            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1068            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1069
1070            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1071            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1072                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1073                    userId, false, "intent filter verifier");
1074
1075            UserHandle user = new UserHandle(userId);
1076            mContext.sendBroadcastAsUser(verificationIntent, user);
1077            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1078                    "Sending IntentFilter verification broadcast");
1079        }
1080
1081        public void receiveVerificationResponse(int verificationId) {
1082            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1083
1084            final boolean verified = ivs.isVerified();
1085
1086            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1087            final int count = filters.size();
1088            if (DEBUG_DOMAIN_VERIFICATION) {
1089                Slog.i(TAG, "Received verification response " + verificationId
1090                        + " for " + count + " filters, verified=" + verified);
1091            }
1092            for (int n=0; n<count; n++) {
1093                PackageParser.ActivityIntentInfo filter = filters.get(n);
1094                filter.setVerified(verified);
1095
1096                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1097                        + " verified with result:" + verified + " and hosts:"
1098                        + ivs.getHostsString());
1099            }
1100
1101            mIntentFilterVerificationStates.remove(verificationId);
1102
1103            final String packageName = ivs.getPackageName();
1104            IntentFilterVerificationInfo ivi = null;
1105
1106            synchronized (mPackages) {
1107                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1108            }
1109            if (ivi == null) {
1110                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1111                        + verificationId + " packageName:" + packageName);
1112                return;
1113            }
1114            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1115                    "Updating IntentFilterVerificationInfo for package " + packageName
1116                            +" verificationId:" + verificationId);
1117
1118            synchronized (mPackages) {
1119                if (verified) {
1120                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1121                } else {
1122                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1123                }
1124                scheduleWriteSettingsLocked();
1125
1126                final int userId = ivs.getUserId();
1127                if (userId != UserHandle.USER_ALL) {
1128                    final int userStatus =
1129                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1130
1131                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1132                    boolean needUpdate = false;
1133
1134                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1135                    // already been set by the User thru the Disambiguation dialog
1136                    switch (userStatus) {
1137                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1138                            if (verified) {
1139                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1140                            } else {
1141                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1142                            }
1143                            needUpdate = true;
1144                            break;
1145
1146                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1147                            if (verified) {
1148                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1149                                needUpdate = true;
1150                            }
1151                            break;
1152
1153                        default:
1154                            // Nothing to do
1155                    }
1156
1157                    if (needUpdate) {
1158                        mSettings.updateIntentFilterVerificationStatusLPw(
1159                                packageName, updatedStatus, userId);
1160                        scheduleWritePackageRestrictionsLocked(userId);
1161                    }
1162                }
1163            }
1164        }
1165
1166        @Override
1167        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1168                    ActivityIntentInfo filter, String packageName) {
1169            if (!hasValidDomains(filter)) {
1170                return false;
1171            }
1172            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1173            if (ivs == null) {
1174                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1175                        packageName);
1176            }
1177            if (DEBUG_DOMAIN_VERIFICATION) {
1178                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1179            }
1180            ivs.addFilter(filter);
1181            return true;
1182        }
1183
1184        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1185                int userId, int verificationId, String packageName) {
1186            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1187                    verifierUid, userId, packageName);
1188            ivs.setPendingState();
1189            synchronized (mPackages) {
1190                mIntentFilterVerificationStates.append(verificationId, ivs);
1191                mCurrentIntentFilterVerifications.add(verificationId);
1192            }
1193            return ivs;
1194        }
1195    }
1196
1197    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1198        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1199                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1200                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1201    }
1202
1203    // Set of pending broadcasts for aggregating enable/disable of components.
1204    static class PendingPackageBroadcasts {
1205        // for each user id, a map of <package name -> components within that package>
1206        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1207
1208        public PendingPackageBroadcasts() {
1209            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1210        }
1211
1212        public ArrayList<String> get(int userId, String packageName) {
1213            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1214            return packages.get(packageName);
1215        }
1216
1217        public void put(int userId, String packageName, ArrayList<String> components) {
1218            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1219            packages.put(packageName, components);
1220        }
1221
1222        public void remove(int userId, String packageName) {
1223            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1224            if (packages != null) {
1225                packages.remove(packageName);
1226            }
1227        }
1228
1229        public void remove(int userId) {
1230            mUidMap.remove(userId);
1231        }
1232
1233        public int userIdCount() {
1234            return mUidMap.size();
1235        }
1236
1237        public int userIdAt(int n) {
1238            return mUidMap.keyAt(n);
1239        }
1240
1241        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1242            return mUidMap.get(userId);
1243        }
1244
1245        public int size() {
1246            // total number of pending broadcast entries across all userIds
1247            int num = 0;
1248            for (int i = 0; i< mUidMap.size(); i++) {
1249                num += mUidMap.valueAt(i).size();
1250            }
1251            return num;
1252        }
1253
1254        public void clear() {
1255            mUidMap.clear();
1256        }
1257
1258        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1259            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1260            if (map == null) {
1261                map = new ArrayMap<String, ArrayList<String>>();
1262                mUidMap.put(userId, map);
1263            }
1264            return map;
1265        }
1266    }
1267    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1268
1269    // Service Connection to remote media container service to copy
1270    // package uri's from external media onto secure containers
1271    // or internal storage.
1272    private IMediaContainerService mContainerService = null;
1273
1274    static final int SEND_PENDING_BROADCAST = 1;
1275    static final int MCS_BOUND = 3;
1276    static final int END_COPY = 4;
1277    static final int INIT_COPY = 5;
1278    static final int MCS_UNBIND = 6;
1279    static final int START_CLEANING_PACKAGE = 7;
1280    static final int FIND_INSTALL_LOC = 8;
1281    static final int POST_INSTALL = 9;
1282    static final int MCS_RECONNECT = 10;
1283    static final int MCS_GIVE_UP = 11;
1284    static final int UPDATED_MEDIA_STATUS = 12;
1285    static final int WRITE_SETTINGS = 13;
1286    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1287    static final int PACKAGE_VERIFIED = 15;
1288    static final int CHECK_PENDING_VERIFICATION = 16;
1289    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1290    static final int INTENT_FILTER_VERIFIED = 18;
1291    static final int WRITE_PACKAGE_LIST = 19;
1292    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1293
1294    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1295
1296    // Delay time in millisecs
1297    static final int BROADCAST_DELAY = 10 * 1000;
1298
1299    static UserManagerService sUserManager;
1300
1301    // Stores a list of users whose package restrictions file needs to be updated
1302    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1303
1304    final private DefaultContainerConnection mDefContainerConn =
1305            new DefaultContainerConnection();
1306    class DefaultContainerConnection implements ServiceConnection {
1307        public void onServiceConnected(ComponentName name, IBinder service) {
1308            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1309            final IMediaContainerService imcs = IMediaContainerService.Stub
1310                    .asInterface(Binder.allowBlocking(service));
1311            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1312        }
1313
1314        public void onServiceDisconnected(ComponentName name) {
1315            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1316        }
1317    }
1318
1319    // Recordkeeping of restore-after-install operations that are currently in flight
1320    // between the Package Manager and the Backup Manager
1321    static class PostInstallData {
1322        public InstallArgs args;
1323        public PackageInstalledInfo res;
1324
1325        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1326            args = _a;
1327            res = _r;
1328        }
1329    }
1330
1331    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1332    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1333
1334    // XML tags for backup/restore of various bits of state
1335    private static final String TAG_PREFERRED_BACKUP = "pa";
1336    private static final String TAG_DEFAULT_APPS = "da";
1337    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1338
1339    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1340    private static final String TAG_ALL_GRANTS = "rt-grants";
1341    private static final String TAG_GRANT = "grant";
1342    private static final String ATTR_PACKAGE_NAME = "pkg";
1343
1344    private static final String TAG_PERMISSION = "perm";
1345    private static final String ATTR_PERMISSION_NAME = "name";
1346    private static final String ATTR_IS_GRANTED = "g";
1347    private static final String ATTR_USER_SET = "set";
1348    private static final String ATTR_USER_FIXED = "fixed";
1349    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1350
1351    // System/policy permission grants are not backed up
1352    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1353            FLAG_PERMISSION_POLICY_FIXED
1354            | FLAG_PERMISSION_SYSTEM_FIXED
1355            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1356
1357    // And we back up these user-adjusted states
1358    private static final int USER_RUNTIME_GRANT_MASK =
1359            FLAG_PERMISSION_USER_SET
1360            | FLAG_PERMISSION_USER_FIXED
1361            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1362
1363    final @Nullable String mRequiredVerifierPackage;
1364    final @NonNull String mRequiredInstallerPackage;
1365    final @NonNull String mRequiredUninstallerPackage;
1366    final @Nullable String mSetupWizardPackage;
1367    final @Nullable String mStorageManagerPackage;
1368    final @NonNull String mServicesSystemSharedLibraryPackageName;
1369    final @NonNull String mSharedSystemSharedLibraryPackageName;
1370
1371    final boolean mPermissionReviewRequired;
1372
1373    private final PackageUsage mPackageUsage = new PackageUsage();
1374    private final CompilerStats mCompilerStats = new CompilerStats();
1375
1376    class PackageHandler extends Handler {
1377        private boolean mBound = false;
1378        final ArrayList<HandlerParams> mPendingInstalls =
1379            new ArrayList<HandlerParams>();
1380
1381        private boolean connectToService() {
1382            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1383                    " DefaultContainerService");
1384            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1385            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1386            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1387                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1388                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1389                mBound = true;
1390                return true;
1391            }
1392            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1393            return false;
1394        }
1395
1396        private void disconnectService() {
1397            mContainerService = null;
1398            mBound = false;
1399            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1400            mContext.unbindService(mDefContainerConn);
1401            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1402        }
1403
1404        PackageHandler(Looper looper) {
1405            super(looper);
1406        }
1407
1408        public void handleMessage(Message msg) {
1409            try {
1410                doHandleMessage(msg);
1411            } finally {
1412                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1413            }
1414        }
1415
1416        void doHandleMessage(Message msg) {
1417            switch (msg.what) {
1418                case INIT_COPY: {
1419                    HandlerParams params = (HandlerParams) msg.obj;
1420                    int idx = mPendingInstalls.size();
1421                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1422                    // If a bind was already initiated we dont really
1423                    // need to do anything. The pending install
1424                    // will be processed later on.
1425                    if (!mBound) {
1426                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1427                                System.identityHashCode(mHandler));
1428                        // If this is the only one pending we might
1429                        // have to bind to the service again.
1430                        if (!connectToService()) {
1431                            Slog.e(TAG, "Failed to bind to media container service");
1432                            params.serviceError();
1433                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1434                                    System.identityHashCode(mHandler));
1435                            if (params.traceMethod != null) {
1436                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1437                                        params.traceCookie);
1438                            }
1439                            return;
1440                        } else {
1441                            // Once we bind to the service, the first
1442                            // pending request will be processed.
1443                            mPendingInstalls.add(idx, params);
1444                        }
1445                    } else {
1446                        mPendingInstalls.add(idx, params);
1447                        // Already bound to the service. Just make
1448                        // sure we trigger off processing the first request.
1449                        if (idx == 0) {
1450                            mHandler.sendEmptyMessage(MCS_BOUND);
1451                        }
1452                    }
1453                    break;
1454                }
1455                case MCS_BOUND: {
1456                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1457                    if (msg.obj != null) {
1458                        mContainerService = (IMediaContainerService) msg.obj;
1459                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1460                                System.identityHashCode(mHandler));
1461                    }
1462                    if (mContainerService == null) {
1463                        if (!mBound) {
1464                            // Something seriously wrong since we are not bound and we are not
1465                            // waiting for connection. Bail out.
1466                            Slog.e(TAG, "Cannot bind to media container service");
1467                            for (HandlerParams params : mPendingInstalls) {
1468                                // Indicate service bind error
1469                                params.serviceError();
1470                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1471                                        System.identityHashCode(params));
1472                                if (params.traceMethod != null) {
1473                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1474                                            params.traceMethod, params.traceCookie);
1475                                }
1476                                return;
1477                            }
1478                            mPendingInstalls.clear();
1479                        } else {
1480                            Slog.w(TAG, "Waiting to connect to media container service");
1481                        }
1482                    } else if (mPendingInstalls.size() > 0) {
1483                        HandlerParams params = mPendingInstalls.get(0);
1484                        if (params != null) {
1485                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1486                                    System.identityHashCode(params));
1487                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1488                            if (params.startCopy()) {
1489                                // We are done...  look for more work or to
1490                                // go idle.
1491                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1492                                        "Checking for more work or unbind...");
1493                                // Delete pending install
1494                                if (mPendingInstalls.size() > 0) {
1495                                    mPendingInstalls.remove(0);
1496                                }
1497                                if (mPendingInstalls.size() == 0) {
1498                                    if (mBound) {
1499                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1500                                                "Posting delayed MCS_UNBIND");
1501                                        removeMessages(MCS_UNBIND);
1502                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1503                                        // Unbind after a little delay, to avoid
1504                                        // continual thrashing.
1505                                        sendMessageDelayed(ubmsg, 10000);
1506                                    }
1507                                } else {
1508                                    // There are more pending requests in queue.
1509                                    // Just post MCS_BOUND message to trigger processing
1510                                    // of next pending install.
1511                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1512                                            "Posting MCS_BOUND for next work");
1513                                    mHandler.sendEmptyMessage(MCS_BOUND);
1514                                }
1515                            }
1516                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1517                        }
1518                    } else {
1519                        // Should never happen ideally.
1520                        Slog.w(TAG, "Empty queue");
1521                    }
1522                    break;
1523                }
1524                case MCS_RECONNECT: {
1525                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1526                    if (mPendingInstalls.size() > 0) {
1527                        if (mBound) {
1528                            disconnectService();
1529                        }
1530                        if (!connectToService()) {
1531                            Slog.e(TAG, "Failed to bind to media container service");
1532                            for (HandlerParams params : mPendingInstalls) {
1533                                // Indicate service bind error
1534                                params.serviceError();
1535                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1536                                        System.identityHashCode(params));
1537                            }
1538                            mPendingInstalls.clear();
1539                        }
1540                    }
1541                    break;
1542                }
1543                case MCS_UNBIND: {
1544                    // If there is no actual work left, then time to unbind.
1545                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1546
1547                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1548                        if (mBound) {
1549                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1550
1551                            disconnectService();
1552                        }
1553                    } else if (mPendingInstalls.size() > 0) {
1554                        // There are more pending requests in queue.
1555                        // Just post MCS_BOUND message to trigger processing
1556                        // of next pending install.
1557                        mHandler.sendEmptyMessage(MCS_BOUND);
1558                    }
1559
1560                    break;
1561                }
1562                case MCS_GIVE_UP: {
1563                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1564                    HandlerParams params = mPendingInstalls.remove(0);
1565                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1566                            System.identityHashCode(params));
1567                    break;
1568                }
1569                case SEND_PENDING_BROADCAST: {
1570                    String packages[];
1571                    ArrayList<String> components[];
1572                    int size = 0;
1573                    int uids[];
1574                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1575                    synchronized (mPackages) {
1576                        if (mPendingBroadcasts == null) {
1577                            return;
1578                        }
1579                        size = mPendingBroadcasts.size();
1580                        if (size <= 0) {
1581                            // Nothing to be done. Just return
1582                            return;
1583                        }
1584                        packages = new String[size];
1585                        components = new ArrayList[size];
1586                        uids = new int[size];
1587                        int i = 0;  // filling out the above arrays
1588
1589                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1590                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1591                            Iterator<Map.Entry<String, ArrayList<String>>> it
1592                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1593                                            .entrySet().iterator();
1594                            while (it.hasNext() && i < size) {
1595                                Map.Entry<String, ArrayList<String>> ent = it.next();
1596                                packages[i] = ent.getKey();
1597                                components[i] = ent.getValue();
1598                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1599                                uids[i] = (ps != null)
1600                                        ? UserHandle.getUid(packageUserId, ps.appId)
1601                                        : -1;
1602                                i++;
1603                            }
1604                        }
1605                        size = i;
1606                        mPendingBroadcasts.clear();
1607                    }
1608                    // Send broadcasts
1609                    for (int i = 0; i < size; i++) {
1610                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1611                    }
1612                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1613                    break;
1614                }
1615                case START_CLEANING_PACKAGE: {
1616                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1617                    final String packageName = (String)msg.obj;
1618                    final int userId = msg.arg1;
1619                    final boolean andCode = msg.arg2 != 0;
1620                    synchronized (mPackages) {
1621                        if (userId == UserHandle.USER_ALL) {
1622                            int[] users = sUserManager.getUserIds();
1623                            for (int user : users) {
1624                                mSettings.addPackageToCleanLPw(
1625                                        new PackageCleanItem(user, packageName, andCode));
1626                            }
1627                        } else {
1628                            mSettings.addPackageToCleanLPw(
1629                                    new PackageCleanItem(userId, packageName, andCode));
1630                        }
1631                    }
1632                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1633                    startCleaningPackages();
1634                } break;
1635                case POST_INSTALL: {
1636                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1637
1638                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1639                    final boolean didRestore = (msg.arg2 != 0);
1640                    mRunningInstalls.delete(msg.arg1);
1641
1642                    if (data != null) {
1643                        InstallArgs args = data.args;
1644                        PackageInstalledInfo parentRes = data.res;
1645
1646                        final boolean grantPermissions = (args.installFlags
1647                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1648                        final boolean killApp = (args.installFlags
1649                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1650                        final String[] grantedPermissions = args.installGrantPermissions;
1651
1652                        // Handle the parent package
1653                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1654                                grantedPermissions, didRestore, args.installerPackageName,
1655                                args.observer);
1656
1657                        // Handle the child packages
1658                        final int childCount = (parentRes.addedChildPackages != null)
1659                                ? parentRes.addedChildPackages.size() : 0;
1660                        for (int i = 0; i < childCount; i++) {
1661                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1662                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1663                                    grantedPermissions, false, args.installerPackageName,
1664                                    args.observer);
1665                        }
1666
1667                        // Log tracing if needed
1668                        if (args.traceMethod != null) {
1669                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1670                                    args.traceCookie);
1671                        }
1672                    } else {
1673                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1674                    }
1675
1676                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1677                } break;
1678                case UPDATED_MEDIA_STATUS: {
1679                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1680                    boolean reportStatus = msg.arg1 == 1;
1681                    boolean doGc = msg.arg2 == 1;
1682                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1683                    if (doGc) {
1684                        // Force a gc to clear up stale containers.
1685                        Runtime.getRuntime().gc();
1686                    }
1687                    if (msg.obj != null) {
1688                        @SuppressWarnings("unchecked")
1689                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1690                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1691                        // Unload containers
1692                        unloadAllContainers(args);
1693                    }
1694                    if (reportStatus) {
1695                        try {
1696                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1697                                    "Invoking StorageManagerService call back");
1698                            PackageHelper.getStorageManager().finishMediaUpdate();
1699                        } catch (RemoteException e) {
1700                            Log.e(TAG, "StorageManagerService not running?");
1701                        }
1702                    }
1703                } break;
1704                case WRITE_SETTINGS: {
1705                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1706                    synchronized (mPackages) {
1707                        removeMessages(WRITE_SETTINGS);
1708                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1709                        mSettings.writeLPr();
1710                        mDirtyUsers.clear();
1711                    }
1712                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1713                } break;
1714                case WRITE_PACKAGE_RESTRICTIONS: {
1715                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1716                    synchronized (mPackages) {
1717                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1718                        for (int userId : mDirtyUsers) {
1719                            mSettings.writePackageRestrictionsLPr(userId);
1720                        }
1721                        mDirtyUsers.clear();
1722                    }
1723                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1724                } break;
1725                case WRITE_PACKAGE_LIST: {
1726                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1727                    synchronized (mPackages) {
1728                        removeMessages(WRITE_PACKAGE_LIST);
1729                        mSettings.writePackageListLPr(msg.arg1);
1730                    }
1731                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1732                } break;
1733                case CHECK_PENDING_VERIFICATION: {
1734                    final int verificationId = msg.arg1;
1735                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1736
1737                    if ((state != null) && !state.timeoutExtended()) {
1738                        final InstallArgs args = state.getInstallArgs();
1739                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1740
1741                        Slog.i(TAG, "Verification timed out for " + originUri);
1742                        mPendingVerification.remove(verificationId);
1743
1744                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1745
1746                        final UserHandle user = args.getUser();
1747                        if (getDefaultVerificationResponse(user)
1748                                == PackageManager.VERIFICATION_ALLOW) {
1749                            Slog.i(TAG, "Continuing with installation of " + originUri);
1750                            state.setVerifierResponse(Binder.getCallingUid(),
1751                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1752                            broadcastPackageVerified(verificationId, originUri,
1753                                    PackageManager.VERIFICATION_ALLOW, user);
1754                            try {
1755                                ret = args.copyApk(mContainerService, true);
1756                            } catch (RemoteException e) {
1757                                Slog.e(TAG, "Could not contact the ContainerService");
1758                            }
1759                        } else {
1760                            broadcastPackageVerified(verificationId, originUri,
1761                                    PackageManager.VERIFICATION_REJECT, user);
1762                        }
1763
1764                        Trace.asyncTraceEnd(
1765                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1766
1767                        processPendingInstall(args, ret);
1768                        mHandler.sendEmptyMessage(MCS_UNBIND);
1769                    }
1770                    break;
1771                }
1772                case PACKAGE_VERIFIED: {
1773                    final int verificationId = msg.arg1;
1774
1775                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1776                    if (state == null) {
1777                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1778                        break;
1779                    }
1780
1781                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1782
1783                    state.setVerifierResponse(response.callerUid, response.code);
1784
1785                    if (state.isVerificationComplete()) {
1786                        mPendingVerification.remove(verificationId);
1787
1788                        final InstallArgs args = state.getInstallArgs();
1789                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1790
1791                        int ret;
1792                        if (state.isInstallAllowed()) {
1793                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1794                            broadcastPackageVerified(verificationId, originUri,
1795                                    response.code, state.getInstallArgs().getUser());
1796                            try {
1797                                ret = args.copyApk(mContainerService, true);
1798                            } catch (RemoteException e) {
1799                                Slog.e(TAG, "Could not contact the ContainerService");
1800                            }
1801                        } else {
1802                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1803                        }
1804
1805                        Trace.asyncTraceEnd(
1806                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1807
1808                        processPendingInstall(args, ret);
1809                        mHandler.sendEmptyMessage(MCS_UNBIND);
1810                    }
1811
1812                    break;
1813                }
1814                case START_INTENT_FILTER_VERIFICATIONS: {
1815                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1816                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1817                            params.replacing, params.pkg);
1818                    break;
1819                }
1820                case INTENT_FILTER_VERIFIED: {
1821                    final int verificationId = msg.arg1;
1822
1823                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1824                            verificationId);
1825                    if (state == null) {
1826                        Slog.w(TAG, "Invalid IntentFilter verification token "
1827                                + verificationId + " received");
1828                        break;
1829                    }
1830
1831                    final int userId = state.getUserId();
1832
1833                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1834                            "Processing IntentFilter verification with token:"
1835                            + verificationId + " and userId:" + userId);
1836
1837                    final IntentFilterVerificationResponse response =
1838                            (IntentFilterVerificationResponse) msg.obj;
1839
1840                    state.setVerifierResponse(response.callerUid, response.code);
1841
1842                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1843                            "IntentFilter verification with token:" + verificationId
1844                            + " and userId:" + userId
1845                            + " is settings verifier response with response code:"
1846                            + response.code);
1847
1848                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1849                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1850                                + response.getFailedDomainsString());
1851                    }
1852
1853                    if (state.isVerificationComplete()) {
1854                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1855                    } else {
1856                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1857                                "IntentFilter verification with token:" + verificationId
1858                                + " was not said to be complete");
1859                    }
1860
1861                    break;
1862                }
1863                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1864                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1865                            mInstantAppResolverConnection,
1866                            (InstantAppRequest) msg.obj,
1867                            mInstantAppInstallerActivity,
1868                            mHandler);
1869                }
1870            }
1871        }
1872    }
1873
1874    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1875            boolean killApp, String[] grantedPermissions,
1876            boolean launchedForRestore, String installerPackage,
1877            IPackageInstallObserver2 installObserver) {
1878        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1879            // Send the removed broadcasts
1880            if (res.removedInfo != null) {
1881                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1882            }
1883
1884            // Now that we successfully installed the package, grant runtime
1885            // permissions if requested before broadcasting the install. Also
1886            // for legacy apps in permission review mode we clear the permission
1887            // review flag which is used to emulate runtime permissions for
1888            // legacy apps.
1889            if (grantPermissions) {
1890                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1891            }
1892
1893            final boolean update = res.removedInfo != null
1894                    && res.removedInfo.removedPackage != null;
1895            final String origInstallerPackageName = res.removedInfo != null
1896                    ? res.removedInfo.installerPackageName : null;
1897
1898            // If this is the first time we have child packages for a disabled privileged
1899            // app that had no children, we grant requested runtime permissions to the new
1900            // children if the parent on the system image had them already granted.
1901            if (res.pkg.parentPackage != null) {
1902                synchronized (mPackages) {
1903                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1904                }
1905            }
1906
1907            synchronized (mPackages) {
1908                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1909            }
1910
1911            final String packageName = res.pkg.applicationInfo.packageName;
1912
1913            // Determine the set of users who are adding this package for
1914            // the first time vs. those who are seeing an update.
1915            int[] firstUsers = EMPTY_INT_ARRAY;
1916            int[] updateUsers = EMPTY_INT_ARRAY;
1917            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1918            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1919            for (int newUser : res.newUsers) {
1920                if (ps.getInstantApp(newUser)) {
1921                    continue;
1922                }
1923                if (allNewUsers) {
1924                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1925                    continue;
1926                }
1927                boolean isNew = true;
1928                for (int origUser : res.origUsers) {
1929                    if (origUser == newUser) {
1930                        isNew = false;
1931                        break;
1932                    }
1933                }
1934                if (isNew) {
1935                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1936                } else {
1937                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1938                }
1939            }
1940
1941            // Send installed broadcasts if the package is not a static shared lib.
1942            if (res.pkg.staticSharedLibName == null) {
1943                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1944
1945                // Send added for users that see the package for the first time
1946                // sendPackageAddedForNewUsers also deals with system apps
1947                int appId = UserHandle.getAppId(res.uid);
1948                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1949                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1950
1951                // Send added for users that don't see the package for the first time
1952                Bundle extras = new Bundle(1);
1953                extras.putInt(Intent.EXTRA_UID, res.uid);
1954                if (update) {
1955                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1956                }
1957                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1958                        extras, 0 /*flags*/,
1959                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1960                if (origInstallerPackageName != null) {
1961                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1962                            extras, 0 /*flags*/,
1963                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1964                }
1965
1966                // Send replaced for users that don't see the package for the first time
1967                if (update) {
1968                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1969                            packageName, extras, 0 /*flags*/,
1970                            null /*targetPackage*/, null /*finishedReceiver*/,
1971                            updateUsers);
1972                    if (origInstallerPackageName != null) {
1973                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1974                                extras, 0 /*flags*/,
1975                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1976                    }
1977                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1978                            null /*package*/, null /*extras*/, 0 /*flags*/,
1979                            packageName /*targetPackage*/,
1980                            null /*finishedReceiver*/, updateUsers);
1981                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1982                    // First-install and we did a restore, so we're responsible for the
1983                    // first-launch broadcast.
1984                    if (DEBUG_BACKUP) {
1985                        Slog.i(TAG, "Post-restore of " + packageName
1986                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1987                    }
1988                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1989                }
1990
1991                // Send broadcast package appeared if forward locked/external for all users
1992                // treat asec-hosted packages like removable media on upgrade
1993                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1994                    if (DEBUG_INSTALL) {
1995                        Slog.i(TAG, "upgrading pkg " + res.pkg
1996                                + " is ASEC-hosted -> AVAILABLE");
1997                    }
1998                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1999                    ArrayList<String> pkgList = new ArrayList<>(1);
2000                    pkgList.add(packageName);
2001                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2002                }
2003            }
2004
2005            // Work that needs to happen on first install within each user
2006            if (firstUsers != null && firstUsers.length > 0) {
2007                synchronized (mPackages) {
2008                    for (int userId : firstUsers) {
2009                        // If this app is a browser and it's newly-installed for some
2010                        // users, clear any default-browser state in those users. The
2011                        // app's nature doesn't depend on the user, so we can just check
2012                        // its browser nature in any user and generalize.
2013                        if (packageIsBrowser(packageName, userId)) {
2014                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2015                        }
2016
2017                        // We may also need to apply pending (restored) runtime
2018                        // permission grants within these users.
2019                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2020                    }
2021                }
2022            }
2023
2024            // Log current value of "unknown sources" setting
2025            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2026                    getUnknownSourcesSettings());
2027
2028            // Remove the replaced package's older resources safely now
2029            // We delete after a gc for applications  on sdcard.
2030            if (res.removedInfo != null && res.removedInfo.args != null) {
2031                Runtime.getRuntime().gc();
2032                synchronized (mInstallLock) {
2033                    res.removedInfo.args.doPostDeleteLI(true);
2034                }
2035            } else {
2036                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2037                // and not block here.
2038                VMRuntime.getRuntime().requestConcurrentGC();
2039            }
2040
2041            // Notify DexManager that the package was installed for new users.
2042            // The updated users should already be indexed and the package code paths
2043            // should not change.
2044            // Don't notify the manager for ephemeral apps as they are not expected to
2045            // survive long enough to benefit of background optimizations.
2046            for (int userId : firstUsers) {
2047                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2048                // There's a race currently where some install events may interleave with an uninstall.
2049                // This can lead to package info being null (b/36642664).
2050                if (info != null) {
2051                    mDexManager.notifyPackageInstalled(info, userId);
2052                }
2053            }
2054        }
2055
2056        // If someone is watching installs - notify them
2057        if (installObserver != null) {
2058            try {
2059                Bundle extras = extrasForInstallResult(res);
2060                installObserver.onPackageInstalled(res.name, res.returnCode,
2061                        res.returnMsg, extras);
2062            } catch (RemoteException e) {
2063                Slog.i(TAG, "Observer no longer exists.");
2064            }
2065        }
2066    }
2067
2068    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2069            PackageParser.Package pkg) {
2070        if (pkg.parentPackage == null) {
2071            return;
2072        }
2073        if (pkg.requestedPermissions == null) {
2074            return;
2075        }
2076        final PackageSetting disabledSysParentPs = mSettings
2077                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2078        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2079                || !disabledSysParentPs.isPrivileged()
2080                || (disabledSysParentPs.childPackageNames != null
2081                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2082            return;
2083        }
2084        final int[] allUserIds = sUserManager.getUserIds();
2085        final int permCount = pkg.requestedPermissions.size();
2086        for (int i = 0; i < permCount; i++) {
2087            String permission = pkg.requestedPermissions.get(i);
2088            BasePermission bp = mSettings.mPermissions.get(permission);
2089            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2090                continue;
2091            }
2092            for (int userId : allUserIds) {
2093                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2094                        permission, userId)) {
2095                    grantRuntimePermission(pkg.packageName, permission, userId);
2096                }
2097            }
2098        }
2099    }
2100
2101    private StorageEventListener mStorageListener = new StorageEventListener() {
2102        @Override
2103        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2104            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2105                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2106                    final String volumeUuid = vol.getFsUuid();
2107
2108                    // Clean up any users or apps that were removed or recreated
2109                    // while this volume was missing
2110                    sUserManager.reconcileUsers(volumeUuid);
2111                    reconcileApps(volumeUuid);
2112
2113                    // Clean up any install sessions that expired or were
2114                    // cancelled while this volume was missing
2115                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2116
2117                    loadPrivatePackages(vol);
2118
2119                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2120                    unloadPrivatePackages(vol);
2121                }
2122            }
2123
2124            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2125                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2126                    updateExternalMediaStatus(true, false);
2127                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2128                    updateExternalMediaStatus(false, false);
2129                }
2130            }
2131        }
2132
2133        @Override
2134        public void onVolumeForgotten(String fsUuid) {
2135            if (TextUtils.isEmpty(fsUuid)) {
2136                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2137                return;
2138            }
2139
2140            // Remove any apps installed on the forgotten volume
2141            synchronized (mPackages) {
2142                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2143                for (PackageSetting ps : packages) {
2144                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2145                    deletePackageVersioned(new VersionedPackage(ps.name,
2146                            PackageManager.VERSION_CODE_HIGHEST),
2147                            new LegacyPackageDeleteObserver(null).getBinder(),
2148                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2149                    // Try very hard to release any references to this package
2150                    // so we don't risk the system server being killed due to
2151                    // open FDs
2152                    AttributeCache.instance().removePackage(ps.name);
2153                }
2154
2155                mSettings.onVolumeForgotten(fsUuid);
2156                mSettings.writeLPr();
2157            }
2158        }
2159    };
2160
2161    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2162            String[] grantedPermissions) {
2163        for (int userId : userIds) {
2164            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2165        }
2166    }
2167
2168    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2169            String[] grantedPermissions) {
2170        SettingBase sb = (SettingBase) pkg.mExtras;
2171        if (sb == null) {
2172            return;
2173        }
2174
2175        PermissionsState permissionsState = sb.getPermissionsState();
2176
2177        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2178                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2179
2180        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2181                >= Build.VERSION_CODES.M;
2182
2183        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2184
2185        for (String permission : pkg.requestedPermissions) {
2186            final BasePermission bp;
2187            synchronized (mPackages) {
2188                bp = mSettings.mPermissions.get(permission);
2189            }
2190            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2191                    && (!instantApp || bp.isInstant())
2192                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2193                    && (grantedPermissions == null
2194                           || ArrayUtils.contains(grantedPermissions, permission))) {
2195                final int flags = permissionsState.getPermissionFlags(permission, userId);
2196                if (supportsRuntimePermissions) {
2197                    // Installer cannot change immutable permissions.
2198                    if ((flags & immutableFlags) == 0) {
2199                        grantRuntimePermission(pkg.packageName, permission, userId);
2200                    }
2201                } else if (mPermissionReviewRequired) {
2202                    // In permission review mode we clear the review flag when we
2203                    // are asked to install the app with all permissions granted.
2204                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2205                        updatePermissionFlags(permission, pkg.packageName,
2206                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2207                    }
2208                }
2209            }
2210        }
2211    }
2212
2213    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2214        Bundle extras = null;
2215        switch (res.returnCode) {
2216            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2217                extras = new Bundle();
2218                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2219                        res.origPermission);
2220                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2221                        res.origPackage);
2222                break;
2223            }
2224            case PackageManager.INSTALL_SUCCEEDED: {
2225                extras = new Bundle();
2226                extras.putBoolean(Intent.EXTRA_REPLACING,
2227                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2228                break;
2229            }
2230        }
2231        return extras;
2232    }
2233
2234    void scheduleWriteSettingsLocked() {
2235        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2236            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2237        }
2238    }
2239
2240    void scheduleWritePackageListLocked(int userId) {
2241        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2242            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2243            msg.arg1 = userId;
2244            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2245        }
2246    }
2247
2248    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2249        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2250        scheduleWritePackageRestrictionsLocked(userId);
2251    }
2252
2253    void scheduleWritePackageRestrictionsLocked(int userId) {
2254        final int[] userIds = (userId == UserHandle.USER_ALL)
2255                ? sUserManager.getUserIds() : new int[]{userId};
2256        for (int nextUserId : userIds) {
2257            if (!sUserManager.exists(nextUserId)) return;
2258            mDirtyUsers.add(nextUserId);
2259            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2260                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2261            }
2262        }
2263    }
2264
2265    public static PackageManagerService main(Context context, Installer installer,
2266            boolean factoryTest, boolean onlyCore) {
2267        // Self-check for initial settings.
2268        PackageManagerServiceCompilerMapping.checkProperties();
2269
2270        PackageManagerService m = new PackageManagerService(context, installer,
2271                factoryTest, onlyCore);
2272        m.enableSystemUserPackages();
2273        ServiceManager.addService("package", m);
2274        return m;
2275    }
2276
2277    private void enableSystemUserPackages() {
2278        if (!UserManager.isSplitSystemUser()) {
2279            return;
2280        }
2281        // For system user, enable apps based on the following conditions:
2282        // - app is whitelisted or belong to one of these groups:
2283        //   -- system app which has no launcher icons
2284        //   -- system app which has INTERACT_ACROSS_USERS permission
2285        //   -- system IME app
2286        // - app is not in the blacklist
2287        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2288        Set<String> enableApps = new ArraySet<>();
2289        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2290                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2291                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2292        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2293        enableApps.addAll(wlApps);
2294        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2295                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2296        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2297        enableApps.removeAll(blApps);
2298        Log.i(TAG, "Applications installed for system user: " + enableApps);
2299        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2300                UserHandle.SYSTEM);
2301        final int allAppsSize = allAps.size();
2302        synchronized (mPackages) {
2303            for (int i = 0; i < allAppsSize; i++) {
2304                String pName = allAps.get(i);
2305                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2306                // Should not happen, but we shouldn't be failing if it does
2307                if (pkgSetting == null) {
2308                    continue;
2309                }
2310                boolean install = enableApps.contains(pName);
2311                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2312                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2313                            + " for system user");
2314                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2315                }
2316            }
2317            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2318        }
2319    }
2320
2321    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2322        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2323                Context.DISPLAY_SERVICE);
2324        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2325    }
2326
2327    /**
2328     * Requests that files preopted on a secondary system partition be copied to the data partition
2329     * if possible.  Note that the actual copying of the files is accomplished by init for security
2330     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2331     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2332     */
2333    private static void requestCopyPreoptedFiles() {
2334        final int WAIT_TIME_MS = 100;
2335        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2336        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2337            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2338            // We will wait for up to 100 seconds.
2339            final long timeStart = SystemClock.uptimeMillis();
2340            final long timeEnd = timeStart + 100 * 1000;
2341            long timeNow = timeStart;
2342            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2343                try {
2344                    Thread.sleep(WAIT_TIME_MS);
2345                } catch (InterruptedException e) {
2346                    // Do nothing
2347                }
2348                timeNow = SystemClock.uptimeMillis();
2349                if (timeNow > timeEnd) {
2350                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2351                    Slog.wtf(TAG, "cppreopt did not finish!");
2352                    break;
2353                }
2354            }
2355
2356            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2357        }
2358    }
2359
2360    public PackageManagerService(Context context, Installer installer,
2361            boolean factoryTest, boolean onlyCore) {
2362        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2363        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2364        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2365                SystemClock.uptimeMillis());
2366
2367        if (mSdkVersion <= 0) {
2368            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2369        }
2370
2371        mContext = context;
2372
2373        mPermissionReviewRequired = context.getResources().getBoolean(
2374                R.bool.config_permissionReviewRequired);
2375
2376        mFactoryTest = factoryTest;
2377        mOnlyCore = onlyCore;
2378        mMetrics = new DisplayMetrics();
2379        mSettings = new Settings(mPackages);
2380        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2381                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2382        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2383                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2384        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2385                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2386        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2387                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2388        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2389                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2390        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2391                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2392
2393        String separateProcesses = SystemProperties.get("debug.separate_processes");
2394        if (separateProcesses != null && separateProcesses.length() > 0) {
2395            if ("*".equals(separateProcesses)) {
2396                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2397                mSeparateProcesses = null;
2398                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2399            } else {
2400                mDefParseFlags = 0;
2401                mSeparateProcesses = separateProcesses.split(",");
2402                Slog.w(TAG, "Running with debug.separate_processes: "
2403                        + separateProcesses);
2404            }
2405        } else {
2406            mDefParseFlags = 0;
2407            mSeparateProcesses = null;
2408        }
2409
2410        mInstaller = installer;
2411        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2412                "*dexopt*");
2413        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2414        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2415
2416        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2417                FgThread.get().getLooper());
2418
2419        getDefaultDisplayMetrics(context, mMetrics);
2420
2421        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2422        SystemConfig systemConfig = SystemConfig.getInstance();
2423        mGlobalGids = systemConfig.getGlobalGids();
2424        mSystemPermissions = systemConfig.getSystemPermissions();
2425        mAvailableFeatures = systemConfig.getAvailableFeatures();
2426        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2427
2428        mProtectedPackages = new ProtectedPackages(mContext);
2429
2430        synchronized (mInstallLock) {
2431        // writer
2432        synchronized (mPackages) {
2433            mHandlerThread = new ServiceThread(TAG,
2434                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2435            mHandlerThread.start();
2436            mHandler = new PackageHandler(mHandlerThread.getLooper());
2437            mProcessLoggingHandler = new ProcessLoggingHandler();
2438            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2439
2440            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2441            mInstantAppRegistry = new InstantAppRegistry(this);
2442
2443            File dataDir = Environment.getDataDirectory();
2444            mAppInstallDir = new File(dataDir, "app");
2445            mAppLib32InstallDir = new File(dataDir, "app-lib");
2446            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2447            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2448            sUserManager = new UserManagerService(context, this,
2449                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2450
2451            // Propagate permission configuration in to package manager.
2452            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2453                    = systemConfig.getPermissions();
2454            for (int i=0; i<permConfig.size(); i++) {
2455                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2456                BasePermission bp = mSettings.mPermissions.get(perm.name);
2457                if (bp == null) {
2458                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2459                    mSettings.mPermissions.put(perm.name, bp);
2460                }
2461                if (perm.gids != null) {
2462                    bp.setGids(perm.gids, perm.perUser);
2463                }
2464            }
2465
2466            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2467            final int builtInLibCount = libConfig.size();
2468            for (int i = 0; i < builtInLibCount; i++) {
2469                String name = libConfig.keyAt(i);
2470                String path = libConfig.valueAt(i);
2471                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2472                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2473            }
2474
2475            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2476
2477            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2478            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2479            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2480
2481            // Clean up orphaned packages for which the code path doesn't exist
2482            // and they are an update to a system app - caused by bug/32321269
2483            final int packageSettingCount = mSettings.mPackages.size();
2484            for (int i = packageSettingCount - 1; i >= 0; i--) {
2485                PackageSetting ps = mSettings.mPackages.valueAt(i);
2486                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2487                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2488                    mSettings.mPackages.removeAt(i);
2489                    mSettings.enableSystemPackageLPw(ps.name);
2490                }
2491            }
2492
2493            if (mFirstBoot) {
2494                requestCopyPreoptedFiles();
2495            }
2496
2497            String customResolverActivity = Resources.getSystem().getString(
2498                    R.string.config_customResolverActivity);
2499            if (TextUtils.isEmpty(customResolverActivity)) {
2500                customResolverActivity = null;
2501            } else {
2502                mCustomResolverComponentName = ComponentName.unflattenFromString(
2503                        customResolverActivity);
2504            }
2505
2506            long startTime = SystemClock.uptimeMillis();
2507
2508            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2509                    startTime);
2510
2511            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2512            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2513
2514            if (bootClassPath == null) {
2515                Slog.w(TAG, "No BOOTCLASSPATH found!");
2516            }
2517
2518            if (systemServerClassPath == null) {
2519                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2520            }
2521
2522            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2523
2524            final VersionInfo ver = mSettings.getInternalVersion();
2525            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2526            if (mIsUpgrade) {
2527                logCriticalInfo(Log.INFO,
2528                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2529            }
2530
2531            // when upgrading from pre-M, promote system app permissions from install to runtime
2532            mPromoteSystemApps =
2533                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2534
2535            // When upgrading from pre-N, we need to handle package extraction like first boot,
2536            // as there is no profiling data available.
2537            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2538
2539            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2540
2541            // save off the names of pre-existing system packages prior to scanning; we don't
2542            // want to automatically grant runtime permissions for new system apps
2543            if (mPromoteSystemApps) {
2544                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2545                while (pkgSettingIter.hasNext()) {
2546                    PackageSetting ps = pkgSettingIter.next();
2547                    if (isSystemApp(ps)) {
2548                        mExistingSystemPackages.add(ps.name);
2549                    }
2550                }
2551            }
2552
2553            mCacheDir = preparePackageParserCache(mIsUpgrade);
2554
2555            // Set flag to monitor and not change apk file paths when
2556            // scanning install directories.
2557            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2558
2559            if (mIsUpgrade || mFirstBoot) {
2560                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2561            }
2562
2563            // Collect vendor overlay packages. (Do this before scanning any apps.)
2564            // For security and version matching reason, only consider
2565            // overlay packages if they reside in the right directory.
2566            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2567                    | PackageParser.PARSE_IS_SYSTEM
2568                    | PackageParser.PARSE_IS_SYSTEM_DIR
2569                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2570
2571            mParallelPackageParserCallback.findStaticOverlayPackages();
2572
2573            // Find base frameworks (resource packages without code).
2574            scanDirTracedLI(frameworkDir, mDefParseFlags
2575                    | PackageParser.PARSE_IS_SYSTEM
2576                    | PackageParser.PARSE_IS_SYSTEM_DIR
2577                    | PackageParser.PARSE_IS_PRIVILEGED,
2578                    scanFlags | SCAN_NO_DEX, 0);
2579
2580            // Collected privileged system packages.
2581            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2582            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2583                    | PackageParser.PARSE_IS_SYSTEM
2584                    | PackageParser.PARSE_IS_SYSTEM_DIR
2585                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2586
2587            // Collect ordinary system packages.
2588            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2589            scanDirTracedLI(systemAppDir, mDefParseFlags
2590                    | PackageParser.PARSE_IS_SYSTEM
2591                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2592
2593            // Collect all vendor packages.
2594            File vendorAppDir = new File("/vendor/app");
2595            try {
2596                vendorAppDir = vendorAppDir.getCanonicalFile();
2597            } catch (IOException e) {
2598                // failed to look up canonical path, continue with original one
2599            }
2600            scanDirTracedLI(vendorAppDir, mDefParseFlags
2601                    | PackageParser.PARSE_IS_SYSTEM
2602                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2603
2604            // Collect all OEM packages.
2605            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2606            scanDirTracedLI(oemAppDir, mDefParseFlags
2607                    | PackageParser.PARSE_IS_SYSTEM
2608                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2609
2610            // Prune any system packages that no longer exist.
2611            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2612            if (!mOnlyCore) {
2613                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2614                while (psit.hasNext()) {
2615                    PackageSetting ps = psit.next();
2616
2617                    /*
2618                     * If this is not a system app, it can't be a
2619                     * disable system app.
2620                     */
2621                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2622                        continue;
2623                    }
2624
2625                    /*
2626                     * If the package is scanned, it's not erased.
2627                     */
2628                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2629                    if (scannedPkg != null) {
2630                        /*
2631                         * If the system app is both scanned and in the
2632                         * disabled packages list, then it must have been
2633                         * added via OTA. Remove it from the currently
2634                         * scanned package so the previously user-installed
2635                         * application can be scanned.
2636                         */
2637                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2638                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2639                                    + ps.name + "; removing system app.  Last known codePath="
2640                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2641                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2642                                    + scannedPkg.mVersionCode);
2643                            removePackageLI(scannedPkg, true);
2644                            mExpectingBetter.put(ps.name, ps.codePath);
2645                        }
2646
2647                        continue;
2648                    }
2649
2650                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2651                        psit.remove();
2652                        logCriticalInfo(Log.WARN, "System package " + ps.name
2653                                + " no longer exists; it's data will be wiped");
2654                        // Actual deletion of code and data will be handled by later
2655                        // reconciliation step
2656                    } else {
2657                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2658                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2659                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2660                        }
2661                    }
2662                }
2663            }
2664
2665            //look for any incomplete package installations
2666            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2667            for (int i = 0; i < deletePkgsList.size(); i++) {
2668                // Actual deletion of code and data will be handled by later
2669                // reconciliation step
2670                final String packageName = deletePkgsList.get(i).name;
2671                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2672                synchronized (mPackages) {
2673                    mSettings.removePackageLPw(packageName);
2674                }
2675            }
2676
2677            //delete tmp files
2678            deleteTempPackageFiles();
2679
2680            // Remove any shared userIDs that have no associated packages
2681            mSettings.pruneSharedUsersLPw();
2682
2683            if (!mOnlyCore) {
2684                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2685                        SystemClock.uptimeMillis());
2686                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2687
2688                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2689                        | PackageParser.PARSE_FORWARD_LOCK,
2690                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2691
2692                /**
2693                 * Remove disable package settings for any updated system
2694                 * apps that were removed via an OTA. If they're not a
2695                 * previously-updated app, remove them completely.
2696                 * Otherwise, just revoke their system-level permissions.
2697                 */
2698                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2699                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2700                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2701
2702                    String msg;
2703                    if (deletedPkg == null) {
2704                        msg = "Updated system package " + deletedAppName
2705                                + " no longer exists; it's data will be wiped";
2706                        // Actual deletion of code and data will be handled by later
2707                        // reconciliation step
2708                    } else {
2709                        msg = "Updated system app + " + deletedAppName
2710                                + " no longer present; removing system privileges for "
2711                                + deletedAppName;
2712
2713                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2714
2715                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2716                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2717                    }
2718                    logCriticalInfo(Log.WARN, msg);
2719                }
2720
2721                /**
2722                 * Make sure all system apps that we expected to appear on
2723                 * the userdata partition actually showed up. If they never
2724                 * appeared, crawl back and revive the system version.
2725                 */
2726                for (int i = 0; i < mExpectingBetter.size(); i++) {
2727                    final String packageName = mExpectingBetter.keyAt(i);
2728                    if (!mPackages.containsKey(packageName)) {
2729                        final File scanFile = mExpectingBetter.valueAt(i);
2730
2731                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2732                                + " but never showed up; reverting to system");
2733
2734                        int reparseFlags = mDefParseFlags;
2735                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2736                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2737                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2738                                    | PackageParser.PARSE_IS_PRIVILEGED;
2739                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2740                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2741                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2742                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2743                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2744                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2745                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2746                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2747                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2748                        } else {
2749                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2750                            continue;
2751                        }
2752
2753                        mSettings.enableSystemPackageLPw(packageName);
2754
2755                        try {
2756                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2757                        } catch (PackageManagerException e) {
2758                            Slog.e(TAG, "Failed to parse original system package: "
2759                                    + e.getMessage());
2760                        }
2761                    }
2762                }
2763            }
2764            mExpectingBetter.clear();
2765
2766            // Resolve the storage manager.
2767            mStorageManagerPackage = getStorageManagerPackageName();
2768
2769            // Resolve protected action filters. Only the setup wizard is allowed to
2770            // have a high priority filter for these actions.
2771            mSetupWizardPackage = getSetupWizardPackageName();
2772            if (mProtectedFilters.size() > 0) {
2773                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2774                    Slog.i(TAG, "No setup wizard;"
2775                        + " All protected intents capped to priority 0");
2776                }
2777                for (ActivityIntentInfo filter : mProtectedFilters) {
2778                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2779                        if (DEBUG_FILTERS) {
2780                            Slog.i(TAG, "Found setup wizard;"
2781                                + " allow priority " + filter.getPriority() + ";"
2782                                + " package: " + filter.activity.info.packageName
2783                                + " activity: " + filter.activity.className
2784                                + " priority: " + filter.getPriority());
2785                        }
2786                        // skip setup wizard; allow it to keep the high priority filter
2787                        continue;
2788                    }
2789                    if (DEBUG_FILTERS) {
2790                        Slog.i(TAG, "Protected action; cap priority to 0;"
2791                                + " package: " + filter.activity.info.packageName
2792                                + " activity: " + filter.activity.className
2793                                + " origPrio: " + filter.getPriority());
2794                    }
2795                    filter.setPriority(0);
2796                }
2797            }
2798            mDeferProtectedFilters = false;
2799            mProtectedFilters.clear();
2800
2801            // Now that we know all of the shared libraries, update all clients to have
2802            // the correct library paths.
2803            updateAllSharedLibrariesLPw(null);
2804
2805            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2806                // NOTE: We ignore potential failures here during a system scan (like
2807                // the rest of the commands above) because there's precious little we
2808                // can do about it. A settings error is reported, though.
2809                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2810            }
2811
2812            // Now that we know all the packages we are keeping,
2813            // read and update their last usage times.
2814            mPackageUsage.read(mPackages);
2815            mCompilerStats.read();
2816
2817            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2818                    SystemClock.uptimeMillis());
2819            Slog.i(TAG, "Time to scan packages: "
2820                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2821                    + " seconds");
2822
2823            // If the platform SDK has changed since the last time we booted,
2824            // we need to re-grant app permission to catch any new ones that
2825            // appear.  This is really a hack, and means that apps can in some
2826            // cases get permissions that the user didn't initially explicitly
2827            // allow...  it would be nice to have some better way to handle
2828            // this situation.
2829            int updateFlags = UPDATE_PERMISSIONS_ALL;
2830            if (ver.sdkVersion != mSdkVersion) {
2831                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2832                        + mSdkVersion + "; regranting permissions for internal storage");
2833                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2834            }
2835            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2836            ver.sdkVersion = mSdkVersion;
2837
2838            // If this is the first boot or an update from pre-M, and it is a normal
2839            // boot, then we need to initialize the default preferred apps across
2840            // all defined users.
2841            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2842                for (UserInfo user : sUserManager.getUsers(true)) {
2843                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2844                    applyFactoryDefaultBrowserLPw(user.id);
2845                    primeDomainVerificationsLPw(user.id);
2846                }
2847            }
2848
2849            // Prepare storage for system user really early during boot,
2850            // since core system apps like SettingsProvider and SystemUI
2851            // can't wait for user to start
2852            final int storageFlags;
2853            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2854                storageFlags = StorageManager.FLAG_STORAGE_DE;
2855            } else {
2856                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2857            }
2858            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2859                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2860                    true /* onlyCoreApps */);
2861            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2862                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2863                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2864                traceLog.traceBegin("AppDataFixup");
2865                try {
2866                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2867                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2868                } catch (InstallerException e) {
2869                    Slog.w(TAG, "Trouble fixing GIDs", e);
2870                }
2871                traceLog.traceEnd();
2872
2873                traceLog.traceBegin("AppDataPrepare");
2874                if (deferPackages == null || deferPackages.isEmpty()) {
2875                    return;
2876                }
2877                int count = 0;
2878                for (String pkgName : deferPackages) {
2879                    PackageParser.Package pkg = null;
2880                    synchronized (mPackages) {
2881                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2882                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2883                            pkg = ps.pkg;
2884                        }
2885                    }
2886                    if (pkg != null) {
2887                        synchronized (mInstallLock) {
2888                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2889                                    true /* maybeMigrateAppData */);
2890                        }
2891                        count++;
2892                    }
2893                }
2894                traceLog.traceEnd();
2895                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2896            }, "prepareAppData");
2897
2898            // If this is first boot after an OTA, and a normal boot, then
2899            // we need to clear code cache directories.
2900            // Note that we do *not* clear the application profiles. These remain valid
2901            // across OTAs and are used to drive profile verification (post OTA) and
2902            // profile compilation (without waiting to collect a fresh set of profiles).
2903            if (mIsUpgrade && !onlyCore) {
2904                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2905                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2906                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2907                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2908                        // No apps are running this early, so no need to freeze
2909                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2910                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2911                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2912                    }
2913                }
2914                ver.fingerprint = Build.FINGERPRINT;
2915            }
2916
2917            checkDefaultBrowser();
2918
2919            // clear only after permissions and other defaults have been updated
2920            mExistingSystemPackages.clear();
2921            mPromoteSystemApps = false;
2922
2923            // All the changes are done during package scanning.
2924            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2925
2926            // can downgrade to reader
2927            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2928            mSettings.writeLPr();
2929            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2930
2931            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2932                    SystemClock.uptimeMillis());
2933
2934            if (!mOnlyCore) {
2935                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2936                mRequiredInstallerPackage = getRequiredInstallerLPr();
2937                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2938                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2939                if (mIntentFilterVerifierComponent != null) {
2940                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2941                            mIntentFilterVerifierComponent);
2942                } else {
2943                    mIntentFilterVerifier = null;
2944                }
2945                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2946                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2947                        SharedLibraryInfo.VERSION_UNDEFINED);
2948                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2949                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2950                        SharedLibraryInfo.VERSION_UNDEFINED);
2951            } else {
2952                mRequiredVerifierPackage = null;
2953                mRequiredInstallerPackage = null;
2954                mRequiredUninstallerPackage = null;
2955                mIntentFilterVerifierComponent = null;
2956                mIntentFilterVerifier = null;
2957                mServicesSystemSharedLibraryPackageName = null;
2958                mSharedSystemSharedLibraryPackageName = null;
2959            }
2960
2961            mInstallerService = new PackageInstallerService(context, this);
2962            final Pair<ComponentName, String> instantAppResolverComponent =
2963                    getInstantAppResolverLPr();
2964            if (instantAppResolverComponent != null) {
2965                if (DEBUG_EPHEMERAL) {
2966                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2967                }
2968                mInstantAppResolverConnection = new EphemeralResolverConnection(
2969                        mContext, instantAppResolverComponent.first,
2970                        instantAppResolverComponent.second);
2971                mInstantAppResolverSettingsComponent =
2972                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2973            } else {
2974                mInstantAppResolverConnection = null;
2975                mInstantAppResolverSettingsComponent = null;
2976            }
2977            updateInstantAppInstallerLocked(null);
2978
2979            // Read and update the usage of dex files.
2980            // Do this at the end of PM init so that all the packages have their
2981            // data directory reconciled.
2982            // At this point we know the code paths of the packages, so we can validate
2983            // the disk file and build the internal cache.
2984            // The usage file is expected to be small so loading and verifying it
2985            // should take a fairly small time compare to the other activities (e.g. package
2986            // scanning).
2987            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2988            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2989            for (int userId : currentUserIds) {
2990                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2991            }
2992            mDexManager.load(userPackages);
2993        } // synchronized (mPackages)
2994        } // synchronized (mInstallLock)
2995
2996        // Now after opening every single application zip, make sure they
2997        // are all flushed.  Not really needed, but keeps things nice and
2998        // tidy.
2999        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3000        Runtime.getRuntime().gc();
3001        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3002
3003        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3004        FallbackCategoryProvider.loadFallbacks();
3005        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3006
3007        // The initial scanning above does many calls into installd while
3008        // holding the mPackages lock, but we're mostly interested in yelling
3009        // once we have a booted system.
3010        mInstaller.setWarnIfHeld(mPackages);
3011
3012        // Expose private service for system components to use.
3013        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3014        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3015    }
3016
3017    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3018        // we're only interested in updating the installer appliction when 1) it's not
3019        // already set or 2) the modified package is the installer
3020        if (mInstantAppInstallerActivity != null
3021                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3022                        .equals(modifiedPackage)) {
3023            return;
3024        }
3025        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3026    }
3027
3028    private static File preparePackageParserCache(boolean isUpgrade) {
3029        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3030            return null;
3031        }
3032
3033        // Disable package parsing on eng builds to allow for faster incremental development.
3034        if ("eng".equals(Build.TYPE)) {
3035            return null;
3036        }
3037
3038        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3039            Slog.i(TAG, "Disabling package parser cache due to system property.");
3040            return null;
3041        }
3042
3043        // The base directory for the package parser cache lives under /data/system/.
3044        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3045                "package_cache");
3046        if (cacheBaseDir == null) {
3047            return null;
3048        }
3049
3050        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3051        // This also serves to "GC" unused entries when the package cache version changes (which
3052        // can only happen during upgrades).
3053        if (isUpgrade) {
3054            FileUtils.deleteContents(cacheBaseDir);
3055        }
3056
3057
3058        // Return the versioned package cache directory. This is something like
3059        // "/data/system/package_cache/1"
3060        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3061
3062        // The following is a workaround to aid development on non-numbered userdebug
3063        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3064        // the system partition is newer.
3065        //
3066        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3067        // that starts with "eng." to signify that this is an engineering build and not
3068        // destined for release.
3069        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3070            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3071
3072            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3073            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3074            // in general and should not be used for production changes. In this specific case,
3075            // we know that they will work.
3076            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3077            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3078                FileUtils.deleteContents(cacheBaseDir);
3079                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3080            }
3081        }
3082
3083        return cacheDir;
3084    }
3085
3086    @Override
3087    public boolean isFirstBoot() {
3088        // allow instant applications
3089        return mFirstBoot;
3090    }
3091
3092    @Override
3093    public boolean isOnlyCoreApps() {
3094        // allow instant applications
3095        return mOnlyCore;
3096    }
3097
3098    @Override
3099    public boolean isUpgrade() {
3100        // allow instant applications
3101        return mIsUpgrade;
3102    }
3103
3104    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3105        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3106
3107        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3108                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3109                UserHandle.USER_SYSTEM);
3110        if (matches.size() == 1) {
3111            return matches.get(0).getComponentInfo().packageName;
3112        } else if (matches.size() == 0) {
3113            Log.e(TAG, "There should probably be a verifier, but, none were found");
3114            return null;
3115        }
3116        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3117    }
3118
3119    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3120        synchronized (mPackages) {
3121            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3122            if (libraryEntry == null) {
3123                throw new IllegalStateException("Missing required shared library:" + name);
3124            }
3125            return libraryEntry.apk;
3126        }
3127    }
3128
3129    private @NonNull String getRequiredInstallerLPr() {
3130        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3131        intent.addCategory(Intent.CATEGORY_DEFAULT);
3132        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3133
3134        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3135                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3136                UserHandle.USER_SYSTEM);
3137        if (matches.size() == 1) {
3138            ResolveInfo resolveInfo = matches.get(0);
3139            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3140                throw new RuntimeException("The installer must be a privileged app");
3141            }
3142            return matches.get(0).getComponentInfo().packageName;
3143        } else {
3144            throw new RuntimeException("There must be exactly one installer; found " + matches);
3145        }
3146    }
3147
3148    private @NonNull String getRequiredUninstallerLPr() {
3149        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3150        intent.addCategory(Intent.CATEGORY_DEFAULT);
3151        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3152
3153        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3154                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3155                UserHandle.USER_SYSTEM);
3156        if (resolveInfo == null ||
3157                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3158            throw new RuntimeException("There must be exactly one uninstaller; found "
3159                    + resolveInfo);
3160        }
3161        return resolveInfo.getComponentInfo().packageName;
3162    }
3163
3164    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3165        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3166
3167        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3168                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3169                UserHandle.USER_SYSTEM);
3170        ResolveInfo best = null;
3171        final int N = matches.size();
3172        for (int i = 0; i < N; i++) {
3173            final ResolveInfo cur = matches.get(i);
3174            final String packageName = cur.getComponentInfo().packageName;
3175            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3176                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3177                continue;
3178            }
3179
3180            if (best == null || cur.priority > best.priority) {
3181                best = cur;
3182            }
3183        }
3184
3185        if (best != null) {
3186            return best.getComponentInfo().getComponentName();
3187        }
3188        Slog.w(TAG, "Intent filter verifier not found");
3189        return null;
3190    }
3191
3192    @Override
3193    public @Nullable ComponentName getInstantAppResolverComponent() {
3194        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3195            return null;
3196        }
3197        synchronized (mPackages) {
3198            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3199            if (instantAppResolver == null) {
3200                return null;
3201            }
3202            return instantAppResolver.first;
3203        }
3204    }
3205
3206    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3207        final String[] packageArray =
3208                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3209        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3210            if (DEBUG_EPHEMERAL) {
3211                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3212            }
3213            return null;
3214        }
3215
3216        final int callingUid = Binder.getCallingUid();
3217        final int resolveFlags =
3218                MATCH_DIRECT_BOOT_AWARE
3219                | MATCH_DIRECT_BOOT_UNAWARE
3220                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3221        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3222        final Intent resolverIntent = new Intent(actionName);
3223        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3224                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3225        // temporarily look for the old action
3226        if (resolvers.size() == 0) {
3227            if (DEBUG_EPHEMERAL) {
3228                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3229            }
3230            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3231            resolverIntent.setAction(actionName);
3232            resolvers = queryIntentServicesInternal(resolverIntent, null,
3233                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3234        }
3235        final int N = resolvers.size();
3236        if (N == 0) {
3237            if (DEBUG_EPHEMERAL) {
3238                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3239            }
3240            return null;
3241        }
3242
3243        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3244        for (int i = 0; i < N; i++) {
3245            final ResolveInfo info = resolvers.get(i);
3246
3247            if (info.serviceInfo == null) {
3248                continue;
3249            }
3250
3251            final String packageName = info.serviceInfo.packageName;
3252            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3253                if (DEBUG_EPHEMERAL) {
3254                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3255                            + " pkg: " + packageName + ", info:" + info);
3256                }
3257                continue;
3258            }
3259
3260            if (DEBUG_EPHEMERAL) {
3261                Slog.v(TAG, "Ephemeral resolver found;"
3262                        + " pkg: " + packageName + ", info:" + info);
3263            }
3264            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3265        }
3266        if (DEBUG_EPHEMERAL) {
3267            Slog.v(TAG, "Ephemeral resolver NOT found");
3268        }
3269        return null;
3270    }
3271
3272    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3273        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3274        intent.addCategory(Intent.CATEGORY_DEFAULT);
3275        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3276
3277        final int resolveFlags =
3278                MATCH_DIRECT_BOOT_AWARE
3279                | MATCH_DIRECT_BOOT_UNAWARE
3280                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3281        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3282                resolveFlags, UserHandle.USER_SYSTEM);
3283        // temporarily look for the old action
3284        if (matches.isEmpty()) {
3285            if (DEBUG_EPHEMERAL) {
3286                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3287            }
3288            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3289            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3290                    resolveFlags, UserHandle.USER_SYSTEM);
3291        }
3292        Iterator<ResolveInfo> iter = matches.iterator();
3293        while (iter.hasNext()) {
3294            final ResolveInfo rInfo = iter.next();
3295            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3296            if (ps != null) {
3297                final PermissionsState permissionsState = ps.getPermissionsState();
3298                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3299                    continue;
3300                }
3301            }
3302            iter.remove();
3303        }
3304        if (matches.size() == 0) {
3305            return null;
3306        } else if (matches.size() == 1) {
3307            return (ActivityInfo) matches.get(0).getComponentInfo();
3308        } else {
3309            throw new RuntimeException(
3310                    "There must be at most one ephemeral installer; found " + matches);
3311        }
3312    }
3313
3314    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3315            @NonNull ComponentName resolver) {
3316        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3317                .addCategory(Intent.CATEGORY_DEFAULT)
3318                .setPackage(resolver.getPackageName());
3319        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3320        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3321                UserHandle.USER_SYSTEM);
3322        // temporarily look for the old action
3323        if (matches.isEmpty()) {
3324            if (DEBUG_EPHEMERAL) {
3325                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3326            }
3327            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3328            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3329                    UserHandle.USER_SYSTEM);
3330        }
3331        if (matches.isEmpty()) {
3332            return null;
3333        }
3334        return matches.get(0).getComponentInfo().getComponentName();
3335    }
3336
3337    private void primeDomainVerificationsLPw(int userId) {
3338        if (DEBUG_DOMAIN_VERIFICATION) {
3339            Slog.d(TAG, "Priming domain verifications in user " + userId);
3340        }
3341
3342        SystemConfig systemConfig = SystemConfig.getInstance();
3343        ArraySet<String> packages = systemConfig.getLinkedApps();
3344
3345        for (String packageName : packages) {
3346            PackageParser.Package pkg = mPackages.get(packageName);
3347            if (pkg != null) {
3348                if (!pkg.isSystemApp()) {
3349                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3350                    continue;
3351                }
3352
3353                ArraySet<String> domains = null;
3354                for (PackageParser.Activity a : pkg.activities) {
3355                    for (ActivityIntentInfo filter : a.intents) {
3356                        if (hasValidDomains(filter)) {
3357                            if (domains == null) {
3358                                domains = new ArraySet<String>();
3359                            }
3360                            domains.addAll(filter.getHostsList());
3361                        }
3362                    }
3363                }
3364
3365                if (domains != null && domains.size() > 0) {
3366                    if (DEBUG_DOMAIN_VERIFICATION) {
3367                        Slog.v(TAG, "      + " + packageName);
3368                    }
3369                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3370                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3371                    // and then 'always' in the per-user state actually used for intent resolution.
3372                    final IntentFilterVerificationInfo ivi;
3373                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3374                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3375                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3376                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3377                } else {
3378                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3379                            + "' does not handle web links");
3380                }
3381            } else {
3382                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3383            }
3384        }
3385
3386        scheduleWritePackageRestrictionsLocked(userId);
3387        scheduleWriteSettingsLocked();
3388    }
3389
3390    private void applyFactoryDefaultBrowserLPw(int userId) {
3391        // The default browser app's package name is stored in a string resource,
3392        // with a product-specific overlay used for vendor customization.
3393        String browserPkg = mContext.getResources().getString(
3394                com.android.internal.R.string.default_browser);
3395        if (!TextUtils.isEmpty(browserPkg)) {
3396            // non-empty string => required to be a known package
3397            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3398            if (ps == null) {
3399                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3400                browserPkg = null;
3401            } else {
3402                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3403            }
3404        }
3405
3406        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3407        // default.  If there's more than one, just leave everything alone.
3408        if (browserPkg == null) {
3409            calculateDefaultBrowserLPw(userId);
3410        }
3411    }
3412
3413    private void calculateDefaultBrowserLPw(int userId) {
3414        List<String> allBrowsers = resolveAllBrowserApps(userId);
3415        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3416        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3417    }
3418
3419    private List<String> resolveAllBrowserApps(int userId) {
3420        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3421        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3422                PackageManager.MATCH_ALL, userId);
3423
3424        final int count = list.size();
3425        List<String> result = new ArrayList<String>(count);
3426        for (int i=0; i<count; i++) {
3427            ResolveInfo info = list.get(i);
3428            if (info.activityInfo == null
3429                    || !info.handleAllWebDataURI
3430                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3431                    || result.contains(info.activityInfo.packageName)) {
3432                continue;
3433            }
3434            result.add(info.activityInfo.packageName);
3435        }
3436
3437        return result;
3438    }
3439
3440    private boolean packageIsBrowser(String packageName, int userId) {
3441        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3442                PackageManager.MATCH_ALL, userId);
3443        final int N = list.size();
3444        for (int i = 0; i < N; i++) {
3445            ResolveInfo info = list.get(i);
3446            if (packageName.equals(info.activityInfo.packageName)) {
3447                return true;
3448            }
3449        }
3450        return false;
3451    }
3452
3453    private void checkDefaultBrowser() {
3454        final int myUserId = UserHandle.myUserId();
3455        final String packageName = getDefaultBrowserPackageName(myUserId);
3456        if (packageName != null) {
3457            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3458            if (info == null) {
3459                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3460                synchronized (mPackages) {
3461                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3462                }
3463            }
3464        }
3465    }
3466
3467    @Override
3468    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3469            throws RemoteException {
3470        try {
3471            return super.onTransact(code, data, reply, flags);
3472        } catch (RuntimeException e) {
3473            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3474                Slog.wtf(TAG, "Package Manager Crash", e);
3475            }
3476            throw e;
3477        }
3478    }
3479
3480    static int[] appendInts(int[] cur, int[] add) {
3481        if (add == null) return cur;
3482        if (cur == null) return add;
3483        final int N = add.length;
3484        for (int i=0; i<N; i++) {
3485            cur = appendInt(cur, add[i]);
3486        }
3487        return cur;
3488    }
3489
3490    /**
3491     * Returns whether or not a full application can see an instant application.
3492     * <p>
3493     * Currently, there are three cases in which this can occur:
3494     * <ol>
3495     * <li>The calling application is a "special" process. The special
3496     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3497     *     and {@code 0}</li>
3498     * <li>The calling application has the permission
3499     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3500     * <li>[TODO] The calling application is the default launcher on the
3501     *     system partition.</li>
3502     * </ol>
3503     */
3504    private boolean canAccessInstantApps(int callingUid) {
3505        final boolean isSpecialProcess =
3506                callingUid == Process.SYSTEM_UID
3507                        || callingUid == Process.SHELL_UID
3508                        || callingUid == Process.ROOT_UID;
3509        final boolean allowMatchInstant =
3510                isSpecialProcess
3511                        || mContext.checkCallingOrSelfPermission(
3512                        android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED;
3513        return allowMatchInstant;
3514    }
3515
3516    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3517        if (!sUserManager.exists(userId)) return null;
3518        if (ps == null) {
3519            return null;
3520        }
3521        PackageParser.Package p = ps.pkg;
3522        if (p == null) {
3523            return null;
3524        }
3525        final int callingUid = Binder.getCallingUid();
3526        // Filter out ephemeral app metadata:
3527        //   * The system/shell/root can see metadata for any app
3528        //   * An installed app can see metadata for 1) other installed apps
3529        //     and 2) ephemeral apps that have explicitly interacted with it
3530        //   * Ephemeral apps can only see their own data and exposed installed apps
3531        //   * Holding a signature permission allows seeing instant apps
3532        if (!canAccessInstantApps(callingUid)) {
3533            final String instantAppPackageName = getInstantAppPackageName(callingUid);
3534            if (instantAppPackageName != null) {
3535                // ephemeral apps can only get information on themselves or
3536                // installed apps that are exposed.
3537                if (!instantAppPackageName.equals(p.packageName)
3538                        && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) {
3539                    return null;
3540                }
3541            } else {
3542                if (ps.getInstantApp(userId)) {
3543                    // only get access to the ephemeral app if we've been granted access
3544                    final int callingAppId = UserHandle.getAppId(callingUid);
3545                    if (!mInstantAppRegistry.isInstantAccessGranted(
3546                            userId, callingAppId, ps.appId)) {
3547                        return null;
3548                    }
3549                }
3550            }
3551        }
3552
3553        final PermissionsState permissionsState = ps.getPermissionsState();
3554
3555        // Compute GIDs only if requested
3556        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3557                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3558        // Compute granted permissions only if package has requested permissions
3559        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3560                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3561        final PackageUserState state = ps.readUserState(userId);
3562
3563        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3564                && ps.isSystem()) {
3565            flags |= MATCH_ANY_USER;
3566        }
3567
3568        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3569                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3570
3571        if (packageInfo == null) {
3572            return null;
3573        }
3574
3575        rebaseEnabledOverlays(packageInfo.applicationInfo, userId);
3576
3577        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3578                resolveExternalPackageNameLPr(p);
3579
3580        return packageInfo;
3581    }
3582
3583    @Override
3584    public void checkPackageStartable(String packageName, int userId) {
3585        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3586            throw new SecurityException("Instant applications don't have access to this method");
3587        }
3588        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3589        synchronized (mPackages) {
3590            final PackageSetting ps = mSettings.mPackages.get(packageName);
3591            if (ps == null) {
3592                throw new SecurityException("Package " + packageName + " was not found!");
3593            }
3594
3595            if (!ps.getInstalled(userId)) {
3596                throw new SecurityException(
3597                        "Package " + packageName + " was not installed for user " + userId + "!");
3598            }
3599
3600            if (mSafeMode && !ps.isSystem()) {
3601                throw new SecurityException("Package " + packageName + " not a system app!");
3602            }
3603
3604            if (mFrozenPackages.contains(packageName)) {
3605                throw new SecurityException("Package " + packageName + " is currently frozen!");
3606            }
3607
3608            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3609                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3610                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3611            }
3612        }
3613    }
3614
3615    @Override
3616    public boolean isPackageAvailable(String packageName, int userId) {
3617        if (!sUserManager.exists(userId)) return false;
3618        final int callingUid = Binder.getCallingUid();
3619        enforceCrossUserPermission(callingUid, userId,
3620                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3621        synchronized (mPackages) {
3622            PackageParser.Package p = mPackages.get(packageName);
3623            if (p != null) {
3624                final PackageSetting ps = (PackageSetting) p.mExtras;
3625                if (filterAppAccessLPr(ps, callingUid, userId)) {
3626                    return false;
3627                }
3628                if (ps != null) {
3629                    final PackageUserState state = ps.readUserState(userId);
3630                    if (state != null) {
3631                        return PackageParser.isAvailable(state);
3632                    }
3633                }
3634            }
3635        }
3636        return false;
3637    }
3638
3639    @Override
3640    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3641        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3642                flags, userId);
3643    }
3644
3645    @Override
3646    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3647            int flags, int userId) {
3648        return getPackageInfoInternal(versionedPackage.getPackageName(),
3649                versionedPackage.getVersionCode(), flags, userId);
3650    }
3651
3652    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3653            int flags, int userId) {
3654        if (!sUserManager.exists(userId)) return null;
3655        final int callingUid = Binder.getCallingUid();
3656        flags = updateFlagsForPackage(flags, userId, packageName);
3657        enforceCrossUserPermission(callingUid, userId,
3658                false /* requireFullPermission */, false /* checkShell */, "get package info");
3659
3660        // reader
3661        synchronized (mPackages) {
3662            // Normalize package name to handle renamed packages and static libs
3663            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3664
3665            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3666            if (matchFactoryOnly) {
3667                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3668                if (ps != null) {
3669                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
3670                        return null;
3671                    }
3672                    if (filterAppAccessLPr(ps, callingUid, userId)) {
3673                        return null;
3674                    }
3675                    return generatePackageInfo(ps, flags, userId);
3676                }
3677            }
3678
3679            PackageParser.Package p = mPackages.get(packageName);
3680            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3681                return null;
3682            }
3683            if (DEBUG_PACKAGE_INFO)
3684                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3685            if (p != null) {
3686                final PackageSetting ps = (PackageSetting) p.mExtras;
3687                if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
3688                    return null;
3689                }
3690                if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
3691                    return null;
3692                }
3693                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3694            }
3695            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3696                final PackageSetting ps = mSettings.mPackages.get(packageName);
3697                if (ps == null) return null;
3698                if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
3699                    return null;
3700                }
3701                if (filterAppAccessLPr(ps, callingUid, userId)) {
3702                    return null;
3703                }
3704                return generatePackageInfo(ps, flags, userId);
3705            }
3706        }
3707        return null;
3708    }
3709
3710    /**
3711     * Returns whether or not access to the application should be filtered.
3712     * <p>
3713     * Access may be limited based upon whether the calling or target applications
3714     * are instant applications.
3715     *
3716     * @see #canAccessInstantApps(int)
3717     */
3718    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3719            @Nullable ComponentName component, boolean componentVisibleToInstantApp, int userId) {
3720        // if we're in an isolated process, get the real calling UID
3721        if (Process.isIsolated(callingUid)) {
3722            callingUid = mIsolatedOwners.get(callingUid);
3723        }
3724        final String instantAppPkgName = getInstantAppPackageName(callingUid);
3725        final boolean callerIsInstantApp = instantAppPkgName != null;
3726        if (ps == null) {
3727            if (callerIsInstantApp) {
3728                // pretend the application exists, but, needs to be filtered
3729                return true;
3730            }
3731            return false;
3732        }
3733        // if the target and caller are the same application, don't filter
3734        if (isCallerSameApp(ps.name, callingUid)) {
3735            return false;
3736        }
3737        if (callerIsInstantApp) {
3738            // request for a specific component; if it hasn't been explicitly exposed, filter
3739            if (component != null) {
3740                return !componentVisibleToInstantApp;
3741            }
3742            // request for application; if no components have been explicitly exposed, filter
3743            return !ps.pkg.visibleToInstantApps;
3744        }
3745        if (ps.getInstantApp(userId)) {
3746            // caller can see all components of all instant applications, don't filter
3747            if (canAccessInstantApps(callingUid)) {
3748                return false;
3749            }
3750            // request for a specific instant application component, filter
3751            if (component != null) {
3752                return true;
3753            }
3754            // request for an instant application; if the caller hasn't been granted access, filter
3755            return !mInstantAppRegistry.isInstantAccessGranted(
3756                    userId, UserHandle.getAppId(callingUid), ps.appId);
3757        }
3758        return false;
3759    }
3760
3761    /**
3762     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3763     */
3764    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3765        return filterAppAccessLPr(ps, callingUid, null, false, userId);
3766    }
3767
3768    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3769            int flags) {
3770        // Callers can access only the libs they depend on, otherwise they need to explicitly
3771        // ask for the shared libraries given the caller is allowed to access all static libs.
3772        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3773            // System/shell/root get to see all static libs
3774            final int appId = UserHandle.getAppId(uid);
3775            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3776                    || appId == Process.ROOT_UID) {
3777                return false;
3778            }
3779        }
3780
3781        // No package means no static lib as it is always on internal storage
3782        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3783            return false;
3784        }
3785
3786        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3787                ps.pkg.staticSharedLibVersion);
3788        if (libEntry == null) {
3789            return false;
3790        }
3791
3792        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3793        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3794        if (uidPackageNames == null) {
3795            return true;
3796        }
3797
3798        for (String uidPackageName : uidPackageNames) {
3799            if (ps.name.equals(uidPackageName)) {
3800                return false;
3801            }
3802            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3803            if (uidPs != null) {
3804                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3805                        libEntry.info.getName());
3806                if (index < 0) {
3807                    continue;
3808                }
3809                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3810                    return false;
3811                }
3812            }
3813        }
3814        return true;
3815    }
3816
3817    @Override
3818    public String[] currentToCanonicalPackageNames(String[] names) {
3819        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3820            return names;
3821        }
3822        String[] out = new String[names.length];
3823        // reader
3824        synchronized (mPackages) {
3825            for (int i=names.length-1; i>=0; i--) {
3826                PackageSetting ps = mSettings.mPackages.get(names[i]);
3827                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3828            }
3829        }
3830        return out;
3831    }
3832
3833    @Override
3834    public String[] canonicalToCurrentPackageNames(String[] names) {
3835        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3836            return names;
3837        }
3838        String[] out = new String[names.length];
3839        // reader
3840        synchronized (mPackages) {
3841            for (int i=names.length-1; i>=0; i--) {
3842                String cur = mSettings.getRenamedPackageLPr(names[i]);
3843                out[i] = cur != null ? cur : names[i];
3844            }
3845        }
3846        return out;
3847    }
3848
3849    @Override
3850    public int getPackageUid(String packageName, int flags, int userId) {
3851        if (!sUserManager.exists(userId)) return -1;
3852        final int callingUid = Binder.getCallingUid();
3853        flags = updateFlagsForPackage(flags, userId, packageName);
3854        enforceCrossUserPermission(callingUid, userId,
3855                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
3856
3857        // reader
3858        synchronized (mPackages) {
3859            final PackageParser.Package p = mPackages.get(packageName);
3860            if (p != null && p.isMatch(flags)) {
3861                PackageSetting ps = (PackageSetting) p.mExtras;
3862                if (filterAppAccessLPr(ps, callingUid, userId)) {
3863                    return -1;
3864                }
3865                return UserHandle.getUid(userId, p.applicationInfo.uid);
3866            }
3867            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3868                final PackageSetting ps = mSettings.mPackages.get(packageName);
3869                if (ps != null && ps.isMatch(flags)
3870                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3871                    return UserHandle.getUid(userId, ps.appId);
3872                }
3873            }
3874        }
3875
3876        return -1;
3877    }
3878
3879    @Override
3880    public int[] getPackageGids(String packageName, int flags, int userId) {
3881        if (!sUserManager.exists(userId)) return null;
3882        final int callingUid = Binder.getCallingUid();
3883        flags = updateFlagsForPackage(flags, userId, packageName);
3884        enforceCrossUserPermission(callingUid, userId,
3885                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
3886
3887        // reader
3888        synchronized (mPackages) {
3889            final PackageParser.Package p = mPackages.get(packageName);
3890            if (p != null && p.isMatch(flags)) {
3891                PackageSetting ps = (PackageSetting) p.mExtras;
3892                if (filterAppAccessLPr(ps, callingUid, userId)) {
3893                    return null;
3894                }
3895                // TODO: Shouldn't this be checking for package installed state for userId and
3896                // return null?
3897                return ps.getPermissionsState().computeGids(userId);
3898            }
3899            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3900                final PackageSetting ps = mSettings.mPackages.get(packageName);
3901                if (ps != null && ps.isMatch(flags)
3902                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3903                    return ps.getPermissionsState().computeGids(userId);
3904                }
3905            }
3906        }
3907
3908        return null;
3909    }
3910
3911    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3912        if (bp.perm != null) {
3913            return PackageParser.generatePermissionInfo(bp.perm, flags);
3914        }
3915        PermissionInfo pi = new PermissionInfo();
3916        pi.name = bp.name;
3917        pi.packageName = bp.sourcePackage;
3918        pi.nonLocalizedLabel = bp.name;
3919        pi.protectionLevel = bp.protectionLevel;
3920        return pi;
3921    }
3922
3923    @Override
3924    public PermissionInfo getPermissionInfo(String name, int flags) {
3925        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3926            return null;
3927        }
3928        // reader
3929        synchronized (mPackages) {
3930            final BasePermission p = mSettings.mPermissions.get(name);
3931            if (p != null) {
3932                return generatePermissionInfo(p, flags);
3933            }
3934            return null;
3935        }
3936    }
3937
3938    @Override
3939    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3940            int flags) {
3941        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3942            return null;
3943        }
3944        // reader
3945        synchronized (mPackages) {
3946            if (group != null && !mPermissionGroups.containsKey(group)) {
3947                // This is thrown as NameNotFoundException
3948                return null;
3949            }
3950
3951            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3952            for (BasePermission p : mSettings.mPermissions.values()) {
3953                if (group == null) {
3954                    if (p.perm == null || p.perm.info.group == null) {
3955                        out.add(generatePermissionInfo(p, flags));
3956                    }
3957                } else {
3958                    if (p.perm != null && group.equals(p.perm.info.group)) {
3959                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3960                    }
3961                }
3962            }
3963            return new ParceledListSlice<>(out);
3964        }
3965    }
3966
3967    @Override
3968    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3969        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3970            return null;
3971        }
3972        // reader
3973        synchronized (mPackages) {
3974            return PackageParser.generatePermissionGroupInfo(
3975                    mPermissionGroups.get(name), flags);
3976        }
3977    }
3978
3979    @Override
3980    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3981        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3982            return ParceledListSlice.emptyList();
3983        }
3984        // reader
3985        synchronized (mPackages) {
3986            final int N = mPermissionGroups.size();
3987            ArrayList<PermissionGroupInfo> out
3988                    = new ArrayList<PermissionGroupInfo>(N);
3989            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3990                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3991            }
3992            return new ParceledListSlice<>(out);
3993        }
3994    }
3995
3996    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3997            int uid, int userId) {
3998        if (!sUserManager.exists(userId)) return null;
3999        PackageSetting ps = mSettings.mPackages.get(packageName);
4000        if (ps != null) {
4001            if (filterSharedLibPackageLPr(ps, uid, userId, flags)) {
4002                return null;
4003            }
4004            if (filterAppAccessLPr(ps, uid, userId)) {
4005                return null;
4006            }
4007            if (ps.pkg == null) {
4008                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4009                if (pInfo != null) {
4010                    return pInfo.applicationInfo;
4011                }
4012                return null;
4013            }
4014            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4015                    ps.readUserState(userId), userId);
4016            if (ai != null) {
4017                rebaseEnabledOverlays(ai, userId);
4018                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4019            }
4020            return ai;
4021        }
4022        return null;
4023    }
4024
4025    @Override
4026    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4027        if (!sUserManager.exists(userId)) return null;
4028        flags = updateFlagsForApplication(flags, userId, packageName);
4029        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4030                false /* requireFullPermission */, false /* checkShell */, "get application info");
4031
4032        // writer
4033        synchronized (mPackages) {
4034            // Normalize package name to handle renamed packages and static libs
4035            packageName = resolveInternalPackageNameLPr(packageName,
4036                    PackageManager.VERSION_CODE_HIGHEST);
4037
4038            PackageParser.Package p = mPackages.get(packageName);
4039            if (DEBUG_PACKAGE_INFO) Log.v(
4040                    TAG, "getApplicationInfo " + packageName
4041                    + ": " + p);
4042            if (p != null) {
4043                PackageSetting ps = mSettings.mPackages.get(packageName);
4044                if (ps == null) return null;
4045                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
4046                    return null;
4047                }
4048                if (filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
4049                    return null;
4050                }
4051                // Note: isEnabledLP() does not apply here - always return info
4052                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4053                        p, flags, ps.readUserState(userId), userId);
4054                if (ai != null) {
4055                    rebaseEnabledOverlays(ai, userId);
4056                    ai.packageName = resolveExternalPackageNameLPr(p);
4057                }
4058                return ai;
4059            }
4060            if ("android".equals(packageName)||"system".equals(packageName)) {
4061                return mAndroidApplication;
4062            }
4063            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4064                // Already generates the external package name
4065                return generateApplicationInfoFromSettingsLPw(packageName,
4066                        Binder.getCallingUid(), flags, userId);
4067            }
4068        }
4069        return null;
4070    }
4071
4072    private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) {
4073        List<String> paths = new ArrayList<>();
4074        ArrayMap<String, ArrayList<String>> userSpecificOverlays =
4075            mEnabledOverlayPaths.get(userId);
4076        if (userSpecificOverlays != null) {
4077            if (!"android".equals(ai.packageName)) {
4078                ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android");
4079                if (frameworkOverlays != null) {
4080                    paths.addAll(frameworkOverlays);
4081                }
4082            }
4083
4084            ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName);
4085            if (appOverlays != null) {
4086                paths.addAll(appOverlays);
4087            }
4088        }
4089        ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null;
4090    }
4091
4092    private String normalizePackageNameLPr(String packageName) {
4093        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4094        return normalizedPackageName != null ? normalizedPackageName : packageName;
4095    }
4096
4097    @Override
4098    public void deletePreloadsFileCache() {
4099        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4100            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4101        }
4102        File dir = Environment.getDataPreloadsFileCacheDirectory();
4103        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4104        FileUtils.deleteContents(dir);
4105    }
4106
4107    @Override
4108    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4109            final IPackageDataObserver observer) {
4110        mContext.enforceCallingOrSelfPermission(
4111                android.Manifest.permission.CLEAR_APP_CACHE, null);
4112        mHandler.post(() -> {
4113            boolean success = false;
4114            try {
4115                freeStorage(volumeUuid, freeStorageSize, 0);
4116                success = true;
4117            } catch (IOException e) {
4118                Slog.w(TAG, e);
4119            }
4120            if (observer != null) {
4121                try {
4122                    observer.onRemoveCompleted(null, success);
4123                } catch (RemoteException e) {
4124                    Slog.w(TAG, e);
4125                }
4126            }
4127        });
4128    }
4129
4130    @Override
4131    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4132            final IntentSender pi) {
4133        mContext.enforceCallingOrSelfPermission(
4134                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4135        mHandler.post(() -> {
4136            boolean success = false;
4137            try {
4138                freeStorage(volumeUuid, freeStorageSize, 0);
4139                success = true;
4140            } catch (IOException e) {
4141                Slog.w(TAG, e);
4142            }
4143            if (pi != null) {
4144                try {
4145                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4146                } catch (SendIntentException e) {
4147                    Slog.w(TAG, e);
4148                }
4149            }
4150        });
4151    }
4152
4153    /**
4154     * Blocking call to clear various types of cached data across the system
4155     * until the requested bytes are available.
4156     */
4157    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4158        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4159        final File file = storage.findPathForUuid(volumeUuid);
4160        if (file.getUsableSpace() >= bytes) return;
4161
4162        if (ENABLE_FREE_CACHE_V2) {
4163            final boolean aggressive = (storageFlags
4164                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4165            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4166                    volumeUuid);
4167
4168            // 1. Pre-flight to determine if we have any chance to succeed
4169            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4170            if (internalVolume && (aggressive || SystemProperties
4171                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4172                deletePreloadsFileCache();
4173                if (file.getUsableSpace() >= bytes) return;
4174            }
4175
4176            // 3. Consider parsed APK data (aggressive only)
4177            if (internalVolume && aggressive) {
4178                FileUtils.deleteContents(mCacheDir);
4179                if (file.getUsableSpace() >= bytes) return;
4180            }
4181
4182            // 4. Consider cached app data (above quotas)
4183            try {
4184                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2);
4185            } catch (InstallerException ignored) {
4186            }
4187            if (file.getUsableSpace() >= bytes) return;
4188
4189            // 5. Consider shared libraries with refcount=0 and age>2h
4190            // 6. Consider dexopt output (aggressive only)
4191            // 7. Consider ephemeral apps not used in last week
4192
4193            // 8. Consider cached app data (below quotas)
4194            try {
4195                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2
4196                        | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4197            } catch (InstallerException ignored) {
4198            }
4199            if (file.getUsableSpace() >= bytes) return;
4200
4201            // 9. Consider DropBox entries
4202            // 10. Consider ephemeral cookies
4203
4204        } else {
4205            try {
4206                mInstaller.freeCache(volumeUuid, bytes, 0);
4207            } catch (InstallerException ignored) {
4208            }
4209            if (file.getUsableSpace() >= bytes) return;
4210        }
4211
4212        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4213    }
4214
4215    /**
4216     * Update given flags based on encryption status of current user.
4217     */
4218    private int updateFlags(int flags, int userId) {
4219        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4220                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4221            // Caller expressed an explicit opinion about what encryption
4222            // aware/unaware components they want to see, so fall through and
4223            // give them what they want
4224        } else {
4225            // Caller expressed no opinion, so match based on user state
4226            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4227                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4228            } else {
4229                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4230            }
4231        }
4232        return flags;
4233    }
4234
4235    private UserManagerInternal getUserManagerInternal() {
4236        if (mUserManagerInternal == null) {
4237            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4238        }
4239        return mUserManagerInternal;
4240    }
4241
4242    private DeviceIdleController.LocalService getDeviceIdleController() {
4243        if (mDeviceIdleController == null) {
4244            mDeviceIdleController =
4245                    LocalServices.getService(DeviceIdleController.LocalService.class);
4246        }
4247        return mDeviceIdleController;
4248    }
4249
4250    /**
4251     * Update given flags when being used to request {@link PackageInfo}.
4252     */
4253    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4254        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4255        boolean triaged = true;
4256        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4257                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4258            // Caller is asking for component details, so they'd better be
4259            // asking for specific encryption matching behavior, or be triaged
4260            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4261                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4262                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4263                triaged = false;
4264            }
4265        }
4266        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4267                | PackageManager.MATCH_SYSTEM_ONLY
4268                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4269            triaged = false;
4270        }
4271        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4272            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4273                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4274                    + Debug.getCallers(5));
4275        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4276                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4277            // If the caller wants all packages and has a restricted profile associated with it,
4278            // then match all users. This is to make sure that launchers that need to access work
4279            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4280            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4281            flags |= PackageManager.MATCH_ANY_USER;
4282        }
4283        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4284            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4285                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4286        }
4287        return updateFlags(flags, userId);
4288    }
4289
4290    /**
4291     * Update given flags when being used to request {@link ApplicationInfo}.
4292     */
4293    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4294        return updateFlagsForPackage(flags, userId, cookie);
4295    }
4296
4297    /**
4298     * Update given flags when being used to request {@link ComponentInfo}.
4299     */
4300    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4301        if (cookie instanceof Intent) {
4302            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4303                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4304            }
4305        }
4306
4307        boolean triaged = true;
4308        // Caller is asking for component details, so they'd better be
4309        // asking for specific encryption matching behavior, or be triaged
4310        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4311                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4312                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4313            triaged = false;
4314        }
4315        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4316            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4317                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4318        }
4319
4320        return updateFlags(flags, userId);
4321    }
4322
4323    /**
4324     * Update given intent when being used to request {@link ResolveInfo}.
4325     */
4326    private Intent updateIntentForResolve(Intent intent) {
4327        if (intent.getSelector() != null) {
4328            intent = intent.getSelector();
4329        }
4330        if (DEBUG_PREFERRED) {
4331            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4332        }
4333        return intent;
4334    }
4335
4336    /**
4337     * Update given flags when being used to request {@link ResolveInfo}.
4338     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4339     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4340     * flag set. However, this flag is only honoured in three circumstances:
4341     * <ul>
4342     * <li>when called from a system process</li>
4343     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4344     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4345     * action and a {@code android.intent.category.BROWSABLE} category</li>
4346     * </ul>
4347     */
4348    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4349        return updateFlagsForResolve(flags, userId, intent, callingUid,
4350                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4351    }
4352    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4353            boolean wantInstantApps) {
4354        return updateFlagsForResolve(flags, userId, intent, callingUid,
4355                wantInstantApps, false /*onlyExposedExplicitly*/);
4356    }
4357    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4358            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4359        // Safe mode means we shouldn't match any third-party components
4360        if (mSafeMode) {
4361            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4362        }
4363        if (getInstantAppPackageName(callingUid) != null) {
4364            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4365            if (onlyExposedExplicitly) {
4366                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4367            }
4368            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4369            flags |= PackageManager.MATCH_INSTANT;
4370        } else {
4371            final boolean allowMatchInstant =
4372                    (wantInstantApps
4373                            && Intent.ACTION_VIEW.equals(intent.getAction())
4374                            && hasWebURI(intent))
4375                    || canAccessInstantApps(callingUid);
4376            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4377                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4378            if (!allowMatchInstant) {
4379                flags &= ~PackageManager.MATCH_INSTANT;
4380            }
4381        }
4382        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4383    }
4384
4385    private ActivityInfo generateActivityInfo(ActivityInfo ai, int flags, PackageUserState state,
4386            int userId) {
4387        ActivityInfo ret = PackageParser.generateActivityInfo(ai, flags, state, userId);
4388        if (ret != null) {
4389            rebaseEnabledOverlays(ret.applicationInfo, userId);
4390        }
4391        return ret;
4392    }
4393
4394    private ActivityInfo generateActivityInfo(PackageParser.Activity a, int flags,
4395            PackageUserState state, int userId) {
4396        ActivityInfo ai = PackageParser.generateActivityInfo(a, flags, state, userId);
4397        if (ai != null) {
4398            rebaseEnabledOverlays(ai.applicationInfo, userId);
4399        }
4400        return ai;
4401    }
4402
4403    @Override
4404    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4405        if (!sUserManager.exists(userId)) return null;
4406        final int callingUid = Binder.getCallingUid();
4407        flags = updateFlagsForComponent(flags, userId, component);
4408        enforceCrossUserPermission(callingUid, userId,
4409                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4410        synchronized (mPackages) {
4411            PackageParser.Activity a = mActivities.mActivities.get(component);
4412
4413            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4414            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4415                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4416                if (ps == null) return null;
4417                final boolean visibleToInstantApp =
4418                        (a.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4419                if (filterAppAccessLPr(ps, callingUid, component, visibleToInstantApp, userId)) {
4420                    return null;
4421                }
4422                return generateActivityInfo(a, flags, ps.readUserState(userId), userId);
4423            }
4424            if (mResolveComponentName.equals(component)) {
4425                return generateActivityInfo(mResolveActivity, flags, new PackageUserState(),
4426                        userId);
4427            }
4428        }
4429        return null;
4430    }
4431
4432    @Override
4433    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4434            String resolvedType) {
4435        synchronized (mPackages) {
4436            if (component.equals(mResolveComponentName)) {
4437                // The resolver supports EVERYTHING!
4438                return true;
4439            }
4440            final int callingUid = Binder.getCallingUid();
4441            final int callingUserId = UserHandle.getUserId(callingUid);
4442            PackageParser.Activity a = mActivities.mActivities.get(component);
4443            if (a == null) {
4444                return false;
4445            }
4446            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4447            if (ps == null) {
4448                return false;
4449            }
4450            final boolean visibleToInstantApp =
4451                    (a.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4452            if (filterAppAccessLPr(ps, callingUid, component, visibleToInstantApp, callingUserId)) {
4453                return false;
4454            }
4455            for (int i=0; i<a.intents.size(); i++) {
4456                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4457                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4458                    return true;
4459                }
4460            }
4461            return false;
4462        }
4463    }
4464
4465    @Override
4466    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4467        if (!sUserManager.exists(userId)) return null;
4468        flags = updateFlagsForComponent(flags, userId, component);
4469        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4470                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4471        synchronized (mPackages) {
4472            PackageParser.Activity a = mReceivers.mActivities.get(component);
4473            if (DEBUG_PACKAGE_INFO) Log.v(
4474                TAG, "getReceiverInfo " + component + ": " + a);
4475            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4476                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4477                if (ps == null) return null;
4478                return generateActivityInfo(a, flags, ps.readUserState(userId), userId);
4479            }
4480        }
4481        return null;
4482    }
4483
4484    @Override
4485    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4486            int flags, int userId) {
4487        if (!sUserManager.exists(userId)) return null;
4488        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4489        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4490            return null;
4491        }
4492
4493        flags = updateFlagsForPackage(flags, userId, null);
4494
4495        final boolean canSeeStaticLibraries =
4496                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4497                        == PERMISSION_GRANTED
4498                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4499                        == PERMISSION_GRANTED
4500                || canRequestPackageInstallsInternal(packageName,
4501                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4502                        false  /* throwIfPermNotDeclared*/)
4503                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4504                        == PERMISSION_GRANTED;
4505
4506        synchronized (mPackages) {
4507            List<SharedLibraryInfo> result = null;
4508
4509            final int libCount = mSharedLibraries.size();
4510            for (int i = 0; i < libCount; i++) {
4511                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4512                if (versionedLib == null) {
4513                    continue;
4514                }
4515
4516                final int versionCount = versionedLib.size();
4517                for (int j = 0; j < versionCount; j++) {
4518                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4519                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4520                        break;
4521                    }
4522                    final long identity = Binder.clearCallingIdentity();
4523                    try {
4524                        PackageInfo packageInfo = getPackageInfoVersioned(
4525                                libInfo.getDeclaringPackage(), flags
4526                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4527                        if (packageInfo == null) {
4528                            continue;
4529                        }
4530                    } finally {
4531                        Binder.restoreCallingIdentity(identity);
4532                    }
4533
4534                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4535                            libInfo.getVersion(), libInfo.getType(),
4536                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4537                            flags, userId));
4538
4539                    if (result == null) {
4540                        result = new ArrayList<>();
4541                    }
4542                    result.add(resLibInfo);
4543                }
4544            }
4545
4546            return result != null ? new ParceledListSlice<>(result) : null;
4547        }
4548    }
4549
4550    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4551            SharedLibraryInfo libInfo, int flags, int userId) {
4552        List<VersionedPackage> versionedPackages = null;
4553        final int packageCount = mSettings.mPackages.size();
4554        for (int i = 0; i < packageCount; i++) {
4555            PackageSetting ps = mSettings.mPackages.valueAt(i);
4556
4557            if (ps == null) {
4558                continue;
4559            }
4560
4561            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4562                continue;
4563            }
4564
4565            final String libName = libInfo.getName();
4566            if (libInfo.isStatic()) {
4567                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4568                if (libIdx < 0) {
4569                    continue;
4570                }
4571                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4572                    continue;
4573                }
4574                if (versionedPackages == null) {
4575                    versionedPackages = new ArrayList<>();
4576                }
4577                // If the dependent is a static shared lib, use the public package name
4578                String dependentPackageName = ps.name;
4579                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4580                    dependentPackageName = ps.pkg.manifestPackageName;
4581                }
4582                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4583            } else if (ps.pkg != null) {
4584                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4585                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4586                    if (versionedPackages == null) {
4587                        versionedPackages = new ArrayList<>();
4588                    }
4589                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4590                }
4591            }
4592        }
4593
4594        return versionedPackages;
4595    }
4596
4597    @Override
4598    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4599        if (!sUserManager.exists(userId)) return null;
4600        final int callingUid = Binder.getCallingUid();
4601        flags = updateFlagsForComponent(flags, userId, component);
4602        enforceCrossUserPermission(callingUid, userId,
4603                false /* requireFullPermission */, false /* checkShell */, "get service info");
4604        synchronized (mPackages) {
4605            PackageParser.Service s = mServices.mServices.get(component);
4606            if (DEBUG_PACKAGE_INFO) Log.v(
4607                TAG, "getServiceInfo " + component + ": " + s);
4608            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4609                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4610                if (ps == null) return null;
4611                final boolean visibleToInstantApp =
4612                        (s.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4613                if (filterAppAccessLPr(ps, callingUid, component, visibleToInstantApp, userId)) {
4614                    return null;
4615                }
4616                ServiceInfo si = PackageParser.generateServiceInfo(s, flags,
4617                        ps.readUserState(userId), userId);
4618                if (si != null) {
4619                    rebaseEnabledOverlays(si.applicationInfo, userId);
4620                }
4621                return si;
4622            }
4623        }
4624        return null;
4625    }
4626
4627    @Override
4628    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4629        if (!sUserManager.exists(userId)) return null;
4630        final int callingUid = Binder.getCallingUid();
4631        flags = updateFlagsForComponent(flags, userId, component);
4632        enforceCrossUserPermission(callingUid, userId,
4633                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4634        synchronized (mPackages) {
4635            PackageParser.Provider p = mProviders.mProviders.get(component);
4636            if (DEBUG_PACKAGE_INFO) Log.v(
4637                TAG, "getProviderInfo " + component + ": " + p);
4638            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4639                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4640                if (ps == null) return null;
4641                final boolean visibleToInstantApp =
4642                        (p.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4643                if (filterAppAccessLPr(ps, callingUid, component, visibleToInstantApp, userId)) {
4644                    return null;
4645                }
4646                ProviderInfo pi = PackageParser.generateProviderInfo(p, flags,
4647                        ps.readUserState(userId), userId);
4648                if (pi != null) {
4649                    rebaseEnabledOverlays(pi.applicationInfo, userId);
4650                }
4651                return pi;
4652            }
4653        }
4654        return null;
4655    }
4656
4657    @Override
4658    public String[] getSystemSharedLibraryNames() {
4659        // allow instant applications
4660        synchronized (mPackages) {
4661            Set<String> libs = null;
4662            final int libCount = mSharedLibraries.size();
4663            for (int i = 0; i < libCount; i++) {
4664                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4665                if (versionedLib == null) {
4666                    continue;
4667                }
4668                final int versionCount = versionedLib.size();
4669                for (int j = 0; j < versionCount; j++) {
4670                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4671                    if (!libEntry.info.isStatic()) {
4672                        if (libs == null) {
4673                            libs = new ArraySet<>();
4674                        }
4675                        libs.add(libEntry.info.getName());
4676                        break;
4677                    }
4678                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4679                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4680                            UserHandle.getUserId(Binder.getCallingUid()),
4681                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4682                        if (libs == null) {
4683                            libs = new ArraySet<>();
4684                        }
4685                        libs.add(libEntry.info.getName());
4686                        break;
4687                    }
4688                }
4689            }
4690
4691            if (libs != null) {
4692                String[] libsArray = new String[libs.size()];
4693                libs.toArray(libsArray);
4694                return libsArray;
4695            }
4696
4697            return null;
4698        }
4699    }
4700
4701    @Override
4702    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4703        // allow instant applications
4704        synchronized (mPackages) {
4705            return mServicesSystemSharedLibraryPackageName;
4706        }
4707    }
4708
4709    @Override
4710    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4711        // allow instant applications
4712        synchronized (mPackages) {
4713            return mSharedSystemSharedLibraryPackageName;
4714        }
4715    }
4716
4717    private void updateSequenceNumberLP(String packageName, int[] userList) {
4718        for (int i = userList.length - 1; i >= 0; --i) {
4719            final int userId = userList[i];
4720            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4721            if (changedPackages == null) {
4722                changedPackages = new SparseArray<>();
4723                mChangedPackages.put(userId, changedPackages);
4724            }
4725            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4726            if (sequenceNumbers == null) {
4727                sequenceNumbers = new HashMap<>();
4728                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4729            }
4730            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4731            if (sequenceNumber != null) {
4732                changedPackages.remove(sequenceNumber);
4733            }
4734            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4735            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4736        }
4737        mChangedPackagesSequenceNumber++;
4738    }
4739
4740    @Override
4741    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4742        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4743            return null;
4744        }
4745        synchronized (mPackages) {
4746            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4747                return null;
4748            }
4749            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4750            if (changedPackages == null) {
4751                return null;
4752            }
4753            final List<String> packageNames =
4754                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4755            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4756                final String packageName = changedPackages.get(i);
4757                if (packageName != null) {
4758                    packageNames.add(packageName);
4759                }
4760            }
4761            return packageNames.isEmpty()
4762                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4763        }
4764    }
4765
4766    @Override
4767    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4768        // allow instant applications
4769        ArrayList<FeatureInfo> res;
4770        synchronized (mAvailableFeatures) {
4771            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4772            res.addAll(mAvailableFeatures.values());
4773        }
4774        final FeatureInfo fi = new FeatureInfo();
4775        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4776                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4777        res.add(fi);
4778
4779        return new ParceledListSlice<>(res);
4780    }
4781
4782    @Override
4783    public boolean hasSystemFeature(String name, int version) {
4784        // allow instant applications
4785        synchronized (mAvailableFeatures) {
4786            final FeatureInfo feat = mAvailableFeatures.get(name);
4787            if (feat == null) {
4788                return false;
4789            } else {
4790                return feat.version >= version;
4791            }
4792        }
4793    }
4794
4795    @Override
4796    public int checkPermission(String permName, String pkgName, int userId) {
4797        if (!sUserManager.exists(userId)) {
4798            return PackageManager.PERMISSION_DENIED;
4799        }
4800        final int callingUid = Binder.getCallingUid();
4801
4802        synchronized (mPackages) {
4803            final PackageParser.Package p = mPackages.get(pkgName);
4804            if (p != null && p.mExtras != null) {
4805                final PackageSetting ps = (PackageSetting) p.mExtras;
4806                if (filterAppAccessLPr(ps, callingUid, userId)) {
4807                    return PackageManager.PERMISSION_DENIED;
4808                }
4809                final PermissionsState permissionsState = ps.getPermissionsState();
4810                if (permissionsState.hasPermission(permName, userId)) {
4811                    return PackageManager.PERMISSION_GRANTED;
4812                }
4813                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4814                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4815                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4816                    return PackageManager.PERMISSION_GRANTED;
4817                }
4818            }
4819        }
4820
4821        return PackageManager.PERMISSION_DENIED;
4822    }
4823
4824    @Override
4825    public int checkUidPermission(String permName, int uid) {
4826        final int callingUid = Binder.getCallingUid();
4827        final int callingUserId = UserHandle.getUserId(callingUid);
4828        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
4829        final int userId = UserHandle.getUserId(uid);
4830        if (!sUserManager.exists(userId)) {
4831            return PackageManager.PERMISSION_DENIED;
4832        }
4833
4834        synchronized (mPackages) {
4835            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4836            if (obj != null) {
4837                if (obj instanceof SharedUserSetting) {
4838                    if (isCallerInstantApp) {
4839                        return PackageManager.PERMISSION_DENIED;
4840                    }
4841                } else if (obj instanceof PackageSetting) {
4842                    final PackageSetting ps = (PackageSetting) obj;
4843                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
4844                        return PackageManager.PERMISSION_DENIED;
4845                    }
4846                }
4847                final SettingBase settingBase = (SettingBase) obj;
4848                final PermissionsState permissionsState = settingBase.getPermissionsState();
4849                if (permissionsState.hasPermission(permName, userId)) {
4850                    return PackageManager.PERMISSION_GRANTED;
4851                }
4852                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4853                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4854                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4855                    return PackageManager.PERMISSION_GRANTED;
4856                }
4857            } else {
4858                ArraySet<String> perms = mSystemPermissions.get(uid);
4859                if (perms != null) {
4860                    if (perms.contains(permName)) {
4861                        return PackageManager.PERMISSION_GRANTED;
4862                    }
4863                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4864                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4865                        return PackageManager.PERMISSION_GRANTED;
4866                    }
4867                }
4868            }
4869        }
4870
4871        return PackageManager.PERMISSION_DENIED;
4872    }
4873
4874    @Override
4875    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4876        if (UserHandle.getCallingUserId() != userId) {
4877            mContext.enforceCallingPermission(
4878                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4879                    "isPermissionRevokedByPolicy for user " + userId);
4880        }
4881
4882        if (checkPermission(permission, packageName, userId)
4883                == PackageManager.PERMISSION_GRANTED) {
4884            return false;
4885        }
4886
4887        final int callingUid = Binder.getCallingUid();
4888        if (getInstantAppPackageName(callingUid) != null) {
4889            if (!isCallerSameApp(packageName, callingUid)) {
4890                return false;
4891            }
4892        } else {
4893            if (isInstantApp(packageName, userId)) {
4894                return false;
4895            }
4896        }
4897
4898        final long identity = Binder.clearCallingIdentity();
4899        try {
4900            final int flags = getPermissionFlags(permission, packageName, userId);
4901            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4902        } finally {
4903            Binder.restoreCallingIdentity(identity);
4904        }
4905    }
4906
4907    @Override
4908    public String getPermissionControllerPackageName() {
4909        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4910            throw new SecurityException("Instant applications don't have access to this method");
4911        }
4912        synchronized (mPackages) {
4913            return mRequiredInstallerPackage;
4914        }
4915    }
4916
4917    /**
4918     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4919     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4920     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4921     * @param message the message to log on security exception
4922     */
4923    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4924            boolean checkShell, String message) {
4925        if (userId < 0) {
4926            throw new IllegalArgumentException("Invalid userId " + userId);
4927        }
4928        if (checkShell) {
4929            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4930        }
4931        if (userId == UserHandle.getUserId(callingUid)) return;
4932        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4933            if (requireFullPermission) {
4934                mContext.enforceCallingOrSelfPermission(
4935                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4936            } else {
4937                try {
4938                    mContext.enforceCallingOrSelfPermission(
4939                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4940                } catch (SecurityException se) {
4941                    mContext.enforceCallingOrSelfPermission(
4942                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4943                }
4944            }
4945        }
4946    }
4947
4948    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4949        if (callingUid == Process.SHELL_UID) {
4950            if (userHandle >= 0
4951                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4952                throw new SecurityException("Shell does not have permission to access user "
4953                        + userHandle);
4954            } else if (userHandle < 0) {
4955                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4956                        + Debug.getCallers(3));
4957            }
4958        }
4959    }
4960
4961    private BasePermission findPermissionTreeLP(String permName) {
4962        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4963            if (permName.startsWith(bp.name) &&
4964                    permName.length() > bp.name.length() &&
4965                    permName.charAt(bp.name.length()) == '.') {
4966                return bp;
4967            }
4968        }
4969        return null;
4970    }
4971
4972    private BasePermission checkPermissionTreeLP(String permName) {
4973        if (permName != null) {
4974            BasePermission bp = findPermissionTreeLP(permName);
4975            if (bp != null) {
4976                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4977                    return bp;
4978                }
4979                throw new SecurityException("Calling uid "
4980                        + Binder.getCallingUid()
4981                        + " is not allowed to add to permission tree "
4982                        + bp.name + " owned by uid " + bp.uid);
4983            }
4984        }
4985        throw new SecurityException("No permission tree found for " + permName);
4986    }
4987
4988    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4989        if (s1 == null) {
4990            return s2 == null;
4991        }
4992        if (s2 == null) {
4993            return false;
4994        }
4995        if (s1.getClass() != s2.getClass()) {
4996            return false;
4997        }
4998        return s1.equals(s2);
4999    }
5000
5001    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5002        if (pi1.icon != pi2.icon) return false;
5003        if (pi1.logo != pi2.logo) return false;
5004        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5005        if (!compareStrings(pi1.name, pi2.name)) return false;
5006        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5007        // We'll take care of setting this one.
5008        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5009        // These are not currently stored in settings.
5010        //if (!compareStrings(pi1.group, pi2.group)) return false;
5011        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5012        //if (pi1.labelRes != pi2.labelRes) return false;
5013        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5014        return true;
5015    }
5016
5017    int permissionInfoFootprint(PermissionInfo info) {
5018        int size = info.name.length();
5019        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5020        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5021        return size;
5022    }
5023
5024    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5025        int size = 0;
5026        for (BasePermission perm : mSettings.mPermissions.values()) {
5027            if (perm.uid == tree.uid) {
5028                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5029            }
5030        }
5031        return size;
5032    }
5033
5034    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5035        // We calculate the max size of permissions defined by this uid and throw
5036        // if that plus the size of 'info' would exceed our stated maximum.
5037        if (tree.uid != Process.SYSTEM_UID) {
5038            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5039            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5040                throw new SecurityException("Permission tree size cap exceeded");
5041            }
5042        }
5043    }
5044
5045    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5046        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5047            throw new SecurityException("Instant apps can't add permissions");
5048        }
5049        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5050            throw new SecurityException("Label must be specified in permission");
5051        }
5052        BasePermission tree = checkPermissionTreeLP(info.name);
5053        BasePermission bp = mSettings.mPermissions.get(info.name);
5054        boolean added = bp == null;
5055        boolean changed = true;
5056        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5057        if (added) {
5058            enforcePermissionCapLocked(info, tree);
5059            bp = new BasePermission(info.name, tree.sourcePackage,
5060                    BasePermission.TYPE_DYNAMIC);
5061        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5062            throw new SecurityException(
5063                    "Not allowed to modify non-dynamic permission "
5064                    + info.name);
5065        } else {
5066            if (bp.protectionLevel == fixedLevel
5067                    && bp.perm.owner.equals(tree.perm.owner)
5068                    && bp.uid == tree.uid
5069                    && comparePermissionInfos(bp.perm.info, info)) {
5070                changed = false;
5071            }
5072        }
5073        bp.protectionLevel = fixedLevel;
5074        info = new PermissionInfo(info);
5075        info.protectionLevel = fixedLevel;
5076        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5077        bp.perm.info.packageName = tree.perm.info.packageName;
5078        bp.uid = tree.uid;
5079        if (added) {
5080            mSettings.mPermissions.put(info.name, bp);
5081        }
5082        if (changed) {
5083            if (!async) {
5084                mSettings.writeLPr();
5085            } else {
5086                scheduleWriteSettingsLocked();
5087            }
5088        }
5089        return added;
5090    }
5091
5092    @Override
5093    public boolean addPermission(PermissionInfo info) {
5094        synchronized (mPackages) {
5095            return addPermissionLocked(info, false);
5096        }
5097    }
5098
5099    @Override
5100    public boolean addPermissionAsync(PermissionInfo info) {
5101        synchronized (mPackages) {
5102            return addPermissionLocked(info, true);
5103        }
5104    }
5105
5106    @Override
5107    public void removePermission(String name) {
5108        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5109            throw new SecurityException("Instant applications don't have access to this method");
5110        }
5111        synchronized (mPackages) {
5112            checkPermissionTreeLP(name);
5113            BasePermission bp = mSettings.mPermissions.get(name);
5114            if (bp != null) {
5115                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5116                    throw new SecurityException(
5117                            "Not allowed to modify non-dynamic permission "
5118                            + name);
5119                }
5120                mSettings.mPermissions.remove(name);
5121                mSettings.writeLPr();
5122            }
5123        }
5124    }
5125
5126    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5127            PackageParser.Package pkg, BasePermission bp) {
5128        int index = pkg.requestedPermissions.indexOf(bp.name);
5129        if (index == -1) {
5130            throw new SecurityException("Package " + pkg.packageName
5131                    + " has not requested permission " + bp.name);
5132        }
5133        if (!bp.isRuntime() && !bp.isDevelopment()) {
5134            throw new SecurityException("Permission " + bp.name
5135                    + " is not a changeable permission type");
5136        }
5137    }
5138
5139    @Override
5140    public void grantRuntimePermission(String packageName, String name, final int userId) {
5141        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5142    }
5143
5144    private void grantRuntimePermission(String packageName, String name, final int userId,
5145            boolean overridePolicy) {
5146        if (!sUserManager.exists(userId)) {
5147            Log.e(TAG, "No such user:" + userId);
5148            return;
5149        }
5150
5151        mContext.enforceCallingOrSelfPermission(
5152                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5153                "grantRuntimePermission");
5154
5155        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5156                true /* requireFullPermission */, true /* checkShell */,
5157                "grantRuntimePermission");
5158
5159        final int uid;
5160        final SettingBase sb;
5161
5162        synchronized (mPackages) {
5163            final PackageParser.Package pkg = mPackages.get(packageName);
5164            if (pkg == null) {
5165                throw new IllegalArgumentException("Unknown package: " + packageName);
5166            }
5167
5168            final BasePermission bp = mSettings.mPermissions.get(name);
5169            if (bp == null) {
5170                throw new IllegalArgumentException("Unknown permission: " + name);
5171            }
5172
5173            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5174
5175            // If a permission review is required for legacy apps we represent
5176            // their permissions as always granted runtime ones since we need
5177            // to keep the review required permission flag per user while an
5178            // install permission's state is shared across all users.
5179            if (mPermissionReviewRequired
5180                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5181                    && bp.isRuntime()) {
5182                return;
5183            }
5184
5185            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5186            sb = (SettingBase) pkg.mExtras;
5187            if (sb == null) {
5188                throw new IllegalArgumentException("Unknown package: " + packageName);
5189            }
5190
5191            final PermissionsState permissionsState = sb.getPermissionsState();
5192
5193            final int flags = permissionsState.getPermissionFlags(name, userId);
5194            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5195                throw new SecurityException("Cannot grant system fixed permission "
5196                        + name + " for package " + packageName);
5197            }
5198            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5199                throw new SecurityException("Cannot grant policy fixed permission "
5200                        + name + " for package " + packageName);
5201            }
5202
5203            if (bp.isDevelopment()) {
5204                // Development permissions must be handled specially, since they are not
5205                // normal runtime permissions.  For now they apply to all users.
5206                if (permissionsState.grantInstallPermission(bp) !=
5207                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5208                    scheduleWriteSettingsLocked();
5209                }
5210                return;
5211            }
5212
5213            final PackageSetting ps = mSettings.mPackages.get(packageName);
5214            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5215                throw new SecurityException("Cannot grant non-ephemeral permission"
5216                        + name + " for package " + packageName);
5217            }
5218
5219            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5220                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5221                return;
5222            }
5223
5224            final int result = permissionsState.grantRuntimePermission(bp, userId);
5225            switch (result) {
5226                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5227                    return;
5228                }
5229
5230                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5231                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5232                    mHandler.post(new Runnable() {
5233                        @Override
5234                        public void run() {
5235                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5236                        }
5237                    });
5238                }
5239                break;
5240            }
5241
5242            if (bp.isRuntime()) {
5243                logPermissionGranted(mContext, name, packageName);
5244            }
5245
5246            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5247
5248            // Not critical if that is lost - app has to request again.
5249            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5250        }
5251
5252        // Only need to do this if user is initialized. Otherwise it's a new user
5253        // and there are no processes running as the user yet and there's no need
5254        // to make an expensive call to remount processes for the changed permissions.
5255        if (READ_EXTERNAL_STORAGE.equals(name)
5256                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5257            final long token = Binder.clearCallingIdentity();
5258            try {
5259                if (sUserManager.isInitialized(userId)) {
5260                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5261                            StorageManagerInternal.class);
5262                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5263                }
5264            } finally {
5265                Binder.restoreCallingIdentity(token);
5266            }
5267        }
5268    }
5269
5270    @Override
5271    public void revokeRuntimePermission(String packageName, String name, int userId) {
5272        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5273    }
5274
5275    private void revokeRuntimePermission(String packageName, String name, int userId,
5276            boolean overridePolicy) {
5277        if (!sUserManager.exists(userId)) {
5278            Log.e(TAG, "No such user:" + userId);
5279            return;
5280        }
5281
5282        mContext.enforceCallingOrSelfPermission(
5283                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5284                "revokeRuntimePermission");
5285
5286        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5287                true /* requireFullPermission */, true /* checkShell */,
5288                "revokeRuntimePermission");
5289
5290        final int appId;
5291
5292        synchronized (mPackages) {
5293            final PackageParser.Package pkg = mPackages.get(packageName);
5294            if (pkg == null) {
5295                throw new IllegalArgumentException("Unknown package: " + packageName);
5296            }
5297
5298            final BasePermission bp = mSettings.mPermissions.get(name);
5299            if (bp == null) {
5300                throw new IllegalArgumentException("Unknown permission: " + name);
5301            }
5302
5303            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5304
5305            // If a permission review is required for legacy apps we represent
5306            // their permissions as always granted runtime ones since we need
5307            // to keep the review required permission flag per user while an
5308            // install permission's state is shared across all users.
5309            if (mPermissionReviewRequired
5310                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5311                    && bp.isRuntime()) {
5312                return;
5313            }
5314
5315            SettingBase sb = (SettingBase) pkg.mExtras;
5316            if (sb == null) {
5317                throw new IllegalArgumentException("Unknown package: " + packageName);
5318            }
5319
5320            final PermissionsState permissionsState = sb.getPermissionsState();
5321
5322            final int flags = permissionsState.getPermissionFlags(name, userId);
5323            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5324                throw new SecurityException("Cannot revoke system fixed permission "
5325                        + name + " for package " + packageName);
5326            }
5327            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5328                throw new SecurityException("Cannot revoke policy fixed permission "
5329                        + name + " for package " + packageName);
5330            }
5331
5332            if (bp.isDevelopment()) {
5333                // Development permissions must be handled specially, since they are not
5334                // normal runtime permissions.  For now they apply to all users.
5335                if (permissionsState.revokeInstallPermission(bp) !=
5336                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5337                    scheduleWriteSettingsLocked();
5338                }
5339                return;
5340            }
5341
5342            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5343                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5344                return;
5345            }
5346
5347            if (bp.isRuntime()) {
5348                logPermissionRevoked(mContext, name, packageName);
5349            }
5350
5351            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5352
5353            // Critical, after this call app should never have the permission.
5354            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5355
5356            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5357        }
5358
5359        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5360    }
5361
5362    /**
5363     * Get the first event id for the permission.
5364     *
5365     * <p>There are four events for each permission: <ul>
5366     *     <li>Request permission: first id + 0</li>
5367     *     <li>Grant permission: first id + 1</li>
5368     *     <li>Request for permission denied: first id + 2</li>
5369     *     <li>Revoke permission: first id + 3</li>
5370     * </ul></p>
5371     *
5372     * @param name name of the permission
5373     *
5374     * @return The first event id for the permission
5375     */
5376    private static int getBaseEventId(@NonNull String name) {
5377        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5378
5379        if (eventIdIndex == -1) {
5380            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5381                    || "user".equals(Build.TYPE)) {
5382                Log.i(TAG, "Unknown permission " + name);
5383
5384                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5385            } else {
5386                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5387                //
5388                // Also update
5389                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5390                // - metrics_constants.proto
5391                throw new IllegalStateException("Unknown permission " + name);
5392            }
5393        }
5394
5395        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5396    }
5397
5398    /**
5399     * Log that a permission was revoked.
5400     *
5401     * @param context Context of the caller
5402     * @param name name of the permission
5403     * @param packageName package permission if for
5404     */
5405    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5406            @NonNull String packageName) {
5407        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5408    }
5409
5410    /**
5411     * Log that a permission request was granted.
5412     *
5413     * @param context Context of the caller
5414     * @param name name of the permission
5415     * @param packageName package permission if for
5416     */
5417    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5418            @NonNull String packageName) {
5419        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5420    }
5421
5422    @Override
5423    public void resetRuntimePermissions() {
5424        mContext.enforceCallingOrSelfPermission(
5425                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5426                "revokeRuntimePermission");
5427
5428        int callingUid = Binder.getCallingUid();
5429        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5430            mContext.enforceCallingOrSelfPermission(
5431                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5432                    "resetRuntimePermissions");
5433        }
5434
5435        synchronized (mPackages) {
5436            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5437            for (int userId : UserManagerService.getInstance().getUserIds()) {
5438                final int packageCount = mPackages.size();
5439                for (int i = 0; i < packageCount; i++) {
5440                    PackageParser.Package pkg = mPackages.valueAt(i);
5441                    if (!(pkg.mExtras instanceof PackageSetting)) {
5442                        continue;
5443                    }
5444                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5445                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5446                }
5447            }
5448        }
5449    }
5450
5451    @Override
5452    public int getPermissionFlags(String name, String packageName, int userId) {
5453        if (!sUserManager.exists(userId)) {
5454            return 0;
5455        }
5456
5457        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5458
5459        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5460                true /* requireFullPermission */, false /* checkShell */,
5461                "getPermissionFlags");
5462
5463        synchronized (mPackages) {
5464            final PackageParser.Package pkg = mPackages.get(packageName);
5465            if (pkg == null) {
5466                return 0;
5467            }
5468
5469            final BasePermission bp = mSettings.mPermissions.get(name);
5470            if (bp == null) {
5471                return 0;
5472            }
5473
5474            SettingBase sb = (SettingBase) pkg.mExtras;
5475            if (sb == null) {
5476                return 0;
5477            }
5478
5479            PermissionsState permissionsState = sb.getPermissionsState();
5480            return permissionsState.getPermissionFlags(name, userId);
5481        }
5482    }
5483
5484    @Override
5485    public void updatePermissionFlags(String name, String packageName, int flagMask,
5486            int flagValues, int userId) {
5487        if (!sUserManager.exists(userId)) {
5488            return;
5489        }
5490
5491        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5492
5493        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5494                true /* requireFullPermission */, true /* checkShell */,
5495                "updatePermissionFlags");
5496
5497        // Only the system can change these flags and nothing else.
5498        if (getCallingUid() != Process.SYSTEM_UID) {
5499            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5500            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5501            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5502            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5503            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5504        }
5505
5506        synchronized (mPackages) {
5507            final PackageParser.Package pkg = mPackages.get(packageName);
5508            if (pkg == null) {
5509                throw new IllegalArgumentException("Unknown package: " + packageName);
5510            }
5511
5512            final BasePermission bp = mSettings.mPermissions.get(name);
5513            if (bp == null) {
5514                throw new IllegalArgumentException("Unknown permission: " + name);
5515            }
5516
5517            SettingBase sb = (SettingBase) pkg.mExtras;
5518            if (sb == null) {
5519                throw new IllegalArgumentException("Unknown package: " + packageName);
5520            }
5521
5522            PermissionsState permissionsState = sb.getPermissionsState();
5523
5524            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5525
5526            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5527                // Install and runtime permissions are stored in different places,
5528                // so figure out what permission changed and persist the change.
5529                if (permissionsState.getInstallPermissionState(name) != null) {
5530                    scheduleWriteSettingsLocked();
5531                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5532                        || hadState) {
5533                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5534                }
5535            }
5536        }
5537    }
5538
5539    /**
5540     * Update the permission flags for all packages and runtime permissions of a user in order
5541     * to allow device or profile owner to remove POLICY_FIXED.
5542     */
5543    @Override
5544    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5545        if (!sUserManager.exists(userId)) {
5546            return;
5547        }
5548
5549        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5550
5551        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5552                true /* requireFullPermission */, true /* checkShell */,
5553                "updatePermissionFlagsForAllApps");
5554
5555        // Only the system can change system fixed flags.
5556        if (getCallingUid() != Process.SYSTEM_UID) {
5557            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5558            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5559        }
5560
5561        synchronized (mPackages) {
5562            boolean changed = false;
5563            final int packageCount = mPackages.size();
5564            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5565                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5566                SettingBase sb = (SettingBase) pkg.mExtras;
5567                if (sb == null) {
5568                    continue;
5569                }
5570                PermissionsState permissionsState = sb.getPermissionsState();
5571                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5572                        userId, flagMask, flagValues);
5573            }
5574            if (changed) {
5575                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5576            }
5577        }
5578    }
5579
5580    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5581        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5582                != PackageManager.PERMISSION_GRANTED
5583            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5584                != PackageManager.PERMISSION_GRANTED) {
5585            throw new SecurityException(message + " requires "
5586                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5587                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5588        }
5589    }
5590
5591    @Override
5592    public boolean shouldShowRequestPermissionRationale(String permissionName,
5593            String packageName, int userId) {
5594        if (UserHandle.getCallingUserId() != userId) {
5595            mContext.enforceCallingPermission(
5596                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5597                    "canShowRequestPermissionRationale for user " + userId);
5598        }
5599
5600        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5601        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5602            return false;
5603        }
5604
5605        if (checkPermission(permissionName, packageName, userId)
5606                == PackageManager.PERMISSION_GRANTED) {
5607            return false;
5608        }
5609
5610        final int flags;
5611
5612        final long identity = Binder.clearCallingIdentity();
5613        try {
5614            flags = getPermissionFlags(permissionName,
5615                    packageName, userId);
5616        } finally {
5617            Binder.restoreCallingIdentity(identity);
5618        }
5619
5620        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5621                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5622                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5623
5624        if ((flags & fixedFlags) != 0) {
5625            return false;
5626        }
5627
5628        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5629    }
5630
5631    @Override
5632    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5633        mContext.enforceCallingOrSelfPermission(
5634                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5635                "addOnPermissionsChangeListener");
5636
5637        synchronized (mPackages) {
5638            mOnPermissionChangeListeners.addListenerLocked(listener);
5639        }
5640    }
5641
5642    @Override
5643    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5644        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5645            throw new SecurityException("Instant applications don't have access to this method");
5646        }
5647        synchronized (mPackages) {
5648            mOnPermissionChangeListeners.removeListenerLocked(listener);
5649        }
5650    }
5651
5652    @Override
5653    public boolean isProtectedBroadcast(String actionName) {
5654        // allow instant applications
5655        synchronized (mPackages) {
5656            if (mProtectedBroadcasts.contains(actionName)) {
5657                return true;
5658            } else if (actionName != null) {
5659                // TODO: remove these terrible hacks
5660                if (actionName.startsWith("android.net.netmon.lingerExpired")
5661                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5662                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5663                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5664                    return true;
5665                }
5666            }
5667        }
5668        return false;
5669    }
5670
5671    @Override
5672    public int checkSignatures(String pkg1, String pkg2) {
5673        synchronized (mPackages) {
5674            final PackageParser.Package p1 = mPackages.get(pkg1);
5675            final PackageParser.Package p2 = mPackages.get(pkg2);
5676            if (p1 == null || p1.mExtras == null
5677                    || p2 == null || p2.mExtras == null) {
5678                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5679            }
5680            final int callingUid = Binder.getCallingUid();
5681            final int callingUserId = UserHandle.getUserId(callingUid);
5682            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5683            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5684            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5685                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5686                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5687            }
5688            return compareSignatures(p1.mSignatures, p2.mSignatures);
5689        }
5690    }
5691
5692    @Override
5693    public int checkUidSignatures(int uid1, int uid2) {
5694        final int callingUid = Binder.getCallingUid();
5695        final int callingUserId = UserHandle.getUserId(callingUid);
5696        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5697        // Map to base uids.
5698        uid1 = UserHandle.getAppId(uid1);
5699        uid2 = UserHandle.getAppId(uid2);
5700        // reader
5701        synchronized (mPackages) {
5702            Signature[] s1;
5703            Signature[] s2;
5704            Object obj = mSettings.getUserIdLPr(uid1);
5705            if (obj != null) {
5706                if (obj instanceof SharedUserSetting) {
5707                    if (isCallerInstantApp) {
5708                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5709                    }
5710                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5711                } else if (obj instanceof PackageSetting) {
5712                    final PackageSetting ps = (PackageSetting) obj;
5713                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5714                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5715                    }
5716                    s1 = ps.signatures.mSignatures;
5717                } else {
5718                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5719                }
5720            } else {
5721                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5722            }
5723            obj = mSettings.getUserIdLPr(uid2);
5724            if (obj != null) {
5725                if (obj instanceof SharedUserSetting) {
5726                    if (isCallerInstantApp) {
5727                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5728                    }
5729                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5730                } else if (obj instanceof PackageSetting) {
5731                    final PackageSetting ps = (PackageSetting) obj;
5732                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5733                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5734                    }
5735                    s2 = ps.signatures.mSignatures;
5736                } else {
5737                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5738                }
5739            } else {
5740                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5741            }
5742            return compareSignatures(s1, s2);
5743        }
5744    }
5745
5746    /**
5747     * This method should typically only be used when granting or revoking
5748     * permissions, since the app may immediately restart after this call.
5749     * <p>
5750     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5751     * guard your work against the app being relaunched.
5752     */
5753    private void killUid(int appId, int userId, String reason) {
5754        final long identity = Binder.clearCallingIdentity();
5755        try {
5756            IActivityManager am = ActivityManager.getService();
5757            if (am != null) {
5758                try {
5759                    am.killUid(appId, userId, reason);
5760                } catch (RemoteException e) {
5761                    /* ignore - same process */
5762                }
5763            }
5764        } finally {
5765            Binder.restoreCallingIdentity(identity);
5766        }
5767    }
5768
5769    /**
5770     * Compares two sets of signatures. Returns:
5771     * <br />
5772     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5773     * <br />
5774     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5775     * <br />
5776     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5777     * <br />
5778     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5779     * <br />
5780     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5781     */
5782    static int compareSignatures(Signature[] s1, Signature[] s2) {
5783        if (s1 == null) {
5784            return s2 == null
5785                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5786                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5787        }
5788
5789        if (s2 == null) {
5790            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5791        }
5792
5793        if (s1.length != s2.length) {
5794            return PackageManager.SIGNATURE_NO_MATCH;
5795        }
5796
5797        // Since both signature sets are of size 1, we can compare without HashSets.
5798        if (s1.length == 1) {
5799            return s1[0].equals(s2[0]) ?
5800                    PackageManager.SIGNATURE_MATCH :
5801                    PackageManager.SIGNATURE_NO_MATCH;
5802        }
5803
5804        ArraySet<Signature> set1 = new ArraySet<Signature>();
5805        for (Signature sig : s1) {
5806            set1.add(sig);
5807        }
5808        ArraySet<Signature> set2 = new ArraySet<Signature>();
5809        for (Signature sig : s2) {
5810            set2.add(sig);
5811        }
5812        // Make sure s2 contains all signatures in s1.
5813        if (set1.equals(set2)) {
5814            return PackageManager.SIGNATURE_MATCH;
5815        }
5816        return PackageManager.SIGNATURE_NO_MATCH;
5817    }
5818
5819    /**
5820     * If the database version for this type of package (internal storage or
5821     * external storage) is less than the version where package signatures
5822     * were updated, return true.
5823     */
5824    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5825        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5826        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5827    }
5828
5829    /**
5830     * Used for backward compatibility to make sure any packages with
5831     * certificate chains get upgraded to the new style. {@code existingSigs}
5832     * will be in the old format (since they were stored on disk from before the
5833     * system upgrade) and {@code scannedSigs} will be in the newer format.
5834     */
5835    private int compareSignaturesCompat(PackageSignatures existingSigs,
5836            PackageParser.Package scannedPkg) {
5837        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5838            return PackageManager.SIGNATURE_NO_MATCH;
5839        }
5840
5841        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5842        for (Signature sig : existingSigs.mSignatures) {
5843            existingSet.add(sig);
5844        }
5845        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5846        for (Signature sig : scannedPkg.mSignatures) {
5847            try {
5848                Signature[] chainSignatures = sig.getChainSignatures();
5849                for (Signature chainSig : chainSignatures) {
5850                    scannedCompatSet.add(chainSig);
5851                }
5852            } catch (CertificateEncodingException e) {
5853                scannedCompatSet.add(sig);
5854            }
5855        }
5856        /*
5857         * Make sure the expanded scanned set contains all signatures in the
5858         * existing one.
5859         */
5860        if (scannedCompatSet.equals(existingSet)) {
5861            // Migrate the old signatures to the new scheme.
5862            existingSigs.assignSignatures(scannedPkg.mSignatures);
5863            // The new KeySets will be re-added later in the scanning process.
5864            synchronized (mPackages) {
5865                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5866            }
5867            return PackageManager.SIGNATURE_MATCH;
5868        }
5869        return PackageManager.SIGNATURE_NO_MATCH;
5870    }
5871
5872    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5873        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5874        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5875    }
5876
5877    private int compareSignaturesRecover(PackageSignatures existingSigs,
5878            PackageParser.Package scannedPkg) {
5879        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5880            return PackageManager.SIGNATURE_NO_MATCH;
5881        }
5882
5883        String msg = null;
5884        try {
5885            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5886                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5887                        + scannedPkg.packageName);
5888                return PackageManager.SIGNATURE_MATCH;
5889            }
5890        } catch (CertificateException e) {
5891            msg = e.getMessage();
5892        }
5893
5894        logCriticalInfo(Log.INFO,
5895                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5896        return PackageManager.SIGNATURE_NO_MATCH;
5897    }
5898
5899    @Override
5900    public List<String> getAllPackages() {
5901        final int callingUid = Binder.getCallingUid();
5902        final int callingUserId = UserHandle.getUserId(callingUid);
5903        synchronized (mPackages) {
5904            if (canAccessInstantApps(callingUid)) {
5905                return new ArrayList<String>(mPackages.keySet());
5906            }
5907            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5908            final List<String> result = new ArrayList<>();
5909            if (instantAppPkgName != null) {
5910                // caller is an instant application; filter unexposed applications
5911                for (PackageParser.Package pkg : mPackages.values()) {
5912                    if (!pkg.visibleToInstantApps) {
5913                        continue;
5914                    }
5915                    result.add(pkg.packageName);
5916                }
5917            } else {
5918                // caller is a normal application; filter instant applications
5919                for (PackageParser.Package pkg : mPackages.values()) {
5920                    final PackageSetting ps =
5921                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5922                    if (ps != null
5923                            && ps.getInstantApp(callingUserId)
5924                            && !mInstantAppRegistry.isInstantAccessGranted(
5925                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5926                        continue;
5927                    }
5928                    result.add(pkg.packageName);
5929                }
5930            }
5931            return result;
5932        }
5933    }
5934
5935    @Override
5936    public String[] getPackagesForUid(int uid) {
5937        final int callingUid = Binder.getCallingUid();
5938        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5939        final int userId = UserHandle.getUserId(uid);
5940        uid = UserHandle.getAppId(uid);
5941        // reader
5942        synchronized (mPackages) {
5943            Object obj = mSettings.getUserIdLPr(uid);
5944            if (obj instanceof SharedUserSetting) {
5945                if (isCallerInstantApp) {
5946                    return null;
5947                }
5948                final SharedUserSetting sus = (SharedUserSetting) obj;
5949                final int N = sus.packages.size();
5950                String[] res = new String[N];
5951                final Iterator<PackageSetting> it = sus.packages.iterator();
5952                int i = 0;
5953                while (it.hasNext()) {
5954                    PackageSetting ps = it.next();
5955                    if (ps.getInstalled(userId)) {
5956                        res[i++] = ps.name;
5957                    } else {
5958                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5959                    }
5960                }
5961                return res;
5962            } else if (obj instanceof PackageSetting) {
5963                final PackageSetting ps = (PackageSetting) obj;
5964                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5965                    return new String[]{ps.name};
5966                }
5967            }
5968        }
5969        return null;
5970    }
5971
5972    @Override
5973    public String getNameForUid(int uid) {
5974        final int callingUid = Binder.getCallingUid();
5975        if (getInstantAppPackageName(callingUid) != null) {
5976            return null;
5977        }
5978        synchronized (mPackages) {
5979            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5980            if (obj instanceof SharedUserSetting) {
5981                final SharedUserSetting sus = (SharedUserSetting) obj;
5982                return sus.name + ":" + sus.userId;
5983            } else if (obj instanceof PackageSetting) {
5984                final PackageSetting ps = (PackageSetting) obj;
5985                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5986                    return null;
5987                }
5988                return ps.name;
5989            }
5990        }
5991        return null;
5992    }
5993
5994    @Override
5995    public int getUidForSharedUser(String sharedUserName) {
5996        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5997            return -1;
5998        }
5999        if (sharedUserName == null) {
6000            return -1;
6001        }
6002        // reader
6003        synchronized (mPackages) {
6004            SharedUserSetting suid;
6005            try {
6006                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6007                if (suid != null) {
6008                    return suid.userId;
6009                }
6010            } catch (PackageManagerException ignore) {
6011                // can't happen, but, still need to catch it
6012            }
6013            return -1;
6014        }
6015    }
6016
6017    @Override
6018    public int getFlagsForUid(int uid) {
6019        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6020            return 0;
6021        }
6022        synchronized (mPackages) {
6023            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6024            if (obj instanceof SharedUserSetting) {
6025                final SharedUserSetting sus = (SharedUserSetting) obj;
6026                return sus.pkgFlags;
6027            } else if (obj instanceof PackageSetting) {
6028                final PackageSetting ps = (PackageSetting) obj;
6029                return ps.pkgFlags;
6030            }
6031        }
6032        return 0;
6033    }
6034
6035    @Override
6036    public int getPrivateFlagsForUid(int uid) {
6037        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6038            return 0;
6039        }
6040        synchronized (mPackages) {
6041            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6042            if (obj instanceof SharedUserSetting) {
6043                final SharedUserSetting sus = (SharedUserSetting) obj;
6044                return sus.pkgPrivateFlags;
6045            } else if (obj instanceof PackageSetting) {
6046                final PackageSetting ps = (PackageSetting) obj;
6047                return ps.pkgPrivateFlags;
6048            }
6049        }
6050        return 0;
6051    }
6052
6053    @Override
6054    public boolean isUidPrivileged(int uid) {
6055        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6056            return false;
6057        }
6058        uid = UserHandle.getAppId(uid);
6059        // reader
6060        synchronized (mPackages) {
6061            Object obj = mSettings.getUserIdLPr(uid);
6062            if (obj instanceof SharedUserSetting) {
6063                final SharedUserSetting sus = (SharedUserSetting) obj;
6064                final Iterator<PackageSetting> it = sus.packages.iterator();
6065                while (it.hasNext()) {
6066                    if (it.next().isPrivileged()) {
6067                        return true;
6068                    }
6069                }
6070            } else if (obj instanceof PackageSetting) {
6071                final PackageSetting ps = (PackageSetting) obj;
6072                return ps.isPrivileged();
6073            }
6074        }
6075        return false;
6076    }
6077
6078    @Override
6079    public String[] getAppOpPermissionPackages(String permissionName) {
6080        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6081            return null;
6082        }
6083        synchronized (mPackages) {
6084            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6085            if (pkgs == null) {
6086                return null;
6087            }
6088            return pkgs.toArray(new String[pkgs.size()]);
6089        }
6090    }
6091
6092    @Override
6093    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6094            int flags, int userId) {
6095        return resolveIntentInternal(
6096                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6097    }
6098
6099    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6100            int flags, int userId, boolean resolveForStart) {
6101        try {
6102            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6103
6104            if (!sUserManager.exists(userId)) return null;
6105            final int callingUid = Binder.getCallingUid();
6106            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6107            enforceCrossUserPermission(callingUid, userId,
6108                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6109
6110            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6111            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6112                    flags, userId, resolveForStart);
6113            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6114
6115            final ResolveInfo bestChoice =
6116                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6117            return bestChoice;
6118        } finally {
6119            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6120        }
6121    }
6122
6123    @Override
6124    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6125        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6126            throw new SecurityException(
6127                    "findPersistentPreferredActivity can only be run by the system");
6128        }
6129        if (!sUserManager.exists(userId)) {
6130            return null;
6131        }
6132        final int callingUid = Binder.getCallingUid();
6133        intent = updateIntentForResolve(intent);
6134        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6135        final int flags = updateFlagsForResolve(
6136                0, userId, intent, callingUid, false /*includeInstantApps*/);
6137        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6138                userId);
6139        synchronized (mPackages) {
6140            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6141                    userId);
6142        }
6143    }
6144
6145    @Override
6146    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6147            IntentFilter filter, int match, ComponentName activity) {
6148        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6149            return;
6150        }
6151        final int userId = UserHandle.getCallingUserId();
6152        if (DEBUG_PREFERRED) {
6153            Log.v(TAG, "setLastChosenActivity intent=" + intent
6154                + " resolvedType=" + resolvedType
6155                + " flags=" + flags
6156                + " filter=" + filter
6157                + " match=" + match
6158                + " activity=" + activity);
6159            filter.dump(new PrintStreamPrinter(System.out), "    ");
6160        }
6161        intent.setComponent(null);
6162        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6163                userId);
6164        // Find any earlier preferred or last chosen entries and nuke them
6165        findPreferredActivity(intent, resolvedType,
6166                flags, query, 0, false, true, false, userId);
6167        // Add the new activity as the last chosen for this filter
6168        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6169                "Setting last chosen");
6170    }
6171
6172    @Override
6173    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6174        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6175            return null;
6176        }
6177        final int userId = UserHandle.getCallingUserId();
6178        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6179        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6180                userId);
6181        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6182                false, false, false, userId);
6183    }
6184
6185    /**
6186     * Returns whether or not instant apps have been disabled remotely.
6187     */
6188    private boolean isEphemeralDisabled() {
6189        return mEphemeralAppsDisabled;
6190    }
6191
6192    private boolean isInstantAppAllowed(
6193            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6194            boolean skipPackageCheck) {
6195        if (mInstantAppResolverConnection == null) {
6196            return false;
6197        }
6198        if (mInstantAppInstallerActivity == null) {
6199            return false;
6200        }
6201        if (intent.getComponent() != null) {
6202            return false;
6203        }
6204        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6205            return false;
6206        }
6207        if (!skipPackageCheck && intent.getPackage() != null) {
6208            return false;
6209        }
6210        final boolean isWebUri = hasWebURI(intent);
6211        if (!isWebUri || intent.getData().getHost() == null) {
6212            return false;
6213        }
6214        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6215        // Or if there's already an ephemeral app installed that handles the action
6216        synchronized (mPackages) {
6217            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6218            for (int n = 0; n < count; n++) {
6219                final ResolveInfo info = resolvedActivities.get(n);
6220                final String packageName = info.activityInfo.packageName;
6221                final PackageSetting ps = mSettings.mPackages.get(packageName);
6222                if (ps != null) {
6223                    // only check domain verification status if the app is not a browser
6224                    if (!info.handleAllWebDataURI) {
6225                        // Try to get the status from User settings first
6226                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6227                        final int status = (int) (packedStatus >> 32);
6228                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6229                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6230                            if (DEBUG_EPHEMERAL) {
6231                                Slog.v(TAG, "DENY instant app;"
6232                                    + " pkg: " + packageName + ", status: " + status);
6233                            }
6234                            return false;
6235                        }
6236                    }
6237                    if (ps.getInstantApp(userId)) {
6238                        if (DEBUG_EPHEMERAL) {
6239                            Slog.v(TAG, "DENY instant app installed;"
6240                                    + " pkg: " + packageName);
6241                        }
6242                        return false;
6243                    }
6244                }
6245            }
6246        }
6247        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6248        return true;
6249    }
6250
6251    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6252            Intent origIntent, String resolvedType, String callingPackage,
6253            Bundle verificationBundle, int userId) {
6254        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6255                new InstantAppRequest(responseObj, origIntent, resolvedType,
6256                        callingPackage, userId, verificationBundle));
6257        mHandler.sendMessage(msg);
6258    }
6259
6260    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6261            int flags, List<ResolveInfo> query, int userId) {
6262        if (query != null) {
6263            final int N = query.size();
6264            if (N == 1) {
6265                return query.get(0);
6266            } else if (N > 1) {
6267                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6268                // If there is more than one activity with the same priority,
6269                // then let the user decide between them.
6270                ResolveInfo r0 = query.get(0);
6271                ResolveInfo r1 = query.get(1);
6272                if (DEBUG_INTENT_MATCHING || debug) {
6273                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6274                            + r1.activityInfo.name + "=" + r1.priority);
6275                }
6276                // If the first activity has a higher priority, or a different
6277                // default, then it is always desirable to pick it.
6278                if (r0.priority != r1.priority
6279                        || r0.preferredOrder != r1.preferredOrder
6280                        || r0.isDefault != r1.isDefault) {
6281                    return query.get(0);
6282                }
6283                // If we have saved a preference for a preferred activity for
6284                // this Intent, use that.
6285                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6286                        flags, query, r0.priority, true, false, debug, userId);
6287                if (ri != null) {
6288                    return ri;
6289                }
6290                // If we have an ephemeral app, use it
6291                for (int i = 0; i < N; i++) {
6292                    ri = query.get(i);
6293                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6294                        final String packageName = ri.activityInfo.packageName;
6295                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6296                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6297                        final int status = (int)(packedStatus >> 32);
6298                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6299                            return ri;
6300                        }
6301                    }
6302                }
6303                ri = new ResolveInfo(mResolveInfo);
6304                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6305                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6306                // If all of the options come from the same package, show the application's
6307                // label and icon instead of the generic resolver's.
6308                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6309                // and then throw away the ResolveInfo itself, meaning that the caller loses
6310                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6311                // a fallback for this case; we only set the target package's resources on
6312                // the ResolveInfo, not the ActivityInfo.
6313                final String intentPackage = intent.getPackage();
6314                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6315                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6316                    ri.resolvePackageName = intentPackage;
6317                    if (userNeedsBadging(userId)) {
6318                        ri.noResourceId = true;
6319                    } else {
6320                        ri.icon = appi.icon;
6321                    }
6322                    ri.iconResourceId = appi.icon;
6323                    ri.labelRes = appi.labelRes;
6324                }
6325                ri.activityInfo.applicationInfo = new ApplicationInfo(
6326                        ri.activityInfo.applicationInfo);
6327                if (userId != 0) {
6328                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6329                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6330                }
6331                // Make sure that the resolver is displayable in car mode
6332                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6333                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6334                return ri;
6335            }
6336        }
6337        return null;
6338    }
6339
6340    /**
6341     * Return true if the given list is not empty and all of its contents have
6342     * an activityInfo with the given package name.
6343     */
6344    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6345        if (ArrayUtils.isEmpty(list)) {
6346            return false;
6347        }
6348        for (int i = 0, N = list.size(); i < N; i++) {
6349            final ResolveInfo ri = list.get(i);
6350            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6351            if (ai == null || !packageName.equals(ai.packageName)) {
6352                return false;
6353            }
6354        }
6355        return true;
6356    }
6357
6358    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6359            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6360        final int N = query.size();
6361        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6362                .get(userId);
6363        // Get the list of persistent preferred activities that handle the intent
6364        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6365        List<PersistentPreferredActivity> pprefs = ppir != null
6366                ? ppir.queryIntent(intent, resolvedType,
6367                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6368                        userId)
6369                : null;
6370        if (pprefs != null && pprefs.size() > 0) {
6371            final int M = pprefs.size();
6372            for (int i=0; i<M; i++) {
6373                final PersistentPreferredActivity ppa = pprefs.get(i);
6374                if (DEBUG_PREFERRED || debug) {
6375                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6376                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6377                            + "\n  component=" + ppa.mComponent);
6378                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6379                }
6380                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6381                        flags | MATCH_DISABLED_COMPONENTS, userId);
6382                if (DEBUG_PREFERRED || debug) {
6383                    Slog.v(TAG, "Found persistent preferred activity:");
6384                    if (ai != null) {
6385                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6386                    } else {
6387                        Slog.v(TAG, "  null");
6388                    }
6389                }
6390                if (ai == null) {
6391                    // This previously registered persistent preferred activity
6392                    // component is no longer known. Ignore it and do NOT remove it.
6393                    continue;
6394                }
6395                for (int j=0; j<N; j++) {
6396                    final ResolveInfo ri = query.get(j);
6397                    if (!ri.activityInfo.applicationInfo.packageName
6398                            .equals(ai.applicationInfo.packageName)) {
6399                        continue;
6400                    }
6401                    if (!ri.activityInfo.name.equals(ai.name)) {
6402                        continue;
6403                    }
6404                    //  Found a persistent preference that can handle the intent.
6405                    if (DEBUG_PREFERRED || debug) {
6406                        Slog.v(TAG, "Returning persistent preferred activity: " +
6407                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6408                    }
6409                    return ri;
6410                }
6411            }
6412        }
6413        return null;
6414    }
6415
6416    // TODO: handle preferred activities missing while user has amnesia
6417    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6418            List<ResolveInfo> query, int priority, boolean always,
6419            boolean removeMatches, boolean debug, int userId) {
6420        if (!sUserManager.exists(userId)) return null;
6421        final int callingUid = Binder.getCallingUid();
6422        flags = updateFlagsForResolve(
6423                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6424        intent = updateIntentForResolve(intent);
6425        // writer
6426        synchronized (mPackages) {
6427            // Try to find a matching persistent preferred activity.
6428            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6429                    debug, userId);
6430
6431            // If a persistent preferred activity matched, use it.
6432            if (pri != null) {
6433                return pri;
6434            }
6435
6436            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6437            // Get the list of preferred activities that handle the intent
6438            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6439            List<PreferredActivity> prefs = pir != null
6440                    ? pir.queryIntent(intent, resolvedType,
6441                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6442                            userId)
6443                    : null;
6444            if (prefs != null && prefs.size() > 0) {
6445                boolean changed = false;
6446                try {
6447                    // First figure out how good the original match set is.
6448                    // We will only allow preferred activities that came
6449                    // from the same match quality.
6450                    int match = 0;
6451
6452                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6453
6454                    final int N = query.size();
6455                    for (int j=0; j<N; j++) {
6456                        final ResolveInfo ri = query.get(j);
6457                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6458                                + ": 0x" + Integer.toHexString(match));
6459                        if (ri.match > match) {
6460                            match = ri.match;
6461                        }
6462                    }
6463
6464                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6465                            + Integer.toHexString(match));
6466
6467                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6468                    final int M = prefs.size();
6469                    for (int i=0; i<M; i++) {
6470                        final PreferredActivity pa = prefs.get(i);
6471                        if (DEBUG_PREFERRED || debug) {
6472                            Slog.v(TAG, "Checking PreferredActivity ds="
6473                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6474                                    + "\n  component=" + pa.mPref.mComponent);
6475                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6476                        }
6477                        if (pa.mPref.mMatch != match) {
6478                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6479                                    + Integer.toHexString(pa.mPref.mMatch));
6480                            continue;
6481                        }
6482                        // If it's not an "always" type preferred activity and that's what we're
6483                        // looking for, skip it.
6484                        if (always && !pa.mPref.mAlways) {
6485                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6486                            continue;
6487                        }
6488                        final ActivityInfo ai = getActivityInfo(
6489                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6490                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6491                                userId);
6492                        if (DEBUG_PREFERRED || debug) {
6493                            Slog.v(TAG, "Found preferred activity:");
6494                            if (ai != null) {
6495                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6496                            } else {
6497                                Slog.v(TAG, "  null");
6498                            }
6499                        }
6500                        if (ai == null) {
6501                            // This previously registered preferred activity
6502                            // component is no longer known.  Most likely an update
6503                            // to the app was installed and in the new version this
6504                            // component no longer exists.  Clean it up by removing
6505                            // it from the preferred activities list, and skip it.
6506                            Slog.w(TAG, "Removing dangling preferred activity: "
6507                                    + pa.mPref.mComponent);
6508                            pir.removeFilter(pa);
6509                            changed = true;
6510                            continue;
6511                        }
6512                        for (int j=0; j<N; j++) {
6513                            final ResolveInfo ri = query.get(j);
6514                            if (!ri.activityInfo.applicationInfo.packageName
6515                                    .equals(ai.applicationInfo.packageName)) {
6516                                continue;
6517                            }
6518                            if (!ri.activityInfo.name.equals(ai.name)) {
6519                                continue;
6520                            }
6521
6522                            if (removeMatches) {
6523                                pir.removeFilter(pa);
6524                                changed = true;
6525                                if (DEBUG_PREFERRED) {
6526                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6527                                }
6528                                break;
6529                            }
6530
6531                            // Okay we found a previously set preferred or last chosen app.
6532                            // If the result set is different from when this
6533                            // was created, we need to clear it and re-ask the
6534                            // user their preference, if we're looking for an "always" type entry.
6535                            if (always && !pa.mPref.sameSet(query)) {
6536                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6537                                        + intent + " type " + resolvedType);
6538                                if (DEBUG_PREFERRED) {
6539                                    Slog.v(TAG, "Removing preferred activity since set changed "
6540                                            + pa.mPref.mComponent);
6541                                }
6542                                pir.removeFilter(pa);
6543                                // Re-add the filter as a "last chosen" entry (!always)
6544                                PreferredActivity lastChosen = new PreferredActivity(
6545                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6546                                pir.addFilter(lastChosen);
6547                                changed = true;
6548                                return null;
6549                            }
6550
6551                            // Yay! Either the set matched or we're looking for the last chosen
6552                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6553                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6554                            return ri;
6555                        }
6556                    }
6557                } finally {
6558                    if (changed) {
6559                        if (DEBUG_PREFERRED) {
6560                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6561                        }
6562                        scheduleWritePackageRestrictionsLocked(userId);
6563                    }
6564                }
6565            }
6566        }
6567        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6568        return null;
6569    }
6570
6571    /*
6572     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6573     */
6574    @Override
6575    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6576            int targetUserId) {
6577        mContext.enforceCallingOrSelfPermission(
6578                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6579        List<CrossProfileIntentFilter> matches =
6580                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6581        if (matches != null) {
6582            int size = matches.size();
6583            for (int i = 0; i < size; i++) {
6584                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6585            }
6586        }
6587        if (hasWebURI(intent)) {
6588            // cross-profile app linking works only towards the parent.
6589            final int callingUid = Binder.getCallingUid();
6590            final UserInfo parent = getProfileParent(sourceUserId);
6591            synchronized(mPackages) {
6592                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6593                        false /*includeInstantApps*/);
6594                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6595                        intent, resolvedType, flags, sourceUserId, parent.id);
6596                return xpDomainInfo != null;
6597            }
6598        }
6599        return false;
6600    }
6601
6602    private UserInfo getProfileParent(int userId) {
6603        final long identity = Binder.clearCallingIdentity();
6604        try {
6605            return sUserManager.getProfileParent(userId);
6606        } finally {
6607            Binder.restoreCallingIdentity(identity);
6608        }
6609    }
6610
6611    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6612            String resolvedType, int userId) {
6613        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6614        if (resolver != null) {
6615            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6616        }
6617        return null;
6618    }
6619
6620    @Override
6621    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6622            String resolvedType, int flags, int userId) {
6623        try {
6624            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6625
6626            return new ParceledListSlice<>(
6627                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6628        } finally {
6629            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6630        }
6631    }
6632
6633    /**
6634     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6635     * instant, returns {@code null}.
6636     */
6637    private String getInstantAppPackageName(int callingUid) {
6638        synchronized (mPackages) {
6639            // If the caller is an isolated app use the owner's uid for the lookup.
6640            if (Process.isIsolated(callingUid)) {
6641                callingUid = mIsolatedOwners.get(callingUid);
6642            }
6643            final int appId = UserHandle.getAppId(callingUid);
6644            final Object obj = mSettings.getUserIdLPr(appId);
6645            if (obj instanceof PackageSetting) {
6646                final PackageSetting ps = (PackageSetting) obj;
6647                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6648                return isInstantApp ? ps.pkg.packageName : null;
6649            }
6650        }
6651        return null;
6652    }
6653
6654    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6655            String resolvedType, int flags, int userId) {
6656        return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false);
6657    }
6658
6659    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6660            String resolvedType, int flags, int userId, boolean resolveForStart) {
6661        if (!sUserManager.exists(userId)) return Collections.emptyList();
6662        final int callingUid = Binder.getCallingUid();
6663        final String instantAppPkgName = getInstantAppPackageName(callingUid);
6664        enforceCrossUserPermission(callingUid, userId,
6665                false /* requireFullPermission */, false /* checkShell */,
6666                "query intent activities");
6667        final String pkgName = intent.getPackage();
6668        ComponentName comp = intent.getComponent();
6669        if (comp == null) {
6670            if (intent.getSelector() != null) {
6671                intent = intent.getSelector();
6672                comp = intent.getComponent();
6673            }
6674        }
6675
6676        flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart,
6677                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6678        if (comp != null) {
6679            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6680            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6681            if (ai != null) {
6682                // When specifying an explicit component, we prevent the activity from being
6683                // used when either 1) the calling package is normal and the activity is within
6684                // an ephemeral application or 2) the calling package is ephemeral and the
6685                // activity is not visible to ephemeral applications.
6686                final boolean matchInstantApp =
6687                        (flags & PackageManager.MATCH_INSTANT) != 0;
6688                final boolean matchVisibleToInstantAppOnly =
6689                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6690                final boolean matchExplicitlyVisibleOnly =
6691                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6692                final boolean isCallerInstantApp =
6693                        instantAppPkgName != null;
6694                final boolean isTargetSameInstantApp =
6695                        comp.getPackageName().equals(instantAppPkgName);
6696                final boolean isTargetInstantApp =
6697                        (ai.applicationInfo.privateFlags
6698                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6699                final boolean isTargetVisibleToInstantApp =
6700                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6701                final boolean isTargetExplicitlyVisibleToInstantApp =
6702                        isTargetVisibleToInstantApp
6703                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6704                final boolean isTargetHiddenFromInstantApp =
6705                        !isTargetVisibleToInstantApp
6706                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6707                final boolean blockResolution =
6708                        !isTargetSameInstantApp
6709                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6710                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6711                                        && isTargetHiddenFromInstantApp));
6712                if (!blockResolution) {
6713                    final ResolveInfo ri = new ResolveInfo();
6714                    ri.activityInfo = ai;
6715                    list.add(ri);
6716                }
6717            }
6718            return applyPostResolutionFilter(list, instantAppPkgName);
6719        }
6720
6721        // reader
6722        boolean sortResult = false;
6723        boolean addEphemeral = false;
6724        List<ResolveInfo> result;
6725        final boolean ephemeralDisabled = isEphemeralDisabled();
6726        synchronized (mPackages) {
6727            if (pkgName == null) {
6728                List<CrossProfileIntentFilter> matchingFilters =
6729                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6730                // Check for results that need to skip the current profile.
6731                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6732                        resolvedType, flags, userId);
6733                if (xpResolveInfo != null) {
6734                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6735                    xpResult.add(xpResolveInfo);
6736                    return applyPostResolutionFilter(
6737                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6738                }
6739
6740                // Check for results in the current profile.
6741                result = filterIfNotSystemUser(mActivities.queryIntent(
6742                        intent, resolvedType, flags, userId), userId);
6743                addEphemeral = !ephemeralDisabled
6744                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6745                // Check for cross profile results.
6746                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6747                xpResolveInfo = queryCrossProfileIntents(
6748                        matchingFilters, intent, resolvedType, flags, userId,
6749                        hasNonNegativePriorityResult);
6750                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6751                    boolean isVisibleToUser = filterIfNotSystemUser(
6752                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6753                    if (isVisibleToUser) {
6754                        result.add(xpResolveInfo);
6755                        sortResult = true;
6756                    }
6757                }
6758                if (hasWebURI(intent)) {
6759                    CrossProfileDomainInfo xpDomainInfo = null;
6760                    final UserInfo parent = getProfileParent(userId);
6761                    if (parent != null) {
6762                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6763                                flags, userId, parent.id);
6764                    }
6765                    if (xpDomainInfo != null) {
6766                        if (xpResolveInfo != null) {
6767                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6768                            // in the result.
6769                            result.remove(xpResolveInfo);
6770                        }
6771                        if (result.size() == 0 && !addEphemeral) {
6772                            // No result in current profile, but found candidate in parent user.
6773                            // And we are not going to add emphemeral app, so we can return the
6774                            // result straight away.
6775                            result.add(xpDomainInfo.resolveInfo);
6776                            return applyPostResolutionFilter(result, instantAppPkgName);
6777                        }
6778                    } else if (result.size() <= 1 && !addEphemeral) {
6779                        // No result in parent user and <= 1 result in current profile, and we
6780                        // are not going to add emphemeral app, so we can return the result without
6781                        // further processing.
6782                        return applyPostResolutionFilter(result, instantAppPkgName);
6783                    }
6784                    // We have more than one candidate (combining results from current and parent
6785                    // profile), so we need filtering and sorting.
6786                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6787                            intent, flags, result, xpDomainInfo, userId);
6788                    sortResult = true;
6789                }
6790            } else {
6791                final PackageParser.Package pkg = mPackages.get(pkgName);
6792                result = null;
6793                if (pkg != null) {
6794                    result = filterIfNotSystemUser(
6795                            mActivities.queryIntentForPackage(
6796                                    intent, resolvedType, flags, pkg.activities, userId),
6797                            userId);
6798                }
6799                if (result == null || result.size() == 0) {
6800                    // the caller wants to resolve for a particular package; however, there
6801                    // were no installed results, so, try to find an ephemeral result
6802                    addEphemeral = !ephemeralDisabled
6803                            && isInstantAppAllowed(
6804                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6805                    if (result == null) {
6806                        result = new ArrayList<>();
6807                    }
6808                }
6809            }
6810        }
6811        if (addEphemeral) {
6812            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
6813        }
6814        if (sortResult) {
6815            Collections.sort(result, mResolvePrioritySorter);
6816        }
6817        return applyPostResolutionFilter(result, instantAppPkgName);
6818    }
6819
6820    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6821            String resolvedType, int flags, int userId) {
6822        // first, check to see if we've got an instant app already installed
6823        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6824        ResolveInfo localInstantApp = null;
6825        boolean blockResolution = false;
6826        if (!alreadyResolvedLocally) {
6827            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6828                    flags
6829                        | PackageManager.GET_RESOLVED_FILTER
6830                        | PackageManager.MATCH_INSTANT
6831                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6832                    userId);
6833            for (int i = instantApps.size() - 1; i >= 0; --i) {
6834                final ResolveInfo info = instantApps.get(i);
6835                final String packageName = info.activityInfo.packageName;
6836                final PackageSetting ps = mSettings.mPackages.get(packageName);
6837                if (ps.getInstantApp(userId)) {
6838                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6839                    final int status = (int)(packedStatus >> 32);
6840                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6841                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6842                        // there's a local instant application installed, but, the user has
6843                        // chosen to never use it; skip resolution and don't acknowledge
6844                        // an instant application is even available
6845                        if (DEBUG_EPHEMERAL) {
6846                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6847                        }
6848                        blockResolution = true;
6849                        break;
6850                    } else {
6851                        // we have a locally installed instant application; skip resolution
6852                        // but acknowledge there's an instant application available
6853                        if (DEBUG_EPHEMERAL) {
6854                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6855                        }
6856                        localInstantApp = info;
6857                        break;
6858                    }
6859                }
6860            }
6861        }
6862        // no app installed, let's see if one's available
6863        AuxiliaryResolveInfo auxiliaryResponse = null;
6864        if (!blockResolution) {
6865            if (localInstantApp == null) {
6866                // we don't have an instant app locally, resolve externally
6867                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6868                final InstantAppRequest requestObject = new InstantAppRequest(
6869                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6870                        null /*callingPackage*/, userId, null /*verificationBundle*/);
6871                auxiliaryResponse =
6872                        InstantAppResolver.doInstantAppResolutionPhaseOne(
6873                                mContext, mInstantAppResolverConnection, requestObject);
6874                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6875            } else {
6876                // we have an instant application locally, but, we can't admit that since
6877                // callers shouldn't be able to determine prior browsing. create a dummy
6878                // auxiliary response so the downstream code behaves as if there's an
6879                // instant application available externally. when it comes time to start
6880                // the instant application, we'll do the right thing.
6881                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6882                auxiliaryResponse = new AuxiliaryResolveInfo(
6883                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
6884            }
6885        }
6886        if (auxiliaryResponse != null) {
6887            if (DEBUG_EPHEMERAL) {
6888                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6889            }
6890            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6891            final PackageSetting ps =
6892                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6893            if (ps != null) {
6894                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6895                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6896                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6897                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6898                // make sure this resolver is the default
6899                ephemeralInstaller.isDefault = true;
6900                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6901                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6902                // add a non-generic filter
6903                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6904                ephemeralInstaller.filter.addDataPath(
6905                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6906                ephemeralInstaller.isInstantAppAvailable = true;
6907                result.add(ephemeralInstaller);
6908            }
6909        }
6910        return result;
6911    }
6912
6913    private static class CrossProfileDomainInfo {
6914        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6915        ResolveInfo resolveInfo;
6916        /* Best domain verification status of the activities found in the other profile */
6917        int bestDomainVerificationStatus;
6918    }
6919
6920    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6921            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6922        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6923                sourceUserId)) {
6924            return null;
6925        }
6926        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6927                resolvedType, flags, parentUserId);
6928
6929        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6930            return null;
6931        }
6932        CrossProfileDomainInfo result = null;
6933        int size = resultTargetUser.size();
6934        for (int i = 0; i < size; i++) {
6935            ResolveInfo riTargetUser = resultTargetUser.get(i);
6936            // Intent filter verification is only for filters that specify a host. So don't return
6937            // those that handle all web uris.
6938            if (riTargetUser.handleAllWebDataURI) {
6939                continue;
6940            }
6941            String packageName = riTargetUser.activityInfo.packageName;
6942            PackageSetting ps = mSettings.mPackages.get(packageName);
6943            if (ps == null) {
6944                continue;
6945            }
6946            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6947            int status = (int)(verificationState >> 32);
6948            if (result == null) {
6949                result = new CrossProfileDomainInfo();
6950                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6951                        sourceUserId, parentUserId);
6952                result.bestDomainVerificationStatus = status;
6953            } else {
6954                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6955                        result.bestDomainVerificationStatus);
6956            }
6957        }
6958        // Don't consider matches with status NEVER across profiles.
6959        if (result != null && result.bestDomainVerificationStatus
6960                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6961            return null;
6962        }
6963        return result;
6964    }
6965
6966    /**
6967     * Verification statuses are ordered from the worse to the best, except for
6968     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6969     */
6970    private int bestDomainVerificationStatus(int status1, int status2) {
6971        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6972            return status2;
6973        }
6974        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6975            return status1;
6976        }
6977        return (int) MathUtils.max(status1, status2);
6978    }
6979
6980    private boolean isUserEnabled(int userId) {
6981        long callingId = Binder.clearCallingIdentity();
6982        try {
6983            UserInfo userInfo = sUserManager.getUserInfo(userId);
6984            return userInfo != null && userInfo.isEnabled();
6985        } finally {
6986            Binder.restoreCallingIdentity(callingId);
6987        }
6988    }
6989
6990    /**
6991     * Filter out activities with systemUserOnly flag set, when current user is not System.
6992     *
6993     * @return filtered list
6994     */
6995    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6996        if (userId == UserHandle.USER_SYSTEM) {
6997            return resolveInfos;
6998        }
6999        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7000            ResolveInfo info = resolveInfos.get(i);
7001            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7002                resolveInfos.remove(i);
7003            }
7004        }
7005        return resolveInfos;
7006    }
7007
7008    /**
7009     * Filters out ephemeral activities.
7010     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7011     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7012     *
7013     * @param resolveInfos The pre-filtered list of resolved activities
7014     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7015     *          is performed.
7016     * @return A filtered list of resolved activities.
7017     */
7018    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7019            String ephemeralPkgName) {
7020        // TODO: When adding on-demand split support for non-instant apps, remove this check
7021        // and always apply post filtering
7022        if (ephemeralPkgName == null) {
7023            return resolveInfos;
7024        }
7025        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7026            final ResolveInfo info = resolveInfos.get(i);
7027            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7028            // allow activities that are defined in the provided package
7029            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
7030                if (info.activityInfo.splitName != null
7031                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7032                                info.activityInfo.splitName)) {
7033                    // requested activity is defined in a split that hasn't been installed yet.
7034                    // add the installer to the resolve list
7035                    if (DEBUG_EPHEMERAL) {
7036                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7037                    }
7038                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7039                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7040                            info.activityInfo.packageName, info.activityInfo.splitName,
7041                            info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7042                    // make sure this resolver is the default
7043                    installerInfo.isDefault = true;
7044                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7045                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7046                    // add a non-generic filter
7047                    installerInfo.filter = new IntentFilter();
7048                    // load resources from the correct package
7049                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7050                    resolveInfos.set(i, installerInfo);
7051                }
7052                continue;
7053            }
7054            // allow activities that have been explicitly exposed to ephemeral apps
7055            if (!isEphemeralApp
7056                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7057                continue;
7058            }
7059            resolveInfos.remove(i);
7060        }
7061        return resolveInfos;
7062    }
7063
7064    /**
7065     * @param resolveInfos list of resolve infos in descending priority order
7066     * @return if the list contains a resolve info with non-negative priority
7067     */
7068    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7069        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7070    }
7071
7072    private static boolean hasWebURI(Intent intent) {
7073        if (intent.getData() == null) {
7074            return false;
7075        }
7076        final String scheme = intent.getScheme();
7077        if (TextUtils.isEmpty(scheme)) {
7078            return false;
7079        }
7080        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7081    }
7082
7083    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7084            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7085            int userId) {
7086        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7087
7088        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7089            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7090                    candidates.size());
7091        }
7092
7093        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7094        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7095        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7096        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7097        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7098        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7099
7100        synchronized (mPackages) {
7101            final int count = candidates.size();
7102            // First, try to use linked apps. Partition the candidates into four lists:
7103            // one for the final results, one for the "do not use ever", one for "undefined status"
7104            // and finally one for "browser app type".
7105            for (int n=0; n<count; n++) {
7106                ResolveInfo info = candidates.get(n);
7107                String packageName = info.activityInfo.packageName;
7108                PackageSetting ps = mSettings.mPackages.get(packageName);
7109                if (ps != null) {
7110                    // Add to the special match all list (Browser use case)
7111                    if (info.handleAllWebDataURI) {
7112                        matchAllList.add(info);
7113                        continue;
7114                    }
7115                    // Try to get the status from User settings first
7116                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7117                    int status = (int)(packedStatus >> 32);
7118                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7119                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7120                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7121                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7122                                    + " : linkgen=" + linkGeneration);
7123                        }
7124                        // Use link-enabled generation as preferredOrder, i.e.
7125                        // prefer newly-enabled over earlier-enabled.
7126                        info.preferredOrder = linkGeneration;
7127                        alwaysList.add(info);
7128                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7129                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7130                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7131                        }
7132                        neverList.add(info);
7133                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7134                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7135                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7136                        }
7137                        alwaysAskList.add(info);
7138                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7139                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7140                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7141                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7142                        }
7143                        undefinedList.add(info);
7144                    }
7145                }
7146            }
7147
7148            // We'll want to include browser possibilities in a few cases
7149            boolean includeBrowser = false;
7150
7151            // First try to add the "always" resolution(s) for the current user, if any
7152            if (alwaysList.size() > 0) {
7153                result.addAll(alwaysList);
7154            } else {
7155                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7156                result.addAll(undefinedList);
7157                // Maybe add one for the other profile.
7158                if (xpDomainInfo != null && (
7159                        xpDomainInfo.bestDomainVerificationStatus
7160                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7161                    result.add(xpDomainInfo.resolveInfo);
7162                }
7163                includeBrowser = true;
7164            }
7165
7166            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7167            // If there were 'always' entries their preferred order has been set, so we also
7168            // back that off to make the alternatives equivalent
7169            if (alwaysAskList.size() > 0) {
7170                for (ResolveInfo i : result) {
7171                    i.preferredOrder = 0;
7172                }
7173                result.addAll(alwaysAskList);
7174                includeBrowser = true;
7175            }
7176
7177            if (includeBrowser) {
7178                // Also add browsers (all of them or only the default one)
7179                if (DEBUG_DOMAIN_VERIFICATION) {
7180                    Slog.v(TAG, "   ...including browsers in candidate set");
7181                }
7182                if ((matchFlags & MATCH_ALL) != 0) {
7183                    result.addAll(matchAllList);
7184                } else {
7185                    // Browser/generic handling case.  If there's a default browser, go straight
7186                    // to that (but only if there is no other higher-priority match).
7187                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7188                    int maxMatchPrio = 0;
7189                    ResolveInfo defaultBrowserMatch = null;
7190                    final int numCandidates = matchAllList.size();
7191                    for (int n = 0; n < numCandidates; n++) {
7192                        ResolveInfo info = matchAllList.get(n);
7193                        // track the highest overall match priority...
7194                        if (info.priority > maxMatchPrio) {
7195                            maxMatchPrio = info.priority;
7196                        }
7197                        // ...and the highest-priority default browser match
7198                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7199                            if (defaultBrowserMatch == null
7200                                    || (defaultBrowserMatch.priority < info.priority)) {
7201                                if (debug) {
7202                                    Slog.v(TAG, "Considering default browser match " + info);
7203                                }
7204                                defaultBrowserMatch = info;
7205                            }
7206                        }
7207                    }
7208                    if (defaultBrowserMatch != null
7209                            && defaultBrowserMatch.priority >= maxMatchPrio
7210                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7211                    {
7212                        if (debug) {
7213                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7214                        }
7215                        result.add(defaultBrowserMatch);
7216                    } else {
7217                        result.addAll(matchAllList);
7218                    }
7219                }
7220
7221                // If there is nothing selected, add all candidates and remove the ones that the user
7222                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7223                if (result.size() == 0) {
7224                    result.addAll(candidates);
7225                    result.removeAll(neverList);
7226                }
7227            }
7228        }
7229        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7230            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7231                    result.size());
7232            for (ResolveInfo info : result) {
7233                Slog.v(TAG, "  + " + info.activityInfo);
7234            }
7235        }
7236        return result;
7237    }
7238
7239    // Returns a packed value as a long:
7240    //
7241    // high 'int'-sized word: link status: undefined/ask/never/always.
7242    // low 'int'-sized word: relative priority among 'always' results.
7243    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7244        long result = ps.getDomainVerificationStatusForUser(userId);
7245        // if none available, get the master status
7246        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7247            if (ps.getIntentFilterVerificationInfo() != null) {
7248                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7249            }
7250        }
7251        return result;
7252    }
7253
7254    private ResolveInfo querySkipCurrentProfileIntents(
7255            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7256            int flags, int sourceUserId) {
7257        if (matchingFilters != null) {
7258            int size = matchingFilters.size();
7259            for (int i = 0; i < size; i ++) {
7260                CrossProfileIntentFilter filter = matchingFilters.get(i);
7261                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7262                    // Checking if there are activities in the target user that can handle the
7263                    // intent.
7264                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7265                            resolvedType, flags, sourceUserId);
7266                    if (resolveInfo != null) {
7267                        return resolveInfo;
7268                    }
7269                }
7270            }
7271        }
7272        return null;
7273    }
7274
7275    // Return matching ResolveInfo in target user if any.
7276    private ResolveInfo queryCrossProfileIntents(
7277            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7278            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7279        if (matchingFilters != null) {
7280            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7281            // match the same intent. For performance reasons, it is better not to
7282            // run queryIntent twice for the same userId
7283            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7284            int size = matchingFilters.size();
7285            for (int i = 0; i < size; i++) {
7286                CrossProfileIntentFilter filter = matchingFilters.get(i);
7287                int targetUserId = filter.getTargetUserId();
7288                boolean skipCurrentProfile =
7289                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7290                boolean skipCurrentProfileIfNoMatchFound =
7291                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7292                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7293                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7294                    // Checking if there are activities in the target user that can handle the
7295                    // intent.
7296                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7297                            resolvedType, flags, sourceUserId);
7298                    if (resolveInfo != null) return resolveInfo;
7299                    alreadyTriedUserIds.put(targetUserId, true);
7300                }
7301            }
7302        }
7303        return null;
7304    }
7305
7306    /**
7307     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7308     * will forward the intent to the filter's target user.
7309     * Otherwise, returns null.
7310     */
7311    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7312            String resolvedType, int flags, int sourceUserId) {
7313        int targetUserId = filter.getTargetUserId();
7314        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7315                resolvedType, flags, targetUserId);
7316        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7317            // If all the matches in the target profile are suspended, return null.
7318            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7319                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7320                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7321                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7322                            targetUserId);
7323                }
7324            }
7325        }
7326        return null;
7327    }
7328
7329    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7330            int sourceUserId, int targetUserId) {
7331        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7332        long ident = Binder.clearCallingIdentity();
7333        boolean targetIsProfile;
7334        try {
7335            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7336        } finally {
7337            Binder.restoreCallingIdentity(ident);
7338        }
7339        String className;
7340        if (targetIsProfile) {
7341            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7342        } else {
7343            className = FORWARD_INTENT_TO_PARENT;
7344        }
7345        ComponentName forwardingActivityComponentName = new ComponentName(
7346                mAndroidApplication.packageName, className);
7347        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7348                sourceUserId);
7349        if (!targetIsProfile) {
7350            forwardingActivityInfo.showUserIcon = targetUserId;
7351            forwardingResolveInfo.noResourceId = true;
7352        }
7353        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7354        forwardingResolveInfo.priority = 0;
7355        forwardingResolveInfo.preferredOrder = 0;
7356        forwardingResolveInfo.match = 0;
7357        forwardingResolveInfo.isDefault = true;
7358        forwardingResolveInfo.filter = filter;
7359        forwardingResolveInfo.targetUserId = targetUserId;
7360        return forwardingResolveInfo;
7361    }
7362
7363    @Override
7364    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7365            Intent[] specifics, String[] specificTypes, Intent intent,
7366            String resolvedType, int flags, int userId) {
7367        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7368                specificTypes, intent, resolvedType, flags, userId));
7369    }
7370
7371    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7372            Intent[] specifics, String[] specificTypes, Intent intent,
7373            String resolvedType, int flags, int userId) {
7374        if (!sUserManager.exists(userId)) return Collections.emptyList();
7375        final int callingUid = Binder.getCallingUid();
7376        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7377                false /*includeInstantApps*/);
7378        enforceCrossUserPermission(callingUid, userId,
7379                false /*requireFullPermission*/, false /*checkShell*/,
7380                "query intent activity options");
7381        final String resultsAction = intent.getAction();
7382
7383        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7384                | PackageManager.GET_RESOLVED_FILTER, userId);
7385
7386        if (DEBUG_INTENT_MATCHING) {
7387            Log.v(TAG, "Query " + intent + ": " + results);
7388        }
7389
7390        int specificsPos = 0;
7391        int N;
7392
7393        // todo: note that the algorithm used here is O(N^2).  This
7394        // isn't a problem in our current environment, but if we start running
7395        // into situations where we have more than 5 or 10 matches then this
7396        // should probably be changed to something smarter...
7397
7398        // First we go through and resolve each of the specific items
7399        // that were supplied, taking care of removing any corresponding
7400        // duplicate items in the generic resolve list.
7401        if (specifics != null) {
7402            for (int i=0; i<specifics.length; i++) {
7403                final Intent sintent = specifics[i];
7404                if (sintent == null) {
7405                    continue;
7406                }
7407
7408                if (DEBUG_INTENT_MATCHING) {
7409                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7410                }
7411
7412                String action = sintent.getAction();
7413                if (resultsAction != null && resultsAction.equals(action)) {
7414                    // If this action was explicitly requested, then don't
7415                    // remove things that have it.
7416                    action = null;
7417                }
7418
7419                ResolveInfo ri = null;
7420                ActivityInfo ai = null;
7421
7422                ComponentName comp = sintent.getComponent();
7423                if (comp == null) {
7424                    ri = resolveIntent(
7425                        sintent,
7426                        specificTypes != null ? specificTypes[i] : null,
7427                            flags, userId);
7428                    if (ri == null) {
7429                        continue;
7430                    }
7431                    if (ri == mResolveInfo) {
7432                        // ACK!  Must do something better with this.
7433                    }
7434                    ai = ri.activityInfo;
7435                    comp = new ComponentName(ai.applicationInfo.packageName,
7436                            ai.name);
7437                } else {
7438                    ai = getActivityInfo(comp, flags, userId);
7439                    if (ai == null) {
7440                        continue;
7441                    }
7442                }
7443
7444                // Look for any generic query activities that are duplicates
7445                // of this specific one, and remove them from the results.
7446                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7447                N = results.size();
7448                int j;
7449                for (j=specificsPos; j<N; j++) {
7450                    ResolveInfo sri = results.get(j);
7451                    if ((sri.activityInfo.name.equals(comp.getClassName())
7452                            && sri.activityInfo.applicationInfo.packageName.equals(
7453                                    comp.getPackageName()))
7454                        || (action != null && sri.filter.matchAction(action))) {
7455                        results.remove(j);
7456                        if (DEBUG_INTENT_MATCHING) Log.v(
7457                            TAG, "Removing duplicate item from " + j
7458                            + " due to specific " + specificsPos);
7459                        if (ri == null) {
7460                            ri = sri;
7461                        }
7462                        j--;
7463                        N--;
7464                    }
7465                }
7466
7467                // Add this specific item to its proper place.
7468                if (ri == null) {
7469                    ri = new ResolveInfo();
7470                    ri.activityInfo = ai;
7471                }
7472                results.add(specificsPos, ri);
7473                ri.specificIndex = i;
7474                specificsPos++;
7475            }
7476        }
7477
7478        // Now we go through the remaining generic results and remove any
7479        // duplicate actions that are found here.
7480        N = results.size();
7481        for (int i=specificsPos; i<N-1; i++) {
7482            final ResolveInfo rii = results.get(i);
7483            if (rii.filter == null) {
7484                continue;
7485            }
7486
7487            // Iterate over all of the actions of this result's intent
7488            // filter...  typically this should be just one.
7489            final Iterator<String> it = rii.filter.actionsIterator();
7490            if (it == null) {
7491                continue;
7492            }
7493            while (it.hasNext()) {
7494                final String action = it.next();
7495                if (resultsAction != null && resultsAction.equals(action)) {
7496                    // If this action was explicitly requested, then don't
7497                    // remove things that have it.
7498                    continue;
7499                }
7500                for (int j=i+1; j<N; j++) {
7501                    final ResolveInfo rij = results.get(j);
7502                    if (rij.filter != null && rij.filter.hasAction(action)) {
7503                        results.remove(j);
7504                        if (DEBUG_INTENT_MATCHING) Log.v(
7505                            TAG, "Removing duplicate item from " + j
7506                            + " due to action " + action + " at " + i);
7507                        j--;
7508                        N--;
7509                    }
7510                }
7511            }
7512
7513            // If the caller didn't request filter information, drop it now
7514            // so we don't have to marshall/unmarshall it.
7515            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7516                rii.filter = null;
7517            }
7518        }
7519
7520        // Filter out the caller activity if so requested.
7521        if (caller != null) {
7522            N = results.size();
7523            for (int i=0; i<N; i++) {
7524                ActivityInfo ainfo = results.get(i).activityInfo;
7525                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7526                        && caller.getClassName().equals(ainfo.name)) {
7527                    results.remove(i);
7528                    break;
7529                }
7530            }
7531        }
7532
7533        // If the caller didn't request filter information,
7534        // drop them now so we don't have to
7535        // marshall/unmarshall it.
7536        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7537            N = results.size();
7538            for (int i=0; i<N; i++) {
7539                results.get(i).filter = null;
7540            }
7541        }
7542
7543        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7544        return results;
7545    }
7546
7547    @Override
7548    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7549            String resolvedType, int flags, int userId) {
7550        return new ParceledListSlice<>(
7551                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7552    }
7553
7554    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7555            String resolvedType, int flags, int userId) {
7556        if (!sUserManager.exists(userId)) return Collections.emptyList();
7557        final int callingUid = Binder.getCallingUid();
7558        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7559                false /*includeInstantApps*/);
7560        ComponentName comp = intent.getComponent();
7561        if (comp == null) {
7562            if (intent.getSelector() != null) {
7563                intent = intent.getSelector();
7564                comp = intent.getComponent();
7565            }
7566        }
7567        if (comp != null) {
7568            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7569            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7570            if (ai != null) {
7571                ResolveInfo ri = new ResolveInfo();
7572                ri.activityInfo = ai;
7573                list.add(ri);
7574            }
7575            return list;
7576        }
7577
7578        // reader
7579        synchronized (mPackages) {
7580            String pkgName = intent.getPackage();
7581            if (pkgName == null) {
7582                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
7583            }
7584            final PackageParser.Package pkg = mPackages.get(pkgName);
7585            if (pkg != null) {
7586                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
7587                        userId);
7588            }
7589            return Collections.emptyList();
7590        }
7591    }
7592
7593    @Override
7594    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7595        final int callingUid = Binder.getCallingUid();
7596        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7597    }
7598
7599    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7600            int userId, int callingUid) {
7601        if (!sUserManager.exists(userId)) return null;
7602        flags = updateFlagsForResolve(
7603                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7604        List<ResolveInfo> query = queryIntentServicesInternal(
7605                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7606        if (query != null) {
7607            if (query.size() >= 1) {
7608                // If there is more than one service with the same priority,
7609                // just arbitrarily pick the first one.
7610                return query.get(0);
7611            }
7612        }
7613        return null;
7614    }
7615
7616    @Override
7617    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7618            String resolvedType, int flags, int userId) {
7619        final int callingUid = Binder.getCallingUid();
7620        return new ParceledListSlice<>(queryIntentServicesInternal(
7621                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7622    }
7623
7624    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7625            String resolvedType, int flags, int userId, int callingUid,
7626            boolean includeInstantApps) {
7627        if (!sUserManager.exists(userId)) return Collections.emptyList();
7628        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7629        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7630        ComponentName comp = intent.getComponent();
7631        if (comp == null) {
7632            if (intent.getSelector() != null) {
7633                intent = intent.getSelector();
7634                comp = intent.getComponent();
7635            }
7636        }
7637        if (comp != null) {
7638            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7639            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7640            if (si != null) {
7641                // When specifying an explicit component, we prevent the service from being
7642                // used when either 1) the service is in an instant application and the
7643                // caller is not the same instant application or 2) the calling package is
7644                // ephemeral and the activity is not visible to ephemeral applications.
7645                final boolean matchInstantApp =
7646                        (flags & PackageManager.MATCH_INSTANT) != 0;
7647                final boolean matchVisibleToInstantAppOnly =
7648                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7649                final boolean isCallerInstantApp =
7650                        instantAppPkgName != null;
7651                final boolean isTargetSameInstantApp =
7652                        comp.getPackageName().equals(instantAppPkgName);
7653                final boolean isTargetInstantApp =
7654                        (si.applicationInfo.privateFlags
7655                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7656                final boolean isTargetHiddenFromInstantApp =
7657                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7658                final boolean blockResolution =
7659                        !isTargetSameInstantApp
7660                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7661                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7662                                        && isTargetHiddenFromInstantApp));
7663                if (!blockResolution) {
7664                    final ResolveInfo ri = new ResolveInfo();
7665                    ri.serviceInfo = si;
7666                    list.add(ri);
7667                }
7668            }
7669            return list;
7670        }
7671
7672        // reader
7673        synchronized (mPackages) {
7674            String pkgName = intent.getPackage();
7675            if (pkgName == null) {
7676                return applyPostServiceResolutionFilter(
7677                        mServices.queryIntent(intent, resolvedType, flags, userId),
7678                        instantAppPkgName);
7679            }
7680            final PackageParser.Package pkg = mPackages.get(pkgName);
7681            if (pkg != null) {
7682                return applyPostServiceResolutionFilter(
7683                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7684                                userId),
7685                        instantAppPkgName);
7686            }
7687            return Collections.emptyList();
7688        }
7689    }
7690
7691    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7692            String instantAppPkgName) {
7693        // TODO: When adding on-demand split support for non-instant apps, remove this check
7694        // and always apply post filtering
7695        if (instantAppPkgName == null) {
7696            return resolveInfos;
7697        }
7698        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7699            final ResolveInfo info = resolveInfos.get(i);
7700            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7701            // allow services that are defined in the provided package
7702            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7703                if (info.serviceInfo.splitName != null
7704                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7705                                info.serviceInfo.splitName)) {
7706                    // requested service is defined in a split that hasn't been installed yet.
7707                    // add the installer to the resolve list
7708                    if (DEBUG_EPHEMERAL) {
7709                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7710                    }
7711                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7712                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7713                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7714                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
7715                    // make sure this resolver is the default
7716                    installerInfo.isDefault = true;
7717                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7718                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7719                    // add a non-generic filter
7720                    installerInfo.filter = new IntentFilter();
7721                    // load resources from the correct package
7722                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7723                    resolveInfos.set(i, installerInfo);
7724                }
7725                continue;
7726            }
7727            // allow services that have been explicitly exposed to ephemeral apps
7728            if (!isEphemeralApp
7729                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7730                continue;
7731            }
7732            resolveInfos.remove(i);
7733        }
7734        return resolveInfos;
7735    }
7736
7737    @Override
7738    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7739            String resolvedType, int flags, int userId) {
7740        return new ParceledListSlice<>(
7741                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7742    }
7743
7744    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7745            Intent intent, String resolvedType, int flags, int userId) {
7746        if (!sUserManager.exists(userId)) return Collections.emptyList();
7747        final int callingUid = Binder.getCallingUid();
7748        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7749        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7750                false /*includeInstantApps*/);
7751        ComponentName comp = intent.getComponent();
7752        if (comp == null) {
7753            if (intent.getSelector() != null) {
7754                intent = intent.getSelector();
7755                comp = intent.getComponent();
7756            }
7757        }
7758        if (comp != null) {
7759            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7760            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7761            if (pi != null) {
7762                // When specifying an explicit component, we prevent the provider from being
7763                // used when either 1) the provider is in an instant application and the
7764                // caller is not the same instant application or 2) the calling package is an
7765                // instant application and the provider is not visible to instant applications.
7766                final boolean matchInstantApp =
7767                        (flags & PackageManager.MATCH_INSTANT) != 0;
7768                final boolean matchVisibleToInstantAppOnly =
7769                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7770                final boolean isCallerInstantApp =
7771                        instantAppPkgName != null;
7772                final boolean isTargetSameInstantApp =
7773                        comp.getPackageName().equals(instantAppPkgName);
7774                final boolean isTargetInstantApp =
7775                        (pi.applicationInfo.privateFlags
7776                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7777                final boolean isTargetHiddenFromInstantApp =
7778                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7779                final boolean blockResolution =
7780                        !isTargetSameInstantApp
7781                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7782                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7783                                        && isTargetHiddenFromInstantApp));
7784                if (!blockResolution) {
7785                    final ResolveInfo ri = new ResolveInfo();
7786                    ri.providerInfo = pi;
7787                    list.add(ri);
7788                }
7789            }
7790            return list;
7791        }
7792
7793        // reader
7794        synchronized (mPackages) {
7795            String pkgName = intent.getPackage();
7796            if (pkgName == null) {
7797                return applyPostContentProviderResolutionFilter(
7798                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7799                        instantAppPkgName);
7800            }
7801            final PackageParser.Package pkg = mPackages.get(pkgName);
7802            if (pkg != null) {
7803                return applyPostContentProviderResolutionFilter(
7804                        mProviders.queryIntentForPackage(
7805                        intent, resolvedType, flags, pkg.providers, userId),
7806                        instantAppPkgName);
7807            }
7808            return Collections.emptyList();
7809        }
7810    }
7811
7812    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7813            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7814        // TODO: When adding on-demand split support for non-instant applications, remove
7815        // this check and always apply post filtering
7816        if (instantAppPkgName == null) {
7817            return resolveInfos;
7818        }
7819        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7820            final ResolveInfo info = resolveInfos.get(i);
7821            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7822            // allow providers that are defined in the provided package
7823            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7824                if (info.providerInfo.splitName != null
7825                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7826                                info.providerInfo.splitName)) {
7827                    // requested provider is defined in a split that hasn't been installed yet.
7828                    // add the installer to the resolve list
7829                    if (DEBUG_EPHEMERAL) {
7830                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7831                    }
7832                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7833                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7834                            info.providerInfo.packageName, info.providerInfo.splitName,
7835                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
7836                    // make sure this resolver is the default
7837                    installerInfo.isDefault = true;
7838                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7839                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7840                    // add a non-generic filter
7841                    installerInfo.filter = new IntentFilter();
7842                    // load resources from the correct package
7843                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7844                    resolveInfos.set(i, installerInfo);
7845                }
7846                continue;
7847            }
7848            // allow providers that have been explicitly exposed to instant applications
7849            if (!isEphemeralApp
7850                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7851                continue;
7852            }
7853            resolveInfos.remove(i);
7854        }
7855        return resolveInfos;
7856    }
7857
7858    @Override
7859    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7860        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
7861            return ParceledListSlice.emptyList();
7862        }
7863        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7864        flags = updateFlagsForPackage(flags, userId, null);
7865        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7866        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7867                true /* requireFullPermission */, false /* checkShell */,
7868                "get installed packages");
7869
7870        // writer
7871        synchronized (mPackages) {
7872            ArrayList<PackageInfo> list;
7873            if (listUninstalled) {
7874                list = new ArrayList<>(mSettings.mPackages.size());
7875                for (PackageSetting ps : mSettings.mPackages.values()) {
7876                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7877                        continue;
7878                    }
7879                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7880                    if (pi != null) {
7881                        list.add(pi);
7882                    }
7883                }
7884            } else {
7885                list = new ArrayList<>(mPackages.size());
7886                for (PackageParser.Package p : mPackages.values()) {
7887                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
7888                            Binder.getCallingUid(), userId, flags)) {
7889                        continue;
7890                    }
7891                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7892                            p.mExtras, flags, userId);
7893                    if (pi != null) {
7894                        list.add(pi);
7895                    }
7896                }
7897            }
7898
7899            return new ParceledListSlice<>(list);
7900        }
7901    }
7902
7903    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7904            String[] permissions, boolean[] tmp, int flags, int userId) {
7905        int numMatch = 0;
7906        final PermissionsState permissionsState = ps.getPermissionsState();
7907        for (int i=0; i<permissions.length; i++) {
7908            final String permission = permissions[i];
7909            if (permissionsState.hasPermission(permission, userId)) {
7910                tmp[i] = true;
7911                numMatch++;
7912            } else {
7913                tmp[i] = false;
7914            }
7915        }
7916        if (numMatch == 0) {
7917            return;
7918        }
7919        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7920
7921        // The above might return null in cases of uninstalled apps or install-state
7922        // skew across users/profiles.
7923        if (pi != null) {
7924            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7925                if (numMatch == permissions.length) {
7926                    pi.requestedPermissions = permissions;
7927                } else {
7928                    pi.requestedPermissions = new String[numMatch];
7929                    numMatch = 0;
7930                    for (int i=0; i<permissions.length; i++) {
7931                        if (tmp[i]) {
7932                            pi.requestedPermissions[numMatch] = permissions[i];
7933                            numMatch++;
7934                        }
7935                    }
7936                }
7937            }
7938            list.add(pi);
7939        }
7940    }
7941
7942    @Override
7943    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7944            String[] permissions, int flags, int userId) {
7945        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7946        flags = updateFlagsForPackage(flags, userId, permissions);
7947        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7948                true /* requireFullPermission */, false /* checkShell */,
7949                "get packages holding permissions");
7950        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7951
7952        // writer
7953        synchronized (mPackages) {
7954            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7955            boolean[] tmpBools = new boolean[permissions.length];
7956            if (listUninstalled) {
7957                for (PackageSetting ps : mSettings.mPackages.values()) {
7958                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7959                            userId);
7960                }
7961            } else {
7962                for (PackageParser.Package pkg : mPackages.values()) {
7963                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7964                    if (ps != null) {
7965                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7966                                userId);
7967                    }
7968                }
7969            }
7970
7971            return new ParceledListSlice<PackageInfo>(list);
7972        }
7973    }
7974
7975    @Override
7976    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7977        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
7978            return ParceledListSlice.emptyList();
7979        }
7980        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7981        flags = updateFlagsForApplication(flags, userId, null);
7982        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7983
7984        // writer
7985        synchronized (mPackages) {
7986            ArrayList<ApplicationInfo> list;
7987            if (listUninstalled) {
7988                list = new ArrayList<>(mSettings.mPackages.size());
7989                for (PackageSetting ps : mSettings.mPackages.values()) {
7990                    ApplicationInfo ai;
7991                    int effectiveFlags = flags;
7992                    if (ps.isSystem()) {
7993                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7994                    }
7995                    if (ps.pkg != null) {
7996                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7997                            continue;
7998                        }
7999                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8000                                ps.readUserState(userId), userId);
8001                        if (ai != null) {
8002                            rebaseEnabledOverlays(ai, userId);
8003                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8004                        }
8005                    } else {
8006                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8007                        // and already converts to externally visible package name
8008                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8009                                Binder.getCallingUid(), effectiveFlags, userId);
8010                    }
8011                    if (ai != null) {
8012                        list.add(ai);
8013                    }
8014                }
8015            } else {
8016                list = new ArrayList<>(mPackages.size());
8017                for (PackageParser.Package p : mPackages.values()) {
8018                    if (p.mExtras != null) {
8019                        PackageSetting ps = (PackageSetting) p.mExtras;
8020                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8021                            continue;
8022                        }
8023                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8024                                ps.readUserState(userId), userId);
8025                        if (ai != null) {
8026                            rebaseEnabledOverlays(ai, userId);
8027                            ai.packageName = resolveExternalPackageNameLPr(p);
8028                            list.add(ai);
8029                        }
8030                    }
8031                }
8032            }
8033
8034            return new ParceledListSlice<>(list);
8035        }
8036    }
8037
8038    @Override
8039    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8040        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8041            return null;
8042        }
8043        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8044                "getEphemeralApplications");
8045        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8046                true /* requireFullPermission */, false /* checkShell */,
8047                "getEphemeralApplications");
8048        synchronized (mPackages) {
8049            List<InstantAppInfo> instantApps = mInstantAppRegistry
8050                    .getInstantAppsLPr(userId);
8051            if (instantApps != null) {
8052                return new ParceledListSlice<>(instantApps);
8053            }
8054        }
8055        return null;
8056    }
8057
8058    @Override
8059    public boolean isInstantApp(String packageName, int userId) {
8060        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8061                true /* requireFullPermission */, false /* checkShell */,
8062                "isInstantApp");
8063        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8064            return false;
8065        }
8066        int callingUid = Binder.getCallingUid();
8067        if (Process.isIsolated(callingUid)) {
8068            callingUid = mIsolatedOwners.get(callingUid);
8069        }
8070
8071        synchronized (mPackages) {
8072            final PackageSetting ps = mSettings.mPackages.get(packageName);
8073            PackageParser.Package pkg = mPackages.get(packageName);
8074            final boolean returnAllowed =
8075                    ps != null
8076                    && (isCallerSameApp(packageName, callingUid)
8077                            || mContext.checkCallingOrSelfPermission(
8078                                    android.Manifest.permission.ACCESS_INSTANT_APPS)
8079                                            == PERMISSION_GRANTED
8080                            || mInstantAppRegistry.isInstantAccessGranted(
8081                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8082            if (returnAllowed) {
8083                return ps.getInstantApp(userId);
8084            }
8085        }
8086        return false;
8087    }
8088
8089    @Override
8090    public byte[] getInstantAppCookie(String packageName, int userId) {
8091        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8092            return null;
8093        }
8094
8095        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8096                true /* requireFullPermission */, false /* checkShell */,
8097                "getInstantAppCookie");
8098        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8099            return null;
8100        }
8101        synchronized (mPackages) {
8102            return mInstantAppRegistry.getInstantAppCookieLPw(
8103                    packageName, userId);
8104        }
8105    }
8106
8107    @Override
8108    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8109        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8110            return true;
8111        }
8112
8113        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8114                true /* requireFullPermission */, true /* checkShell */,
8115                "setInstantAppCookie");
8116        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8117            return false;
8118        }
8119        synchronized (mPackages) {
8120            return mInstantAppRegistry.setInstantAppCookieLPw(
8121                    packageName, cookie, userId);
8122        }
8123    }
8124
8125    @Override
8126    public Bitmap getInstantAppIcon(String packageName, int userId) {
8127        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8128            return null;
8129        }
8130
8131        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8132                "getInstantAppIcon");
8133
8134        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8135                true /* requireFullPermission */, false /* checkShell */,
8136                "getInstantAppIcon");
8137
8138        synchronized (mPackages) {
8139            return mInstantAppRegistry.getInstantAppIconLPw(
8140                    packageName, userId);
8141        }
8142    }
8143
8144    private boolean isCallerSameApp(String packageName, int uid) {
8145        PackageParser.Package pkg = mPackages.get(packageName);
8146        return pkg != null
8147                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8148    }
8149
8150    @Override
8151    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8152        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8153            return ParceledListSlice.emptyList();
8154        }
8155        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8156    }
8157
8158    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8159        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8160
8161        // reader
8162        synchronized (mPackages) {
8163            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8164            final int userId = UserHandle.getCallingUserId();
8165            while (i.hasNext()) {
8166                final PackageParser.Package p = i.next();
8167                if (p.applicationInfo == null) continue;
8168
8169                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8170                        && !p.applicationInfo.isDirectBootAware();
8171                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8172                        && p.applicationInfo.isDirectBootAware();
8173
8174                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8175                        && (!mSafeMode || isSystemApp(p))
8176                        && (matchesUnaware || matchesAware)) {
8177                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8178                    if (ps != null) {
8179                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8180                                ps.readUserState(userId), userId);
8181                        if (ai != null) {
8182                            rebaseEnabledOverlays(ai, userId);
8183                            finalList.add(ai);
8184                        }
8185                    }
8186                }
8187            }
8188        }
8189
8190        return finalList;
8191    }
8192
8193    @Override
8194    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8195        if (!sUserManager.exists(userId)) return null;
8196        flags = updateFlagsForComponent(flags, userId, name);
8197        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8198        // reader
8199        synchronized (mPackages) {
8200            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8201            PackageSetting ps = provider != null
8202                    ? mSettings.mPackages.get(provider.owner.packageName)
8203                    : null;
8204            if (ps != null) {
8205                final boolean isInstantApp = ps.getInstantApp(userId);
8206                // normal application; filter out instant application provider
8207                if (instantAppPkgName == null && isInstantApp) {
8208                    return null;
8209                }
8210                // instant application; filter out other instant applications
8211                if (instantAppPkgName != null
8212                        && isInstantApp
8213                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8214                    return null;
8215                }
8216                // instant application; filter out non-exposed provider
8217                if (instantAppPkgName != null
8218                        && !isInstantApp
8219                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8220                    return null;
8221                }
8222                // provider not enabled
8223                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8224                    return null;
8225                }
8226                return PackageParser.generateProviderInfo(
8227                        provider, flags, ps.readUserState(userId), userId);
8228            }
8229            return null;
8230        }
8231    }
8232
8233    /**
8234     * @deprecated
8235     */
8236    @Deprecated
8237    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8238        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8239            return;
8240        }
8241        // reader
8242        synchronized (mPackages) {
8243            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8244                    .entrySet().iterator();
8245            final int userId = UserHandle.getCallingUserId();
8246            while (i.hasNext()) {
8247                Map.Entry<String, PackageParser.Provider> entry = i.next();
8248                PackageParser.Provider p = entry.getValue();
8249                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8250
8251                if (ps != null && p.syncable
8252                        && (!mSafeMode || (p.info.applicationInfo.flags
8253                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8254                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8255                            ps.readUserState(userId), userId);
8256                    if (info != null) {
8257                        outNames.add(entry.getKey());
8258                        outInfo.add(info);
8259                    }
8260                }
8261            }
8262        }
8263    }
8264
8265    @Override
8266    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8267            int uid, int flags, String metaDataKey) {
8268        final int userId = processName != null ? UserHandle.getUserId(uid)
8269                : UserHandle.getCallingUserId();
8270        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8271        flags = updateFlagsForComponent(flags, userId, processName);
8272
8273        ArrayList<ProviderInfo> finalList = null;
8274        // reader
8275        synchronized (mPackages) {
8276            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8277            while (i.hasNext()) {
8278                final PackageParser.Provider p = i.next();
8279                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8280                if (ps != null && p.info.authority != null
8281                        && (processName == null
8282                                || (p.info.processName.equals(processName)
8283                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8284                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8285
8286                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8287                    // parameter.
8288                    if (metaDataKey != null
8289                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8290                        continue;
8291                    }
8292
8293                    if (finalList == null) {
8294                        finalList = new ArrayList<ProviderInfo>(3);
8295                    }
8296                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8297                            ps.readUserState(userId), userId);
8298                    if (info != null) {
8299                        finalList.add(info);
8300                    }
8301                }
8302            }
8303        }
8304
8305        if (finalList != null) {
8306            Collections.sort(finalList, mProviderInitOrderSorter);
8307            return new ParceledListSlice<ProviderInfo>(finalList);
8308        }
8309
8310        return ParceledListSlice.emptyList();
8311    }
8312
8313    @Override
8314    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
8315        // reader
8316        synchronized (mPackages) {
8317            final PackageParser.Instrumentation i = mInstrumentation.get(name);
8318            return PackageParser.generateInstrumentationInfo(i, flags);
8319        }
8320    }
8321
8322    @Override
8323    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8324            String targetPackage, int flags) {
8325        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8326    }
8327
8328    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8329            int flags) {
8330        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8331
8332        // reader
8333        synchronized (mPackages) {
8334            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8335            while (i.hasNext()) {
8336                final PackageParser.Instrumentation p = i.next();
8337                if (targetPackage == null
8338                        || targetPackage.equals(p.info.targetPackage)) {
8339                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8340                            flags);
8341                    if (ii != null) {
8342                        finalList.add(ii);
8343                    }
8344                }
8345            }
8346        }
8347
8348        return finalList;
8349    }
8350
8351    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8352        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8353        try {
8354            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8355        } finally {
8356            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8357        }
8358    }
8359
8360    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8361        final File[] files = dir.listFiles();
8362        if (ArrayUtils.isEmpty(files)) {
8363            Log.d(TAG, "No files in app dir " + dir);
8364            return;
8365        }
8366
8367        if (DEBUG_PACKAGE_SCANNING) {
8368            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8369                    + " flags=0x" + Integer.toHexString(parseFlags));
8370        }
8371        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8372                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8373                mParallelPackageParserCallback);
8374
8375        // Submit files for parsing in parallel
8376        int fileCount = 0;
8377        for (File file : files) {
8378            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8379                    && !PackageInstallerService.isStageName(file.getName());
8380            if (!isPackage) {
8381                // Ignore entries which are not packages
8382                continue;
8383            }
8384            parallelPackageParser.submit(file, parseFlags);
8385            fileCount++;
8386        }
8387
8388        // Process results one by one
8389        for (; fileCount > 0; fileCount--) {
8390            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8391            Throwable throwable = parseResult.throwable;
8392            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8393
8394            if (throwable == null) {
8395                // Static shared libraries have synthetic package names
8396                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8397                    renameStaticSharedLibraryPackage(parseResult.pkg);
8398                }
8399                try {
8400                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8401                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8402                                currentTime, null);
8403                    }
8404                } catch (PackageManagerException e) {
8405                    errorCode = e.error;
8406                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8407                }
8408            } else if (throwable instanceof PackageParser.PackageParserException) {
8409                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8410                        throwable;
8411                errorCode = e.error;
8412                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8413            } else {
8414                throw new IllegalStateException("Unexpected exception occurred while parsing "
8415                        + parseResult.scanFile, throwable);
8416            }
8417
8418            // Delete invalid userdata apps
8419            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8420                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8421                logCriticalInfo(Log.WARN,
8422                        "Deleting invalid package at " + parseResult.scanFile);
8423                removeCodePathLI(parseResult.scanFile);
8424            }
8425        }
8426        parallelPackageParser.close();
8427    }
8428
8429    private static File getSettingsProblemFile() {
8430        File dataDir = Environment.getDataDirectory();
8431        File systemDir = new File(dataDir, "system");
8432        File fname = new File(systemDir, "uiderrors.txt");
8433        return fname;
8434    }
8435
8436    static void reportSettingsProblem(int priority, String msg) {
8437        logCriticalInfo(priority, msg);
8438    }
8439
8440    public static void logCriticalInfo(int priority, String msg) {
8441        Slog.println(priority, TAG, msg);
8442        EventLogTags.writePmCriticalInfo(msg);
8443        try {
8444            File fname = getSettingsProblemFile();
8445            FileOutputStream out = new FileOutputStream(fname, true);
8446            PrintWriter pw = new FastPrintWriter(out);
8447            SimpleDateFormat formatter = new SimpleDateFormat();
8448            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8449            pw.println(dateString + ": " + msg);
8450            pw.close();
8451            FileUtils.setPermissions(
8452                    fname.toString(),
8453                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8454                    -1, -1);
8455        } catch (java.io.IOException e) {
8456        }
8457    }
8458
8459    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8460        if (srcFile.isDirectory()) {
8461            final File baseFile = new File(pkg.baseCodePath);
8462            long maxModifiedTime = baseFile.lastModified();
8463            if (pkg.splitCodePaths != null) {
8464                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8465                    final File splitFile = new File(pkg.splitCodePaths[i]);
8466                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8467                }
8468            }
8469            return maxModifiedTime;
8470        }
8471        return srcFile.lastModified();
8472    }
8473
8474    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8475            final int policyFlags) throws PackageManagerException {
8476        // When upgrading from pre-N MR1, verify the package time stamp using the package
8477        // directory and not the APK file.
8478        final long lastModifiedTime = mIsPreNMR1Upgrade
8479                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8480        if (ps != null
8481                && ps.codePath.equals(srcFile)
8482                && ps.timeStamp == lastModifiedTime
8483                && !isCompatSignatureUpdateNeeded(pkg)
8484                && !isRecoverSignatureUpdateNeeded(pkg)) {
8485            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8486            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8487            ArraySet<PublicKey> signingKs;
8488            synchronized (mPackages) {
8489                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8490            }
8491            if (ps.signatures.mSignatures != null
8492                    && ps.signatures.mSignatures.length != 0
8493                    && signingKs != null) {
8494                // Optimization: reuse the existing cached certificates
8495                // if the package appears to be unchanged.
8496                pkg.mSignatures = ps.signatures.mSignatures;
8497                pkg.mSigningKeys = signingKs;
8498                return;
8499            }
8500
8501            Slog.w(TAG, "PackageSetting for " + ps.name
8502                    + " is missing signatures.  Collecting certs again to recover them.");
8503        } else {
8504            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8505        }
8506
8507        try {
8508            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8509            PackageParser.collectCertificates(pkg, policyFlags);
8510        } catch (PackageParserException e) {
8511            throw PackageManagerException.from(e);
8512        } finally {
8513            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8514        }
8515    }
8516
8517    /**
8518     *  Traces a package scan.
8519     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8520     */
8521    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8522            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8523        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8524        try {
8525            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8526        } finally {
8527            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8528        }
8529    }
8530
8531    /**
8532     *  Scans a package and returns the newly parsed package.
8533     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8534     */
8535    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8536            long currentTime, UserHandle user) throws PackageManagerException {
8537        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8538        PackageParser pp = new PackageParser();
8539        pp.setSeparateProcesses(mSeparateProcesses);
8540        pp.setOnlyCoreApps(mOnlyCore);
8541        pp.setDisplayMetrics(mMetrics);
8542        pp.setCallback(mPackageParserCallback);
8543
8544        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8545            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8546        }
8547
8548        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8549        final PackageParser.Package pkg;
8550        try {
8551            pkg = pp.parsePackage(scanFile, parseFlags);
8552        } catch (PackageParserException e) {
8553            throw PackageManagerException.from(e);
8554        } finally {
8555            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8556        }
8557
8558        // Static shared libraries have synthetic package names
8559        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8560            renameStaticSharedLibraryPackage(pkg);
8561        }
8562
8563        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8564    }
8565
8566    /**
8567     *  Scans a package and returns the newly parsed package.
8568     *  @throws PackageManagerException on a parse error.
8569     */
8570    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8571            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8572            throws PackageManagerException {
8573        // If the package has children and this is the first dive in the function
8574        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8575        // packages (parent and children) would be successfully scanned before the
8576        // actual scan since scanning mutates internal state and we want to atomically
8577        // install the package and its children.
8578        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8579            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8580                scanFlags |= SCAN_CHECK_ONLY;
8581            }
8582        } else {
8583            scanFlags &= ~SCAN_CHECK_ONLY;
8584        }
8585
8586        // Scan the parent
8587        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8588                scanFlags, currentTime, user);
8589
8590        // Scan the children
8591        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8592        for (int i = 0; i < childCount; i++) {
8593            PackageParser.Package childPackage = pkg.childPackages.get(i);
8594            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8595                    currentTime, user);
8596        }
8597
8598
8599        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8600            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8601        }
8602
8603        return scannedPkg;
8604    }
8605
8606    /**
8607     *  Scans a package and returns the newly parsed package.
8608     *  @throws PackageManagerException on a parse error.
8609     */
8610    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8611            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8612            throws PackageManagerException {
8613        PackageSetting ps = null;
8614        PackageSetting updatedPkg;
8615        // reader
8616        synchronized (mPackages) {
8617            // Look to see if we already know about this package.
8618            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8619            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8620                // This package has been renamed to its original name.  Let's
8621                // use that.
8622                ps = mSettings.getPackageLPr(oldName);
8623            }
8624            // If there was no original package, see one for the real package name.
8625            if (ps == null) {
8626                ps = mSettings.getPackageLPr(pkg.packageName);
8627            }
8628            // Check to see if this package could be hiding/updating a system
8629            // package.  Must look for it either under the original or real
8630            // package name depending on our state.
8631            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8632            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8633
8634            // If this is a package we don't know about on the system partition, we
8635            // may need to remove disabled child packages on the system partition
8636            // or may need to not add child packages if the parent apk is updated
8637            // on the data partition and no longer defines this child package.
8638            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8639                // If this is a parent package for an updated system app and this system
8640                // app got an OTA update which no longer defines some of the child packages
8641                // we have to prune them from the disabled system packages.
8642                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8643                if (disabledPs != null) {
8644                    final int scannedChildCount = (pkg.childPackages != null)
8645                            ? pkg.childPackages.size() : 0;
8646                    final int disabledChildCount = disabledPs.childPackageNames != null
8647                            ? disabledPs.childPackageNames.size() : 0;
8648                    for (int i = 0; i < disabledChildCount; i++) {
8649                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8650                        boolean disabledPackageAvailable = false;
8651                        for (int j = 0; j < scannedChildCount; j++) {
8652                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8653                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8654                                disabledPackageAvailable = true;
8655                                break;
8656                            }
8657                         }
8658                         if (!disabledPackageAvailable) {
8659                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8660                         }
8661                    }
8662                }
8663            }
8664        }
8665
8666        boolean updatedPkgBetter = false;
8667        // First check if this is a system package that may involve an update
8668        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8669            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8670            // it needs to drop FLAG_PRIVILEGED.
8671            if (locationIsPrivileged(scanFile)) {
8672                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8673            } else {
8674                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8675            }
8676
8677            if (ps != null && !ps.codePath.equals(scanFile)) {
8678                // The path has changed from what was last scanned...  check the
8679                // version of the new path against what we have stored to determine
8680                // what to do.
8681                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8682                if (pkg.mVersionCode <= ps.versionCode) {
8683                    // The system package has been updated and the code path does not match
8684                    // Ignore entry. Skip it.
8685                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8686                            + " ignored: updated version " + ps.versionCode
8687                            + " better than this " + pkg.mVersionCode);
8688                    if (!updatedPkg.codePath.equals(scanFile)) {
8689                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8690                                + ps.name + " changing from " + updatedPkg.codePathString
8691                                + " to " + scanFile);
8692                        updatedPkg.codePath = scanFile;
8693                        updatedPkg.codePathString = scanFile.toString();
8694                        updatedPkg.resourcePath = scanFile;
8695                        updatedPkg.resourcePathString = scanFile.toString();
8696                    }
8697                    updatedPkg.pkg = pkg;
8698                    updatedPkg.versionCode = pkg.mVersionCode;
8699
8700                    // Update the disabled system child packages to point to the package too.
8701                    final int childCount = updatedPkg.childPackageNames != null
8702                            ? updatedPkg.childPackageNames.size() : 0;
8703                    for (int i = 0; i < childCount; i++) {
8704                        String childPackageName = updatedPkg.childPackageNames.get(i);
8705                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8706                                childPackageName);
8707                        if (updatedChildPkg != null) {
8708                            updatedChildPkg.pkg = pkg;
8709                            updatedChildPkg.versionCode = pkg.mVersionCode;
8710                        }
8711                    }
8712
8713                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8714                            + scanFile + " ignored: updated version " + ps.versionCode
8715                            + " better than this " + pkg.mVersionCode);
8716                } else {
8717                    // The current app on the system partition is better than
8718                    // what we have updated to on the data partition; switch
8719                    // back to the system partition version.
8720                    // At this point, its safely assumed that package installation for
8721                    // apps in system partition will go through. If not there won't be a working
8722                    // version of the app
8723                    // writer
8724                    synchronized (mPackages) {
8725                        // Just remove the loaded entries from package lists.
8726                        mPackages.remove(ps.name);
8727                    }
8728
8729                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8730                            + " reverting from " + ps.codePathString
8731                            + ": new version " + pkg.mVersionCode
8732                            + " better than installed " + ps.versionCode);
8733
8734                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8735                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8736                    synchronized (mInstallLock) {
8737                        args.cleanUpResourcesLI();
8738                    }
8739                    synchronized (mPackages) {
8740                        mSettings.enableSystemPackageLPw(ps.name);
8741                    }
8742                    updatedPkgBetter = true;
8743                }
8744            }
8745        }
8746
8747        if (updatedPkg != null) {
8748            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8749            // initially
8750            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8751
8752            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8753            // flag set initially
8754            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8755                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8756            }
8757        }
8758
8759        // Verify certificates against what was last scanned
8760        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8761
8762        /*
8763         * A new system app appeared, but we already had a non-system one of the
8764         * same name installed earlier.
8765         */
8766        boolean shouldHideSystemApp = false;
8767        if (updatedPkg == null && ps != null
8768                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8769            /*
8770             * Check to make sure the signatures match first. If they don't,
8771             * wipe the installed application and its data.
8772             */
8773            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
8774                    != PackageManager.SIGNATURE_MATCH) {
8775                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
8776                        + " signatures don't match existing userdata copy; removing");
8777                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8778                        "scanPackageInternalLI")) {
8779                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8780                }
8781                ps = null;
8782            } else {
8783                /*
8784                 * If the newly-added system app is an older version than the
8785                 * already installed version, hide it. It will be scanned later
8786                 * and re-added like an update.
8787                 */
8788                if (pkg.mVersionCode <= ps.versionCode) {
8789                    shouldHideSystemApp = true;
8790                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8791                            + " but new version " + pkg.mVersionCode + " better than installed "
8792                            + ps.versionCode + "; hiding system");
8793                } else {
8794                    /*
8795                     * The newly found system app is a newer version that the
8796                     * one previously installed. Simply remove the
8797                     * already-installed application and replace it with our own
8798                     * while keeping the application data.
8799                     */
8800                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8801                            + " reverting from " + ps.codePathString + ": new version "
8802                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8803                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8804                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8805                    synchronized (mInstallLock) {
8806                        args.cleanUpResourcesLI();
8807                    }
8808                }
8809            }
8810        }
8811
8812        // The apk is forward locked (not public) if its code and resources
8813        // are kept in different files. (except for app in either system or
8814        // vendor path).
8815        // TODO grab this value from PackageSettings
8816        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8817            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8818                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8819            }
8820        }
8821
8822        // TODO: extend to support forward-locked splits
8823        String resourcePath = null;
8824        String baseResourcePath = null;
8825        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
8826            if (ps != null && ps.resourcePathString != null) {
8827                resourcePath = ps.resourcePathString;
8828                baseResourcePath = ps.resourcePathString;
8829            } else {
8830                // Should not happen at all. Just log an error.
8831                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8832            }
8833        } else {
8834            resourcePath = pkg.codePath;
8835            baseResourcePath = pkg.baseCodePath;
8836        }
8837
8838        // Set application objects path explicitly.
8839        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8840        pkg.setApplicationInfoCodePath(pkg.codePath);
8841        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8842        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8843        pkg.setApplicationInfoResourcePath(resourcePath);
8844        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8845        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8846
8847        final int userId = ((user == null) ? 0 : user.getIdentifier());
8848        if (ps != null && ps.getInstantApp(userId)) {
8849            scanFlags |= SCAN_AS_INSTANT_APP;
8850        }
8851
8852        // Note that we invoke the following method only if we are about to unpack an application
8853        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8854                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8855
8856        /*
8857         * If the system app should be overridden by a previously installed
8858         * data, hide the system app now and let the /data/app scan pick it up
8859         * again.
8860         */
8861        if (shouldHideSystemApp) {
8862            synchronized (mPackages) {
8863                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8864            }
8865        }
8866
8867        return scannedPkg;
8868    }
8869
8870    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8871        // Derive the new package synthetic package name
8872        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8873                + pkg.staticSharedLibVersion);
8874    }
8875
8876    private static String fixProcessName(String defProcessName,
8877            String processName) {
8878        if (processName == null) {
8879            return defProcessName;
8880        }
8881        return processName;
8882    }
8883
8884    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8885            throws PackageManagerException {
8886        if (pkgSetting.signatures.mSignatures != null) {
8887            // Already existing package. Make sure signatures match
8888            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8889                    == PackageManager.SIGNATURE_MATCH;
8890            if (!match) {
8891                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8892                        == PackageManager.SIGNATURE_MATCH;
8893            }
8894            if (!match) {
8895                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8896                        == PackageManager.SIGNATURE_MATCH;
8897            }
8898            if (!match) {
8899                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8900                        + pkg.packageName + " signatures do not match the "
8901                        + "previously installed version; ignoring!");
8902            }
8903        }
8904
8905        // Check for shared user signatures
8906        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8907            // Already existing package. Make sure signatures match
8908            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8909                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8910            if (!match) {
8911                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8912                        == PackageManager.SIGNATURE_MATCH;
8913            }
8914            if (!match) {
8915                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8916                        == PackageManager.SIGNATURE_MATCH;
8917            }
8918            if (!match) {
8919                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8920                        "Package " + pkg.packageName
8921                        + " has no signatures that match those in shared user "
8922                        + pkgSetting.sharedUser.name + "; ignoring!");
8923            }
8924        }
8925    }
8926
8927    /**
8928     * Enforces that only the system UID or root's UID can call a method exposed
8929     * via Binder.
8930     *
8931     * @param message used as message if SecurityException is thrown
8932     * @throws SecurityException if the caller is not system or root
8933     */
8934    private static final void enforceSystemOrRoot(String message) {
8935        final int uid = Binder.getCallingUid();
8936        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8937            throw new SecurityException(message);
8938        }
8939    }
8940
8941    @Override
8942    public void performFstrimIfNeeded() {
8943        enforceSystemOrRoot("Only the system can request fstrim");
8944
8945        // Before everything else, see whether we need to fstrim.
8946        try {
8947            IStorageManager sm = PackageHelper.getStorageManager();
8948            if (sm != null) {
8949                boolean doTrim = false;
8950                final long interval = android.provider.Settings.Global.getLong(
8951                        mContext.getContentResolver(),
8952                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8953                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8954                if (interval > 0) {
8955                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8956                    if (timeSinceLast > interval) {
8957                        doTrim = true;
8958                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8959                                + "; running immediately");
8960                    }
8961                }
8962                if (doTrim) {
8963                    final boolean dexOptDialogShown;
8964                    synchronized (mPackages) {
8965                        dexOptDialogShown = mDexOptDialogShown;
8966                    }
8967                    if (!isFirstBoot() && dexOptDialogShown) {
8968                        try {
8969                            ActivityManager.getService().showBootMessage(
8970                                    mContext.getResources().getString(
8971                                            R.string.android_upgrading_fstrim), true);
8972                        } catch (RemoteException e) {
8973                        }
8974                    }
8975                    sm.runMaintenance();
8976                }
8977            } else {
8978                Slog.e(TAG, "storageManager service unavailable!");
8979            }
8980        } catch (RemoteException e) {
8981            // Can't happen; StorageManagerService is local
8982        }
8983    }
8984
8985    @Override
8986    public void updatePackagesIfNeeded() {
8987        enforceSystemOrRoot("Only the system can request package update");
8988
8989        // We need to re-extract after an OTA.
8990        boolean causeUpgrade = isUpgrade();
8991
8992        // First boot or factory reset.
8993        // Note: we also handle devices that are upgrading to N right now as if it is their
8994        //       first boot, as they do not have profile data.
8995        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8996
8997        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8998        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8999
9000        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9001            return;
9002        }
9003
9004        List<PackageParser.Package> pkgs;
9005        synchronized (mPackages) {
9006            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9007        }
9008
9009        final long startTime = System.nanoTime();
9010        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9011                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
9012
9013        final int elapsedTimeSeconds =
9014                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9015
9016        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9017        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9018        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9019        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9020        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9021    }
9022
9023    /*
9024     * Return the prebuilt profile path given a package base code path.
9025     */
9026    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9027        return pkg.baseCodePath + ".prof";
9028    }
9029
9030    /**
9031     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9032     * containing statistics about the invocation. The array consists of three elements,
9033     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9034     * and {@code numberOfPackagesFailed}.
9035     */
9036    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9037            String compilerFilter) {
9038
9039        int numberOfPackagesVisited = 0;
9040        int numberOfPackagesOptimized = 0;
9041        int numberOfPackagesSkipped = 0;
9042        int numberOfPackagesFailed = 0;
9043        final int numberOfPackagesToDexopt = pkgs.size();
9044
9045        for (PackageParser.Package pkg : pkgs) {
9046            numberOfPackagesVisited++;
9047
9048            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
9049                // Copy over initial preopt profiles since we won't get any JIT samples for methods
9050                // that are already compiled.
9051                File profileFile = new File(getPrebuildProfilePath(pkg));
9052                // Copy profile if it exists.
9053                if (profileFile.exists()) {
9054                    try {
9055                        // We could also do this lazily before calling dexopt in
9056                        // PackageDexOptimizer to prevent this happening on first boot. The issue
9057                        // is that we don't have a good way to say "do this only once".
9058                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9059                                pkg.applicationInfo.uid, pkg.packageName)) {
9060                            Log.e(TAG, "Installer failed to copy system profile!");
9061                        }
9062                    } catch (Exception e) {
9063                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9064                                e);
9065                    }
9066                }
9067            }
9068
9069            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9070                if (DEBUG_DEXOPT) {
9071                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9072                }
9073                numberOfPackagesSkipped++;
9074                continue;
9075            }
9076
9077            if (DEBUG_DEXOPT) {
9078                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9079                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9080            }
9081
9082            if (showDialog) {
9083                try {
9084                    ActivityManager.getService().showBootMessage(
9085                            mContext.getResources().getString(R.string.android_upgrading_apk,
9086                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9087                } catch (RemoteException e) {
9088                }
9089                synchronized (mPackages) {
9090                    mDexOptDialogShown = true;
9091                }
9092            }
9093
9094            // If the OTA updates a system app which was previously preopted to a non-preopted state
9095            // the app might end up being verified at runtime. That's because by default the apps
9096            // are verify-profile but for preopted apps there's no profile.
9097            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9098            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9099            // filter (by default 'quicken').
9100            // Note that at this stage unused apps are already filtered.
9101            if (isSystemApp(pkg) &&
9102                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9103                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9104                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9105            }
9106
9107            // checkProfiles is false to avoid merging profiles during boot which
9108            // might interfere with background compilation (b/28612421).
9109            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9110            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9111            // trade-off worth doing to save boot time work.
9112            int dexOptStatus = performDexOptTraced(pkg.packageName,
9113                    false /* checkProfiles */,
9114                    compilerFilter,
9115                    false /* force */);
9116            switch (dexOptStatus) {
9117                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9118                    numberOfPackagesOptimized++;
9119                    break;
9120                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9121                    numberOfPackagesSkipped++;
9122                    break;
9123                case PackageDexOptimizer.DEX_OPT_FAILED:
9124                    numberOfPackagesFailed++;
9125                    break;
9126                default:
9127                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
9128                    break;
9129            }
9130        }
9131
9132        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9133                numberOfPackagesFailed };
9134    }
9135
9136    @Override
9137    public void notifyPackageUse(String packageName, int reason) {
9138        synchronized (mPackages) {
9139            if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
9140                return;
9141            }
9142            final PackageParser.Package p = mPackages.get(packageName);
9143            if (p == null) {
9144                return;
9145            }
9146            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9147        }
9148    }
9149
9150    @Override
9151    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
9152        int userId = UserHandle.getCallingUserId();
9153        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9154        if (ai == null) {
9155            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9156                + loadingPackageName + ", user=" + userId);
9157            return;
9158        }
9159        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
9160    }
9161
9162    @Override
9163    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9164            IDexModuleRegisterCallback callback) {
9165        int userId = UserHandle.getCallingUserId();
9166        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9167        DexManager.RegisterDexModuleResult result;
9168        if (ai == null) {
9169            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9170                     " calling user. package=" + packageName + ", user=" + userId);
9171            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9172        } else {
9173            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9174        }
9175
9176        if (callback != null) {
9177            mHandler.post(() -> {
9178                try {
9179                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9180                } catch (RemoteException e) {
9181                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9182                }
9183            });
9184        }
9185    }
9186
9187    @Override
9188    public boolean performDexOpt(String packageName,
9189            boolean checkProfiles, int compileReason, boolean force) {
9190        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
9191                getCompilerFilterForReason(compileReason), force);
9192        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9193    }
9194
9195    @Override
9196    public boolean performDexOptMode(String packageName,
9197            boolean checkProfiles, String targetCompilerFilter, boolean force) {
9198        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9199            return false;
9200        }
9201        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
9202                targetCompilerFilter, force);
9203        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9204    }
9205
9206    private int performDexOptTraced(String packageName,
9207                boolean checkProfiles, String targetCompilerFilter, boolean force) {
9208        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9209        try {
9210            return performDexOptInternal(packageName, checkProfiles,
9211                    targetCompilerFilter, force);
9212        } finally {
9213            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9214        }
9215    }
9216
9217    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9218    // if the package can now be considered up to date for the given filter.
9219    private int performDexOptInternal(String packageName,
9220                boolean checkProfiles, String targetCompilerFilter, boolean force) {
9221        PackageParser.Package p;
9222        synchronized (mPackages) {
9223            p = mPackages.get(packageName);
9224            if (p == null) {
9225                // Package could not be found. Report failure.
9226                return PackageDexOptimizer.DEX_OPT_FAILED;
9227            }
9228            mPackageUsage.maybeWriteAsync(mPackages);
9229            mCompilerStats.maybeWriteAsync();
9230        }
9231        long callingId = Binder.clearCallingIdentity();
9232        try {
9233            synchronized (mInstallLock) {
9234                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
9235                        targetCompilerFilter, force);
9236            }
9237        } finally {
9238            Binder.restoreCallingIdentity(callingId);
9239        }
9240    }
9241
9242    public ArraySet<String> getOptimizablePackages() {
9243        ArraySet<String> pkgs = new ArraySet<String>();
9244        synchronized (mPackages) {
9245            for (PackageParser.Package p : mPackages.values()) {
9246                if (PackageDexOptimizer.canOptimizePackage(p)) {
9247                    pkgs.add(p.packageName);
9248                }
9249            }
9250        }
9251        return pkgs;
9252    }
9253
9254    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9255            boolean checkProfiles, String targetCompilerFilter,
9256            boolean force) {
9257        // Select the dex optimizer based on the force parameter.
9258        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9259        //       allocate an object here.
9260        PackageDexOptimizer pdo = force
9261                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9262                : mPackageDexOptimizer;
9263
9264        // Dexopt all dependencies first. Note: we ignore the return value and march on
9265        // on errors.
9266        // Note that we are going to call performDexOpt on those libraries as many times as
9267        // they are referenced in packages. When we do a batch of performDexOpt (for example
9268        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9269        // and the first package that uses the library will dexopt it. The
9270        // others will see that the compiled code for the library is up to date.
9271        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9272        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9273        if (!deps.isEmpty()) {
9274            for (PackageParser.Package depPackage : deps) {
9275                // TODO: Analyze and investigate if we (should) profile libraries.
9276                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9277                        false /* checkProfiles */,
9278                        targetCompilerFilter,
9279                        getOrCreateCompilerPackageStats(depPackage),
9280                        true /* isUsedByOtherApps */);
9281            }
9282        }
9283        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
9284                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
9285                mDexManager.isUsedByOtherApps(p.packageName));
9286    }
9287
9288    // Performs dexopt on the used secondary dex files belonging to the given package.
9289    // Returns true if all dex files were process successfully (which could mean either dexopt or
9290    // skip). Returns false if any of the files caused errors.
9291    @Override
9292    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9293            boolean force) {
9294        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9295            return false;
9296        }
9297        mDexManager.reconcileSecondaryDexFiles(packageName);
9298        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
9299    }
9300
9301    public boolean performDexOptSecondary(String packageName, int compileReason,
9302            boolean force) {
9303        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
9304    }
9305
9306    /**
9307     * Reconcile the information we have about the secondary dex files belonging to
9308     * {@code packagName} and the actual dex files. For all dex files that were
9309     * deleted, update the internal records and delete the generated oat files.
9310     */
9311    @Override
9312    public void reconcileSecondaryDexFiles(String packageName) {
9313        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9314            return;
9315        }
9316        mDexManager.reconcileSecondaryDexFiles(packageName);
9317    }
9318
9319    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9320    // a reference there.
9321    /*package*/ DexManager getDexManager() {
9322        return mDexManager;
9323    }
9324
9325    /**
9326     * Execute the background dexopt job immediately.
9327     */
9328    @Override
9329    public boolean runBackgroundDexoptJob() {
9330        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9331            return false;
9332        }
9333        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9334    }
9335
9336    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9337        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9338                || p.usesStaticLibraries != null) {
9339            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9340            Set<String> collectedNames = new HashSet<>();
9341            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9342
9343            retValue.remove(p);
9344
9345            return retValue;
9346        } else {
9347            return Collections.emptyList();
9348        }
9349    }
9350
9351    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9352            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9353        if (!collectedNames.contains(p.packageName)) {
9354            collectedNames.add(p.packageName);
9355            collected.add(p);
9356
9357            if (p.usesLibraries != null) {
9358                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9359                        null, collected, collectedNames);
9360            }
9361            if (p.usesOptionalLibraries != null) {
9362                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9363                        null, collected, collectedNames);
9364            }
9365            if (p.usesStaticLibraries != null) {
9366                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9367                        p.usesStaticLibrariesVersions, collected, collectedNames);
9368            }
9369        }
9370    }
9371
9372    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9373            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9374        final int libNameCount = libs.size();
9375        for (int i = 0; i < libNameCount; i++) {
9376            String libName = libs.get(i);
9377            int version = (versions != null && versions.length == libNameCount)
9378                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9379            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9380            if (libPkg != null) {
9381                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9382            }
9383        }
9384    }
9385
9386    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9387        synchronized (mPackages) {
9388            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9389            if (libEntry != null) {
9390                return mPackages.get(libEntry.apk);
9391            }
9392            return null;
9393        }
9394    }
9395
9396    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9397        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9398        if (versionedLib == null) {
9399            return null;
9400        }
9401        return versionedLib.get(version);
9402    }
9403
9404    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9405        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9406                pkg.staticSharedLibName);
9407        if (versionedLib == null) {
9408            return null;
9409        }
9410        int previousLibVersion = -1;
9411        final int versionCount = versionedLib.size();
9412        for (int i = 0; i < versionCount; i++) {
9413            final int libVersion = versionedLib.keyAt(i);
9414            if (libVersion < pkg.staticSharedLibVersion) {
9415                previousLibVersion = Math.max(previousLibVersion, libVersion);
9416            }
9417        }
9418        if (previousLibVersion >= 0) {
9419            return versionedLib.get(previousLibVersion);
9420        }
9421        return null;
9422    }
9423
9424    public void shutdown() {
9425        mPackageUsage.writeNow(mPackages);
9426        mCompilerStats.writeNow();
9427    }
9428
9429    @Override
9430    public void dumpProfiles(String packageName) {
9431        PackageParser.Package pkg;
9432        synchronized (mPackages) {
9433            pkg = mPackages.get(packageName);
9434            if (pkg == null) {
9435                throw new IllegalArgumentException("Unknown package: " + packageName);
9436            }
9437        }
9438        /* Only the shell, root, or the app user should be able to dump profiles. */
9439        int callingUid = Binder.getCallingUid();
9440        if (callingUid != Process.SHELL_UID &&
9441            callingUid != Process.ROOT_UID &&
9442            callingUid != pkg.applicationInfo.uid) {
9443            throw new SecurityException("dumpProfiles");
9444        }
9445
9446        synchronized (mInstallLock) {
9447            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9448            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9449            try {
9450                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9451                String codePaths = TextUtils.join(";", allCodePaths);
9452                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9453            } catch (InstallerException e) {
9454                Slog.w(TAG, "Failed to dump profiles", e);
9455            }
9456            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9457        }
9458    }
9459
9460    @Override
9461    public void forceDexOpt(String packageName) {
9462        enforceSystemOrRoot("forceDexOpt");
9463
9464        PackageParser.Package pkg;
9465        synchronized (mPackages) {
9466            pkg = mPackages.get(packageName);
9467            if (pkg == null) {
9468                throw new IllegalArgumentException("Unknown package: " + packageName);
9469            }
9470        }
9471
9472        synchronized (mInstallLock) {
9473            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9474
9475            // Whoever is calling forceDexOpt wants a compiled package.
9476            // Don't use profiles since that may cause compilation to be skipped.
9477            final int res = performDexOptInternalWithDependenciesLI(pkg,
9478                    false /* checkProfiles */, getDefaultCompilerFilter(),
9479                    true /* force */);
9480
9481            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9482            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9483                throw new IllegalStateException("Failed to dexopt: " + res);
9484            }
9485        }
9486    }
9487
9488    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9489        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9490            Slog.w(TAG, "Unable to update from " + oldPkg.name
9491                    + " to " + newPkg.packageName
9492                    + ": old package not in system partition");
9493            return false;
9494        } else if (mPackages.get(oldPkg.name) != null) {
9495            Slog.w(TAG, "Unable to update from " + oldPkg.name
9496                    + " to " + newPkg.packageName
9497                    + ": old package still exists");
9498            return false;
9499        }
9500        return true;
9501    }
9502
9503    void removeCodePathLI(File codePath) {
9504        if (codePath.isDirectory()) {
9505            try {
9506                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9507            } catch (InstallerException e) {
9508                Slog.w(TAG, "Failed to remove code path", e);
9509            }
9510        } else {
9511            codePath.delete();
9512        }
9513    }
9514
9515    private int[] resolveUserIds(int userId) {
9516        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9517    }
9518
9519    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9520        if (pkg == null) {
9521            Slog.wtf(TAG, "Package was null!", new Throwable());
9522            return;
9523        }
9524        clearAppDataLeafLIF(pkg, userId, flags);
9525        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9526        for (int i = 0; i < childCount; i++) {
9527            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9528        }
9529    }
9530
9531    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9532        final PackageSetting ps;
9533        synchronized (mPackages) {
9534            ps = mSettings.mPackages.get(pkg.packageName);
9535        }
9536        for (int realUserId : resolveUserIds(userId)) {
9537            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9538            try {
9539                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9540                        ceDataInode);
9541            } catch (InstallerException e) {
9542                Slog.w(TAG, String.valueOf(e));
9543            }
9544        }
9545    }
9546
9547    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9548        if (pkg == null) {
9549            Slog.wtf(TAG, "Package was null!", new Throwable());
9550            return;
9551        }
9552        destroyAppDataLeafLIF(pkg, userId, flags);
9553        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9554        for (int i = 0; i < childCount; i++) {
9555            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9556        }
9557    }
9558
9559    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9560        final PackageSetting ps;
9561        synchronized (mPackages) {
9562            ps = mSettings.mPackages.get(pkg.packageName);
9563        }
9564        for (int realUserId : resolveUserIds(userId)) {
9565            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9566            try {
9567                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9568                        ceDataInode);
9569            } catch (InstallerException e) {
9570                Slog.w(TAG, String.valueOf(e));
9571            }
9572            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9573        }
9574    }
9575
9576    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9577        if (pkg == null) {
9578            Slog.wtf(TAG, "Package was null!", new Throwable());
9579            return;
9580        }
9581        destroyAppProfilesLeafLIF(pkg);
9582        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9583        for (int i = 0; i < childCount; i++) {
9584            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9585        }
9586    }
9587
9588    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9589        try {
9590            mInstaller.destroyAppProfiles(pkg.packageName);
9591        } catch (InstallerException e) {
9592            Slog.w(TAG, String.valueOf(e));
9593        }
9594    }
9595
9596    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9597        if (pkg == null) {
9598            Slog.wtf(TAG, "Package was null!", new Throwable());
9599            return;
9600        }
9601        clearAppProfilesLeafLIF(pkg);
9602        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9603        for (int i = 0; i < childCount; i++) {
9604            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9605        }
9606    }
9607
9608    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9609        try {
9610            mInstaller.clearAppProfiles(pkg.packageName);
9611        } catch (InstallerException e) {
9612            Slog.w(TAG, String.valueOf(e));
9613        }
9614    }
9615
9616    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9617            long lastUpdateTime) {
9618        // Set parent install/update time
9619        PackageSetting ps = (PackageSetting) pkg.mExtras;
9620        if (ps != null) {
9621            ps.firstInstallTime = firstInstallTime;
9622            ps.lastUpdateTime = lastUpdateTime;
9623        }
9624        // Set children install/update time
9625        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9626        for (int i = 0; i < childCount; i++) {
9627            PackageParser.Package childPkg = pkg.childPackages.get(i);
9628            ps = (PackageSetting) childPkg.mExtras;
9629            if (ps != null) {
9630                ps.firstInstallTime = firstInstallTime;
9631                ps.lastUpdateTime = lastUpdateTime;
9632            }
9633        }
9634    }
9635
9636    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9637            PackageParser.Package changingLib) {
9638        if (file.path != null) {
9639            usesLibraryFiles.add(file.path);
9640            return;
9641        }
9642        PackageParser.Package p = mPackages.get(file.apk);
9643        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9644            // If we are doing this while in the middle of updating a library apk,
9645            // then we need to make sure to use that new apk for determining the
9646            // dependencies here.  (We haven't yet finished committing the new apk
9647            // to the package manager state.)
9648            if (p == null || p.packageName.equals(changingLib.packageName)) {
9649                p = changingLib;
9650            }
9651        }
9652        if (p != null) {
9653            usesLibraryFiles.addAll(p.getAllCodePaths());
9654            if (p.usesLibraryFiles != null) {
9655                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9656            }
9657        }
9658    }
9659
9660    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9661            PackageParser.Package changingLib) throws PackageManagerException {
9662        if (pkg == null) {
9663            return;
9664        }
9665        ArraySet<String> usesLibraryFiles = null;
9666        if (pkg.usesLibraries != null) {
9667            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9668                    null, null, pkg.packageName, changingLib, true, null);
9669        }
9670        if (pkg.usesStaticLibraries != null) {
9671            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9672                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9673                    pkg.packageName, changingLib, true, usesLibraryFiles);
9674        }
9675        if (pkg.usesOptionalLibraries != null) {
9676            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9677                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
9678        }
9679        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9680            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9681        } else {
9682            pkg.usesLibraryFiles = null;
9683        }
9684    }
9685
9686    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9687            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
9688            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9689            boolean required, @Nullable ArraySet<String> outUsedLibraries)
9690            throws PackageManagerException {
9691        final int libCount = requestedLibraries.size();
9692        for (int i = 0; i < libCount; i++) {
9693            final String libName = requestedLibraries.get(i);
9694            final int libVersion = requiredVersions != null ? requiredVersions[i]
9695                    : SharedLibraryInfo.VERSION_UNDEFINED;
9696            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9697            if (libEntry == null) {
9698                if (required) {
9699                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9700                            "Package " + packageName + " requires unavailable shared library "
9701                                    + libName + "; failing!");
9702                } else if (DEBUG_SHARED_LIBRARIES) {
9703                    Slog.i(TAG, "Package " + packageName
9704                            + " desires unavailable shared library "
9705                            + libName + "; ignoring!");
9706                }
9707            } else {
9708                if (requiredVersions != null && requiredCertDigests != null) {
9709                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9710                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9711                            "Package " + packageName + " requires unavailable static shared"
9712                                    + " library " + libName + " version "
9713                                    + libEntry.info.getVersion() + "; failing!");
9714                    }
9715
9716                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9717                    if (libPkg == null) {
9718                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9719                                "Package " + packageName + " requires unavailable static shared"
9720                                        + " library; failing!");
9721                    }
9722
9723                    String expectedCertDigest = requiredCertDigests[i];
9724                    String libCertDigest = PackageUtils.computeCertSha256Digest(
9725                                libPkg.mSignatures[0]);
9726                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
9727                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9728                                "Package " + packageName + " requires differently signed" +
9729                                        " static shared library; failing!");
9730                    }
9731                }
9732
9733                if (outUsedLibraries == null) {
9734                    outUsedLibraries = new ArraySet<>();
9735                }
9736                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9737            }
9738        }
9739        return outUsedLibraries;
9740    }
9741
9742    private static boolean hasString(List<String> list, List<String> which) {
9743        if (list == null) {
9744            return false;
9745        }
9746        for (int i=list.size()-1; i>=0; i--) {
9747            for (int j=which.size()-1; j>=0; j--) {
9748                if (which.get(j).equals(list.get(i))) {
9749                    return true;
9750                }
9751            }
9752        }
9753        return false;
9754    }
9755
9756    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9757            PackageParser.Package changingPkg) {
9758        ArrayList<PackageParser.Package> res = null;
9759        for (PackageParser.Package pkg : mPackages.values()) {
9760            if (changingPkg != null
9761                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9762                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9763                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9764                            changingPkg.staticSharedLibName)) {
9765                return null;
9766            }
9767            if (res == null) {
9768                res = new ArrayList<>();
9769            }
9770            res.add(pkg);
9771            try {
9772                updateSharedLibrariesLPr(pkg, changingPkg);
9773            } catch (PackageManagerException e) {
9774                // If a system app update or an app and a required lib missing we
9775                // delete the package and for updated system apps keep the data as
9776                // it is better for the user to reinstall than to be in an limbo
9777                // state. Also libs disappearing under an app should never happen
9778                // - just in case.
9779                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
9780                    final int flags = pkg.isUpdatedSystemApp()
9781                            ? PackageManager.DELETE_KEEP_DATA : 0;
9782                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9783                            flags , null, true, null);
9784                }
9785                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9786            }
9787        }
9788        return res;
9789    }
9790
9791    /**
9792     * Derive the value of the {@code cpuAbiOverride} based on the provided
9793     * value and an optional stored value from the package settings.
9794     */
9795    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
9796        String cpuAbiOverride = null;
9797
9798        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
9799            cpuAbiOverride = null;
9800        } else if (abiOverride != null) {
9801            cpuAbiOverride = abiOverride;
9802        } else if (settings != null) {
9803            cpuAbiOverride = settings.cpuAbiOverrideString;
9804        }
9805
9806        return cpuAbiOverride;
9807    }
9808
9809    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9810            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9811                    throws PackageManagerException {
9812        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9813        // If the package has children and this is the first dive in the function
9814        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9815        // whether all packages (parent and children) would be successfully scanned
9816        // before the actual scan since scanning mutates internal state and we want
9817        // to atomically install the package and its children.
9818        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9819            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9820                scanFlags |= SCAN_CHECK_ONLY;
9821            }
9822        } else {
9823            scanFlags &= ~SCAN_CHECK_ONLY;
9824        }
9825
9826        final PackageParser.Package scannedPkg;
9827        try {
9828            // Scan the parent
9829            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
9830            // Scan the children
9831            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9832            for (int i = 0; i < childCount; i++) {
9833                PackageParser.Package childPkg = pkg.childPackages.get(i);
9834                scanPackageLI(childPkg, policyFlags,
9835                        scanFlags, currentTime, user);
9836            }
9837        } finally {
9838            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9839        }
9840
9841        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9842            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
9843        }
9844
9845        return scannedPkg;
9846    }
9847
9848    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
9849            int scanFlags, long currentTime, @Nullable UserHandle user)
9850                    throws PackageManagerException {
9851        boolean success = false;
9852        try {
9853            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9854                    currentTime, user);
9855            success = true;
9856            return res;
9857        } finally {
9858            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9859                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9860                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9861                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9862                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9863            }
9864        }
9865    }
9866
9867    /**
9868     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9869     */
9870    private static boolean apkHasCode(String fileName) {
9871        StrictJarFile jarFile = null;
9872        try {
9873            jarFile = new StrictJarFile(fileName,
9874                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9875            return jarFile.findEntry("classes.dex") != null;
9876        } catch (IOException ignore) {
9877        } finally {
9878            try {
9879                if (jarFile != null) {
9880                    jarFile.close();
9881                }
9882            } catch (IOException ignore) {}
9883        }
9884        return false;
9885    }
9886
9887    /**
9888     * Enforces code policy for the package. This ensures that if an APK has
9889     * declared hasCode="true" in its manifest that the APK actually contains
9890     * code.
9891     *
9892     * @throws PackageManagerException If bytecode could not be found when it should exist
9893     */
9894    private static void assertCodePolicy(PackageParser.Package pkg)
9895            throws PackageManagerException {
9896        final boolean shouldHaveCode =
9897                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9898        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9899            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9900                    "Package " + pkg.baseCodePath + " code is missing");
9901        }
9902
9903        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9904            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9905                final boolean splitShouldHaveCode =
9906                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9907                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9908                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9909                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9910                }
9911            }
9912        }
9913    }
9914
9915    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9916            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
9917                    throws PackageManagerException {
9918        if (DEBUG_PACKAGE_SCANNING) {
9919            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9920                Log.d(TAG, "Scanning package " + pkg.packageName);
9921        }
9922
9923        applyPolicy(pkg, policyFlags);
9924
9925        assertPackageIsValid(pkg, policyFlags, scanFlags);
9926
9927        // Initialize package source and resource directories
9928        final File scanFile = new File(pkg.codePath);
9929        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9930        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9931
9932        SharedUserSetting suid = null;
9933        PackageSetting pkgSetting = null;
9934
9935        // Getting the package setting may have a side-effect, so if we
9936        // are only checking if scan would succeed, stash a copy of the
9937        // old setting to restore at the end.
9938        PackageSetting nonMutatedPs = null;
9939
9940        // We keep references to the derived CPU Abis from settings in oder to reuse
9941        // them in the case where we're not upgrading or booting for the first time.
9942        String primaryCpuAbiFromSettings = null;
9943        String secondaryCpuAbiFromSettings = null;
9944
9945        // writer
9946        synchronized (mPackages) {
9947            if (pkg.mSharedUserId != null) {
9948                // SIDE EFFECTS; may potentially allocate a new shared user
9949                suid = mSettings.getSharedUserLPw(
9950                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9951                if (DEBUG_PACKAGE_SCANNING) {
9952                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9953                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9954                                + "): packages=" + suid.packages);
9955                }
9956            }
9957
9958            // Check if we are renaming from an original package name.
9959            PackageSetting origPackage = null;
9960            String realName = null;
9961            if (pkg.mOriginalPackages != null) {
9962                // This package may need to be renamed to a previously
9963                // installed name.  Let's check on that...
9964                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9965                if (pkg.mOriginalPackages.contains(renamed)) {
9966                    // This package had originally been installed as the
9967                    // original name, and we have already taken care of
9968                    // transitioning to the new one.  Just update the new
9969                    // one to continue using the old name.
9970                    realName = pkg.mRealPackage;
9971                    if (!pkg.packageName.equals(renamed)) {
9972                        // Callers into this function may have already taken
9973                        // care of renaming the package; only do it here if
9974                        // it is not already done.
9975                        pkg.setPackageName(renamed);
9976                    }
9977                } else {
9978                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9979                        if ((origPackage = mSettings.getPackageLPr(
9980                                pkg.mOriginalPackages.get(i))) != null) {
9981                            // We do have the package already installed under its
9982                            // original name...  should we use it?
9983                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9984                                // New package is not compatible with original.
9985                                origPackage = null;
9986                                continue;
9987                            } else if (origPackage.sharedUser != null) {
9988                                // Make sure uid is compatible between packages.
9989                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9990                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9991                                            + " to " + pkg.packageName + ": old uid "
9992                                            + origPackage.sharedUser.name
9993                                            + " differs from " + pkg.mSharedUserId);
9994                                    origPackage = null;
9995                                    continue;
9996                                }
9997                                // TODO: Add case when shared user id is added [b/28144775]
9998                            } else {
9999                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10000                                        + pkg.packageName + " to old name " + origPackage.name);
10001                            }
10002                            break;
10003                        }
10004                    }
10005                }
10006            }
10007
10008            if (mTransferedPackages.contains(pkg.packageName)) {
10009                Slog.w(TAG, "Package " + pkg.packageName
10010                        + " was transferred to another, but its .apk remains");
10011            }
10012
10013            // See comments in nonMutatedPs declaration
10014            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10015                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10016                if (foundPs != null) {
10017                    nonMutatedPs = new PackageSetting(foundPs);
10018                }
10019            }
10020
10021            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10022                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10023                if (foundPs != null) {
10024                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10025                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10026                }
10027            }
10028
10029            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10030            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10031                PackageManagerService.reportSettingsProblem(Log.WARN,
10032                        "Package " + pkg.packageName + " shared user changed from "
10033                                + (pkgSetting.sharedUser != null
10034                                        ? pkgSetting.sharedUser.name : "<nothing>")
10035                                + " to "
10036                                + (suid != null ? suid.name : "<nothing>")
10037                                + "; replacing with new");
10038                pkgSetting = null;
10039            }
10040            final PackageSetting oldPkgSetting =
10041                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10042            final PackageSetting disabledPkgSetting =
10043                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10044
10045            String[] usesStaticLibraries = null;
10046            if (pkg.usesStaticLibraries != null) {
10047                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10048                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10049            }
10050
10051            if (pkgSetting == null) {
10052                final String parentPackageName = (pkg.parentPackage != null)
10053                        ? pkg.parentPackage.packageName : null;
10054                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10055                // REMOVE SharedUserSetting from method; update in a separate call
10056                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10057                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10058                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10059                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10060                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10061                        true /*allowInstall*/, instantApp, parentPackageName,
10062                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
10063                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10064                // SIDE EFFECTS; updates system state; move elsewhere
10065                if (origPackage != null) {
10066                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10067                }
10068                mSettings.addUserToSettingLPw(pkgSetting);
10069            } else {
10070                // REMOVE SharedUserSetting from method; update in a separate call.
10071                //
10072                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10073                // secondaryCpuAbi are not known at this point so we always update them
10074                // to null here, only to reset them at a later point.
10075                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10076                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10077                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10078                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10079                        UserManagerService.getInstance(), usesStaticLibraries,
10080                        pkg.usesStaticLibrariesVersions);
10081            }
10082            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10083            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10084
10085            // SIDE EFFECTS; modifies system state; move elsewhere
10086            if (pkgSetting.origPackage != null) {
10087                // If we are first transitioning from an original package,
10088                // fix up the new package's name now.  We need to do this after
10089                // looking up the package under its new name, so getPackageLP
10090                // can take care of fiddling things correctly.
10091                pkg.setPackageName(origPackage.name);
10092
10093                // File a report about this.
10094                String msg = "New package " + pkgSetting.realName
10095                        + " renamed to replace old package " + pkgSetting.name;
10096                reportSettingsProblem(Log.WARN, msg);
10097
10098                // Make a note of it.
10099                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10100                    mTransferedPackages.add(origPackage.name);
10101                }
10102
10103                // No longer need to retain this.
10104                pkgSetting.origPackage = null;
10105            }
10106
10107            // SIDE EFFECTS; modifies system state; move elsewhere
10108            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10109                // Make a note of it.
10110                mTransferedPackages.add(pkg.packageName);
10111            }
10112
10113            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10114                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10115            }
10116
10117            if ((scanFlags & SCAN_BOOTING) == 0
10118                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10119                // Check all shared libraries and map to their actual file path.
10120                // We only do this here for apps not on a system dir, because those
10121                // are the only ones that can fail an install due to this.  We
10122                // will take care of the system apps by updating all of their
10123                // library paths after the scan is done. Also during the initial
10124                // scan don't update any libs as we do this wholesale after all
10125                // apps are scanned to avoid dependency based scanning.
10126                updateSharedLibrariesLPr(pkg, null);
10127            }
10128
10129            if (mFoundPolicyFile) {
10130                SELinuxMMAC.assignSeInfoValue(pkg);
10131            }
10132            pkg.applicationInfo.uid = pkgSetting.appId;
10133            pkg.mExtras = pkgSetting;
10134
10135
10136            // Static shared libs have same package with different versions where
10137            // we internally use a synthetic package name to allow multiple versions
10138            // of the same package, therefore we need to compare signatures against
10139            // the package setting for the latest library version.
10140            PackageSetting signatureCheckPs = pkgSetting;
10141            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10142                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10143                if (libraryEntry != null) {
10144                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10145                }
10146            }
10147
10148            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10149                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10150                    // We just determined the app is signed correctly, so bring
10151                    // over the latest parsed certs.
10152                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10153                } else {
10154                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10155                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10156                                "Package " + pkg.packageName + " upgrade keys do not match the "
10157                                + "previously installed version");
10158                    } else {
10159                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10160                        String msg = "System package " + pkg.packageName
10161                                + " signature changed; retaining data.";
10162                        reportSettingsProblem(Log.WARN, msg);
10163                    }
10164                }
10165            } else {
10166                try {
10167                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10168                    verifySignaturesLP(signatureCheckPs, pkg);
10169                    // We just determined the app is signed correctly, so bring
10170                    // over the latest parsed certs.
10171                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10172                } catch (PackageManagerException e) {
10173                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10174                        throw e;
10175                    }
10176                    // The signature has changed, but this package is in the system
10177                    // image...  let's recover!
10178                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10179                    // However...  if this package is part of a shared user, but it
10180                    // doesn't match the signature of the shared user, let's fail.
10181                    // What this means is that you can't change the signatures
10182                    // associated with an overall shared user, which doesn't seem all
10183                    // that unreasonable.
10184                    if (signatureCheckPs.sharedUser != null) {
10185                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10186                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10187                            throw new PackageManagerException(
10188                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10189                                    "Signature mismatch for shared user: "
10190                                            + pkgSetting.sharedUser);
10191                        }
10192                    }
10193                    // File a report about this.
10194                    String msg = "System package " + pkg.packageName
10195                            + " signature changed; retaining data.";
10196                    reportSettingsProblem(Log.WARN, msg);
10197                }
10198            }
10199
10200            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10201                // This package wants to adopt ownership of permissions from
10202                // another package.
10203                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10204                    final String origName = pkg.mAdoptPermissions.get(i);
10205                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10206                    if (orig != null) {
10207                        if (verifyPackageUpdateLPr(orig, pkg)) {
10208                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10209                                    + pkg.packageName);
10210                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10211                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10212                        }
10213                    }
10214                }
10215            }
10216        }
10217
10218        pkg.applicationInfo.processName = fixProcessName(
10219                pkg.applicationInfo.packageName,
10220                pkg.applicationInfo.processName);
10221
10222        if (pkg != mPlatformPackage) {
10223            // Get all of our default paths setup
10224            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10225        }
10226
10227        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10228
10229        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10230            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10231                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10232                derivePackageAbi(
10233                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
10234                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10235
10236                // Some system apps still use directory structure for native libraries
10237                // in which case we might end up not detecting abi solely based on apk
10238                // structure. Try to detect abi based on directory structure.
10239                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10240                        pkg.applicationInfo.primaryCpuAbi == null) {
10241                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10242                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10243                }
10244            } else {
10245                // This is not a first boot or an upgrade, don't bother deriving the
10246                // ABI during the scan. Instead, trust the value that was stored in the
10247                // package setting.
10248                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10249                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10250
10251                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10252
10253                if (DEBUG_ABI_SELECTION) {
10254                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10255                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10256                        pkg.applicationInfo.secondaryCpuAbi);
10257                }
10258            }
10259        } else {
10260            if ((scanFlags & SCAN_MOVE) != 0) {
10261                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10262                // but we already have this packages package info in the PackageSetting. We just
10263                // use that and derive the native library path based on the new codepath.
10264                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10265                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10266            }
10267
10268            // Set native library paths again. For moves, the path will be updated based on the
10269            // ABIs we've determined above. For non-moves, the path will be updated based on the
10270            // ABIs we determined during compilation, but the path will depend on the final
10271            // package path (after the rename away from the stage path).
10272            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10273        }
10274
10275        // This is a special case for the "system" package, where the ABI is
10276        // dictated by the zygote configuration (and init.rc). We should keep track
10277        // of this ABI so that we can deal with "normal" applications that run under
10278        // the same UID correctly.
10279        if (mPlatformPackage == pkg) {
10280            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10281                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10282        }
10283
10284        // If there's a mismatch between the abi-override in the package setting
10285        // and the abiOverride specified for the install. Warn about this because we
10286        // would've already compiled the app without taking the package setting into
10287        // account.
10288        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10289            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10290                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10291                        " for package " + pkg.packageName);
10292            }
10293        }
10294
10295        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10296        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10297        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10298
10299        // Copy the derived override back to the parsed package, so that we can
10300        // update the package settings accordingly.
10301        pkg.cpuAbiOverride = cpuAbiOverride;
10302
10303        if (DEBUG_ABI_SELECTION) {
10304            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10305                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10306                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10307        }
10308
10309        // Push the derived path down into PackageSettings so we know what to
10310        // clean up at uninstall time.
10311        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10312
10313        if (DEBUG_ABI_SELECTION) {
10314            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10315                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10316                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10317        }
10318
10319        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10320        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10321            // We don't do this here during boot because we can do it all
10322            // at once after scanning all existing packages.
10323            //
10324            // We also do this *before* we perform dexopt on this package, so that
10325            // we can avoid redundant dexopts, and also to make sure we've got the
10326            // code and package path correct.
10327            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10328        }
10329
10330        if (mFactoryTest && pkg.requestedPermissions.contains(
10331                android.Manifest.permission.FACTORY_TEST)) {
10332            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10333        }
10334
10335        if (isSystemApp(pkg)) {
10336            pkgSetting.isOrphaned = true;
10337        }
10338
10339        // Take care of first install / last update times.
10340        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10341        if (currentTime != 0) {
10342            if (pkgSetting.firstInstallTime == 0) {
10343                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10344            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10345                pkgSetting.lastUpdateTime = currentTime;
10346            }
10347        } else if (pkgSetting.firstInstallTime == 0) {
10348            // We need *something*.  Take time time stamp of the file.
10349            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10350        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10351            if (scanFileTime != pkgSetting.timeStamp) {
10352                // A package on the system image has changed; consider this
10353                // to be an update.
10354                pkgSetting.lastUpdateTime = scanFileTime;
10355            }
10356        }
10357        pkgSetting.setTimeStamp(scanFileTime);
10358
10359        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10360            if (nonMutatedPs != null) {
10361                synchronized (mPackages) {
10362                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10363                }
10364            }
10365        } else {
10366            final int userId = user == null ? 0 : user.getIdentifier();
10367            // Modify state for the given package setting
10368            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10369                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10370            if (pkgSetting.getInstantApp(userId)) {
10371                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10372            }
10373        }
10374        return pkg;
10375    }
10376
10377    /**
10378     * Applies policy to the parsed package based upon the given policy flags.
10379     * Ensures the package is in a good state.
10380     * <p>
10381     * Implementation detail: This method must NOT have any side effect. It would
10382     * ideally be static, but, it requires locks to read system state.
10383     */
10384    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10385        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10386            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10387            if (pkg.applicationInfo.isDirectBootAware()) {
10388                // we're direct boot aware; set for all components
10389                for (PackageParser.Service s : pkg.services) {
10390                    s.info.encryptionAware = s.info.directBootAware = true;
10391                }
10392                for (PackageParser.Provider p : pkg.providers) {
10393                    p.info.encryptionAware = p.info.directBootAware = true;
10394                }
10395                for (PackageParser.Activity a : pkg.activities) {
10396                    a.info.encryptionAware = a.info.directBootAware = true;
10397                }
10398                for (PackageParser.Activity r : pkg.receivers) {
10399                    r.info.encryptionAware = r.info.directBootAware = true;
10400                }
10401            }
10402        } else {
10403            // Only allow system apps to be flagged as core apps.
10404            pkg.coreApp = false;
10405            // clear flags not applicable to regular apps
10406            pkg.applicationInfo.privateFlags &=
10407                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10408            pkg.applicationInfo.privateFlags &=
10409                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10410        }
10411        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10412
10413        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10414            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10415        }
10416
10417        if (!isSystemApp(pkg)) {
10418            // Only system apps can use these features.
10419            pkg.mOriginalPackages = null;
10420            pkg.mRealPackage = null;
10421            pkg.mAdoptPermissions = null;
10422        }
10423    }
10424
10425    /**
10426     * Asserts the parsed package is valid according to the given policy. If the
10427     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10428     * <p>
10429     * Implementation detail: This method must NOT have any side effects. It would
10430     * ideally be static, but, it requires locks to read system state.
10431     *
10432     * @throws PackageManagerException If the package fails any of the validation checks
10433     */
10434    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10435            throws PackageManagerException {
10436        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10437            assertCodePolicy(pkg);
10438        }
10439
10440        if (pkg.applicationInfo.getCodePath() == null ||
10441                pkg.applicationInfo.getResourcePath() == null) {
10442            // Bail out. The resource and code paths haven't been set.
10443            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10444                    "Code and resource paths haven't been set correctly");
10445        }
10446
10447        // Make sure we're not adding any bogus keyset info
10448        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10449        ksms.assertScannedPackageValid(pkg);
10450
10451        synchronized (mPackages) {
10452            // The special "android" package can only be defined once
10453            if (pkg.packageName.equals("android")) {
10454                if (mAndroidApplication != null) {
10455                    Slog.w(TAG, "*************************************************");
10456                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10457                    Slog.w(TAG, " codePath=" + pkg.codePath);
10458                    Slog.w(TAG, "*************************************************");
10459                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10460                            "Core android package being redefined.  Skipping.");
10461                }
10462            }
10463
10464            // A package name must be unique; don't allow duplicates
10465            if (mPackages.containsKey(pkg.packageName)) {
10466                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10467                        "Application package " + pkg.packageName
10468                        + " already installed.  Skipping duplicate.");
10469            }
10470
10471            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10472                // Static libs have a synthetic package name containing the version
10473                // but we still want the base name to be unique.
10474                if (mPackages.containsKey(pkg.manifestPackageName)) {
10475                    throw new PackageManagerException(
10476                            "Duplicate static shared lib provider package");
10477                }
10478
10479                // Static shared libraries should have at least O target SDK
10480                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10481                    throw new PackageManagerException(
10482                            "Packages declaring static-shared libs must target O SDK or higher");
10483                }
10484
10485                // Package declaring static a shared lib cannot be instant apps
10486                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10487                    throw new PackageManagerException(
10488                            "Packages declaring static-shared libs cannot be instant apps");
10489                }
10490
10491                // Package declaring static a shared lib cannot be renamed since the package
10492                // name is synthetic and apps can't code around package manager internals.
10493                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10494                    throw new PackageManagerException(
10495                            "Packages declaring static-shared libs cannot be renamed");
10496                }
10497
10498                // Package declaring static a shared lib cannot declare child packages
10499                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10500                    throw new PackageManagerException(
10501                            "Packages declaring static-shared libs cannot have child packages");
10502                }
10503
10504                // Package declaring static a shared lib cannot declare dynamic libs
10505                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10506                    throw new PackageManagerException(
10507                            "Packages declaring static-shared libs cannot declare dynamic libs");
10508                }
10509
10510                // Package declaring static a shared lib cannot declare shared users
10511                if (pkg.mSharedUserId != null) {
10512                    throw new PackageManagerException(
10513                            "Packages declaring static-shared libs cannot declare shared users");
10514                }
10515
10516                // Static shared libs cannot declare activities
10517                if (!pkg.activities.isEmpty()) {
10518                    throw new PackageManagerException(
10519                            "Static shared libs cannot declare activities");
10520                }
10521
10522                // Static shared libs cannot declare services
10523                if (!pkg.services.isEmpty()) {
10524                    throw new PackageManagerException(
10525                            "Static shared libs cannot declare services");
10526                }
10527
10528                // Static shared libs cannot declare providers
10529                if (!pkg.providers.isEmpty()) {
10530                    throw new PackageManagerException(
10531                            "Static shared libs cannot declare content providers");
10532                }
10533
10534                // Static shared libs cannot declare receivers
10535                if (!pkg.receivers.isEmpty()) {
10536                    throw new PackageManagerException(
10537                            "Static shared libs cannot declare broadcast receivers");
10538                }
10539
10540                // Static shared libs cannot declare permission groups
10541                if (!pkg.permissionGroups.isEmpty()) {
10542                    throw new PackageManagerException(
10543                            "Static shared libs cannot declare permission groups");
10544                }
10545
10546                // Static shared libs cannot declare permissions
10547                if (!pkg.permissions.isEmpty()) {
10548                    throw new PackageManagerException(
10549                            "Static shared libs cannot declare permissions");
10550                }
10551
10552                // Static shared libs cannot declare protected broadcasts
10553                if (pkg.protectedBroadcasts != null) {
10554                    throw new PackageManagerException(
10555                            "Static shared libs cannot declare protected broadcasts");
10556                }
10557
10558                // Static shared libs cannot be overlay targets
10559                if (pkg.mOverlayTarget != null) {
10560                    throw new PackageManagerException(
10561                            "Static shared libs cannot be overlay targets");
10562                }
10563
10564                // The version codes must be ordered as lib versions
10565                int minVersionCode = Integer.MIN_VALUE;
10566                int maxVersionCode = Integer.MAX_VALUE;
10567
10568                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10569                        pkg.staticSharedLibName);
10570                if (versionedLib != null) {
10571                    final int versionCount = versionedLib.size();
10572                    for (int i = 0; i < versionCount; i++) {
10573                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10574                        // TODO: We will change version code to long, so in the new API it is long
10575                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
10576                                .getVersionCode();
10577                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10578                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10579                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10580                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10581                        } else {
10582                            minVersionCode = maxVersionCode = libVersionCode;
10583                            break;
10584                        }
10585                    }
10586                }
10587                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10588                    throw new PackageManagerException("Static shared"
10589                            + " lib version codes must be ordered as lib versions");
10590                }
10591            }
10592
10593            // Only privileged apps and updated privileged apps can add child packages.
10594            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10595                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10596                    throw new PackageManagerException("Only privileged apps can add child "
10597                            + "packages. Ignoring package " + pkg.packageName);
10598                }
10599                final int childCount = pkg.childPackages.size();
10600                for (int i = 0; i < childCount; i++) {
10601                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10602                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10603                            childPkg.packageName)) {
10604                        throw new PackageManagerException("Can't override child of "
10605                                + "another disabled app. Ignoring package " + pkg.packageName);
10606                    }
10607                }
10608            }
10609
10610            // If we're only installing presumed-existing packages, require that the
10611            // scanned APK is both already known and at the path previously established
10612            // for it.  Previously unknown packages we pick up normally, but if we have an
10613            // a priori expectation about this package's install presence, enforce it.
10614            // With a singular exception for new system packages. When an OTA contains
10615            // a new system package, we allow the codepath to change from a system location
10616            // to the user-installed location. If we don't allow this change, any newer,
10617            // user-installed version of the application will be ignored.
10618            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10619                if (mExpectingBetter.containsKey(pkg.packageName)) {
10620                    logCriticalInfo(Log.WARN,
10621                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10622                } else {
10623                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10624                    if (known != null) {
10625                        if (DEBUG_PACKAGE_SCANNING) {
10626                            Log.d(TAG, "Examining " + pkg.codePath
10627                                    + " and requiring known paths " + known.codePathString
10628                                    + " & " + known.resourcePathString);
10629                        }
10630                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10631                                || !pkg.applicationInfo.getResourcePath().equals(
10632                                        known.resourcePathString)) {
10633                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10634                                    "Application package " + pkg.packageName
10635                                    + " found at " + pkg.applicationInfo.getCodePath()
10636                                    + " but expected at " + known.codePathString
10637                                    + "; ignoring.");
10638                        }
10639                    }
10640                }
10641            }
10642
10643            // Verify that this new package doesn't have any content providers
10644            // that conflict with existing packages.  Only do this if the
10645            // package isn't already installed, since we don't want to break
10646            // things that are installed.
10647            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10648                final int N = pkg.providers.size();
10649                int i;
10650                for (i=0; i<N; i++) {
10651                    PackageParser.Provider p = pkg.providers.get(i);
10652                    if (p.info.authority != null) {
10653                        String names[] = p.info.authority.split(";");
10654                        for (int j = 0; j < names.length; j++) {
10655                            if (mProvidersByAuthority.containsKey(names[j])) {
10656                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10657                                final String otherPackageName =
10658                                        ((other != null && other.getComponentName() != null) ?
10659                                                other.getComponentName().getPackageName() : "?");
10660                                throw new PackageManagerException(
10661                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10662                                        "Can't install because provider name " + names[j]
10663                                                + " (in package " + pkg.applicationInfo.packageName
10664                                                + ") is already used by " + otherPackageName);
10665                            }
10666                        }
10667                    }
10668                }
10669            }
10670        }
10671    }
10672
10673    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10674            int type, String declaringPackageName, int declaringVersionCode) {
10675        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10676        if (versionedLib == null) {
10677            versionedLib = new SparseArray<>();
10678            mSharedLibraries.put(name, versionedLib);
10679            if (type == SharedLibraryInfo.TYPE_STATIC) {
10680                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10681            }
10682        } else if (versionedLib.indexOfKey(version) >= 0) {
10683            return false;
10684        }
10685        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10686                version, type, declaringPackageName, declaringVersionCode);
10687        versionedLib.put(version, libEntry);
10688        return true;
10689    }
10690
10691    private boolean removeSharedLibraryLPw(String name, int version) {
10692        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10693        if (versionedLib == null) {
10694            return false;
10695        }
10696        final int libIdx = versionedLib.indexOfKey(version);
10697        if (libIdx < 0) {
10698            return false;
10699        }
10700        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10701        versionedLib.remove(version);
10702        if (versionedLib.size() <= 0) {
10703            mSharedLibraries.remove(name);
10704            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10705                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10706                        .getPackageName());
10707            }
10708        }
10709        return true;
10710    }
10711
10712    /**
10713     * Adds a scanned package to the system. When this method is finished, the package will
10714     * be available for query, resolution, etc...
10715     */
10716    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10717            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
10718        final String pkgName = pkg.packageName;
10719        if (mCustomResolverComponentName != null &&
10720                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10721            setUpCustomResolverActivity(pkg);
10722        }
10723
10724        if (pkg.packageName.equals("android")) {
10725            synchronized (mPackages) {
10726                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10727                    // Set up information for our fall-back user intent resolution activity.
10728                    mPlatformPackage = pkg;
10729                    pkg.mVersionCode = mSdkVersion;
10730                    mAndroidApplication = pkg.applicationInfo;
10731                    if (!mResolverReplaced) {
10732                        mResolveActivity.applicationInfo = mAndroidApplication;
10733                        mResolveActivity.name = ResolverActivity.class.getName();
10734                        mResolveActivity.packageName = mAndroidApplication.packageName;
10735                        mResolveActivity.processName = "system:ui";
10736                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10737                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10738                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10739                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10740                        mResolveActivity.exported = true;
10741                        mResolveActivity.enabled = true;
10742                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10743                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10744                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10745                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10746                                | ActivityInfo.CONFIG_ORIENTATION
10747                                | ActivityInfo.CONFIG_KEYBOARD
10748                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10749                        mResolveInfo.activityInfo = mResolveActivity;
10750                        mResolveInfo.priority = 0;
10751                        mResolveInfo.preferredOrder = 0;
10752                        mResolveInfo.match = 0;
10753                        mResolveComponentName = new ComponentName(
10754                                mAndroidApplication.packageName, mResolveActivity.name);
10755                    }
10756                }
10757            }
10758        }
10759
10760        ArrayList<PackageParser.Package> clientLibPkgs = null;
10761        // writer
10762        synchronized (mPackages) {
10763            boolean hasStaticSharedLibs = false;
10764
10765            // Any app can add new static shared libraries
10766            if (pkg.staticSharedLibName != null) {
10767                // Static shared libs don't allow renaming as they have synthetic package
10768                // names to allow install of multiple versions, so use name from manifest.
10769                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10770                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10771                        pkg.manifestPackageName, pkg.mVersionCode)) {
10772                    hasStaticSharedLibs = true;
10773                } else {
10774                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10775                                + pkg.staticSharedLibName + " already exists; skipping");
10776                }
10777                // Static shared libs cannot be updated once installed since they
10778                // use synthetic package name which includes the version code, so
10779                // not need to update other packages's shared lib dependencies.
10780            }
10781
10782            if (!hasStaticSharedLibs
10783                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10784                // Only system apps can add new dynamic shared libraries.
10785                if (pkg.libraryNames != null) {
10786                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10787                        String name = pkg.libraryNames.get(i);
10788                        boolean allowed = false;
10789                        if (pkg.isUpdatedSystemApp()) {
10790                            // New library entries can only be added through the
10791                            // system image.  This is important to get rid of a lot
10792                            // of nasty edge cases: for example if we allowed a non-
10793                            // system update of the app to add a library, then uninstalling
10794                            // the update would make the library go away, and assumptions
10795                            // we made such as through app install filtering would now
10796                            // have allowed apps on the device which aren't compatible
10797                            // with it.  Better to just have the restriction here, be
10798                            // conservative, and create many fewer cases that can negatively
10799                            // impact the user experience.
10800                            final PackageSetting sysPs = mSettings
10801                                    .getDisabledSystemPkgLPr(pkg.packageName);
10802                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
10803                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
10804                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
10805                                        allowed = true;
10806                                        break;
10807                                    }
10808                                }
10809                            }
10810                        } else {
10811                            allowed = true;
10812                        }
10813                        if (allowed) {
10814                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10815                                    SharedLibraryInfo.VERSION_UNDEFINED,
10816                                    SharedLibraryInfo.TYPE_DYNAMIC,
10817                                    pkg.packageName, pkg.mVersionCode)) {
10818                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10819                                        + name + " already exists; skipping");
10820                            }
10821                        } else {
10822                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10823                                    + name + " that is not declared on system image; skipping");
10824                        }
10825                    }
10826
10827                    if ((scanFlags & SCAN_BOOTING) == 0) {
10828                        // If we are not booting, we need to update any applications
10829                        // that are clients of our shared library.  If we are booting,
10830                        // this will all be done once the scan is complete.
10831                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10832                    }
10833                }
10834            }
10835        }
10836
10837        if ((scanFlags & SCAN_BOOTING) != 0) {
10838            // No apps can run during boot scan, so they don't need to be frozen
10839        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10840            // Caller asked to not kill app, so it's probably not frozen
10841        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10842            // Caller asked us to ignore frozen check for some reason; they
10843            // probably didn't know the package name
10844        } else {
10845            // We're doing major surgery on this package, so it better be frozen
10846            // right now to keep it from launching
10847            checkPackageFrozen(pkgName);
10848        }
10849
10850        // Also need to kill any apps that are dependent on the library.
10851        if (clientLibPkgs != null) {
10852            for (int i=0; i<clientLibPkgs.size(); i++) {
10853                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10854                killApplication(clientPkg.applicationInfo.packageName,
10855                        clientPkg.applicationInfo.uid, "update lib");
10856            }
10857        }
10858
10859        // writer
10860        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10861
10862        synchronized (mPackages) {
10863            // We don't expect installation to fail beyond this point
10864
10865            // Add the new setting to mSettings
10866            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10867            // Add the new setting to mPackages
10868            mPackages.put(pkg.applicationInfo.packageName, pkg);
10869            // Make sure we don't accidentally delete its data.
10870            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10871            while (iter.hasNext()) {
10872                PackageCleanItem item = iter.next();
10873                if (pkgName.equals(item.packageName)) {
10874                    iter.remove();
10875                }
10876            }
10877
10878            // Add the package's KeySets to the global KeySetManagerService
10879            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10880            ksms.addScannedPackageLPw(pkg);
10881
10882            int N = pkg.providers.size();
10883            StringBuilder r = null;
10884            int i;
10885            for (i=0; i<N; i++) {
10886                PackageParser.Provider p = pkg.providers.get(i);
10887                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10888                        p.info.processName);
10889                mProviders.addProvider(p);
10890                p.syncable = p.info.isSyncable;
10891                if (p.info.authority != null) {
10892                    String names[] = p.info.authority.split(";");
10893                    p.info.authority = null;
10894                    for (int j = 0; j < names.length; j++) {
10895                        if (j == 1 && p.syncable) {
10896                            // We only want the first authority for a provider to possibly be
10897                            // syncable, so if we already added this provider using a different
10898                            // authority clear the syncable flag. We copy the provider before
10899                            // changing it because the mProviders object contains a reference
10900                            // to a provider that we don't want to change.
10901                            // Only do this for the second authority since the resulting provider
10902                            // object can be the same for all future authorities for this provider.
10903                            p = new PackageParser.Provider(p);
10904                            p.syncable = false;
10905                        }
10906                        if (!mProvidersByAuthority.containsKey(names[j])) {
10907                            mProvidersByAuthority.put(names[j], p);
10908                            if (p.info.authority == null) {
10909                                p.info.authority = names[j];
10910                            } else {
10911                                p.info.authority = p.info.authority + ";" + names[j];
10912                            }
10913                            if (DEBUG_PACKAGE_SCANNING) {
10914                                if (chatty)
10915                                    Log.d(TAG, "Registered content provider: " + names[j]
10916                                            + ", className = " + p.info.name + ", isSyncable = "
10917                                            + p.info.isSyncable);
10918                            }
10919                        } else {
10920                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10921                            Slog.w(TAG, "Skipping provider name " + names[j] +
10922                                    " (in package " + pkg.applicationInfo.packageName +
10923                                    "): name already used by "
10924                                    + ((other != null && other.getComponentName() != null)
10925                                            ? other.getComponentName().getPackageName() : "?"));
10926                        }
10927                    }
10928                }
10929                if (chatty) {
10930                    if (r == null) {
10931                        r = new StringBuilder(256);
10932                    } else {
10933                        r.append(' ');
10934                    }
10935                    r.append(p.info.name);
10936                }
10937            }
10938            if (r != null) {
10939                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10940            }
10941
10942            N = pkg.services.size();
10943            r = null;
10944            for (i=0; i<N; i++) {
10945                PackageParser.Service s = pkg.services.get(i);
10946                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10947                        s.info.processName);
10948                mServices.addService(s);
10949                if (chatty) {
10950                    if (r == null) {
10951                        r = new StringBuilder(256);
10952                    } else {
10953                        r.append(' ');
10954                    }
10955                    r.append(s.info.name);
10956                }
10957            }
10958            if (r != null) {
10959                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10960            }
10961
10962            N = pkg.receivers.size();
10963            r = null;
10964            for (i=0; i<N; i++) {
10965                PackageParser.Activity a = pkg.receivers.get(i);
10966                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10967                        a.info.processName);
10968                mReceivers.addActivity(a, "receiver");
10969                if (chatty) {
10970                    if (r == null) {
10971                        r = new StringBuilder(256);
10972                    } else {
10973                        r.append(' ');
10974                    }
10975                    r.append(a.info.name);
10976                }
10977            }
10978            if (r != null) {
10979                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10980            }
10981
10982            N = pkg.activities.size();
10983            r = null;
10984            for (i=0; i<N; i++) {
10985                PackageParser.Activity a = pkg.activities.get(i);
10986                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10987                        a.info.processName);
10988                mActivities.addActivity(a, "activity");
10989                if (chatty) {
10990                    if (r == null) {
10991                        r = new StringBuilder(256);
10992                    } else {
10993                        r.append(' ');
10994                    }
10995                    r.append(a.info.name);
10996                }
10997            }
10998            if (r != null) {
10999                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11000            }
11001
11002            N = pkg.permissionGroups.size();
11003            r = null;
11004            for (i=0; i<N; i++) {
11005                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11006                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11007                final String curPackageName = cur == null ? null : cur.info.packageName;
11008                // Dont allow ephemeral apps to define new permission groups.
11009                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11010                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11011                            + pg.info.packageName
11012                            + " ignored: instant apps cannot define new permission groups.");
11013                    continue;
11014                }
11015                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11016                if (cur == null || isPackageUpdate) {
11017                    mPermissionGroups.put(pg.info.name, pg);
11018                    if (chatty) {
11019                        if (r == null) {
11020                            r = new StringBuilder(256);
11021                        } else {
11022                            r.append(' ');
11023                        }
11024                        if (isPackageUpdate) {
11025                            r.append("UPD:");
11026                        }
11027                        r.append(pg.info.name);
11028                    }
11029                } else {
11030                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11031                            + pg.info.packageName + " ignored: original from "
11032                            + cur.info.packageName);
11033                    if (chatty) {
11034                        if (r == null) {
11035                            r = new StringBuilder(256);
11036                        } else {
11037                            r.append(' ');
11038                        }
11039                        r.append("DUP:");
11040                        r.append(pg.info.name);
11041                    }
11042                }
11043            }
11044            if (r != null) {
11045                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11046            }
11047
11048            N = pkg.permissions.size();
11049            r = null;
11050            for (i=0; i<N; i++) {
11051                PackageParser.Permission p = pkg.permissions.get(i);
11052
11053                // Dont allow ephemeral apps to define new permissions.
11054                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11055                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11056                            + p.info.packageName
11057                            + " ignored: instant apps cannot define new permissions.");
11058                    continue;
11059                }
11060
11061                // Assume by default that we did not install this permission into the system.
11062                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11063
11064                // Now that permission groups have a special meaning, we ignore permission
11065                // groups for legacy apps to prevent unexpected behavior. In particular,
11066                // permissions for one app being granted to someone just because they happen
11067                // to be in a group defined by another app (before this had no implications).
11068                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11069                    p.group = mPermissionGroups.get(p.info.group);
11070                    // Warn for a permission in an unknown group.
11071                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11072                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11073                                + p.info.packageName + " in an unknown group " + p.info.group);
11074                    }
11075                }
11076
11077                ArrayMap<String, BasePermission> permissionMap =
11078                        p.tree ? mSettings.mPermissionTrees
11079                                : mSettings.mPermissions;
11080                BasePermission bp = permissionMap.get(p.info.name);
11081
11082                // Allow system apps to redefine non-system permissions
11083                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11084                    final boolean currentOwnerIsSystem = (bp.perm != null
11085                            && isSystemApp(bp.perm.owner));
11086                    if (isSystemApp(p.owner)) {
11087                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11088                            // It's a built-in permission and no owner, take ownership now
11089                            bp.packageSetting = pkgSetting;
11090                            bp.perm = p;
11091                            bp.uid = pkg.applicationInfo.uid;
11092                            bp.sourcePackage = p.info.packageName;
11093                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11094                        } else if (!currentOwnerIsSystem) {
11095                            String msg = "New decl " + p.owner + " of permission  "
11096                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11097                            reportSettingsProblem(Log.WARN, msg);
11098                            bp = null;
11099                        }
11100                    }
11101                }
11102
11103                if (bp == null) {
11104                    bp = new BasePermission(p.info.name, p.info.packageName,
11105                            BasePermission.TYPE_NORMAL);
11106                    permissionMap.put(p.info.name, bp);
11107                }
11108
11109                if (bp.perm == null) {
11110                    if (bp.sourcePackage == null
11111                            || bp.sourcePackage.equals(p.info.packageName)) {
11112                        BasePermission tree = findPermissionTreeLP(p.info.name);
11113                        if (tree == null
11114                                || tree.sourcePackage.equals(p.info.packageName)) {
11115                            bp.packageSetting = pkgSetting;
11116                            bp.perm = p;
11117                            bp.uid = pkg.applicationInfo.uid;
11118                            bp.sourcePackage = p.info.packageName;
11119                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11120                            if (chatty) {
11121                                if (r == null) {
11122                                    r = new StringBuilder(256);
11123                                } else {
11124                                    r.append(' ');
11125                                }
11126                                r.append(p.info.name);
11127                            }
11128                        } else {
11129                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11130                                    + p.info.packageName + " ignored: base tree "
11131                                    + tree.name + " is from package "
11132                                    + tree.sourcePackage);
11133                        }
11134                    } else {
11135                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11136                                + p.info.packageName + " ignored: original from "
11137                                + bp.sourcePackage);
11138                    }
11139                } else if (chatty) {
11140                    if (r == null) {
11141                        r = new StringBuilder(256);
11142                    } else {
11143                        r.append(' ');
11144                    }
11145                    r.append("DUP:");
11146                    r.append(p.info.name);
11147                }
11148                if (bp.perm == p) {
11149                    bp.protectionLevel = p.info.protectionLevel;
11150                }
11151            }
11152
11153            if (r != null) {
11154                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11155            }
11156
11157            N = pkg.instrumentation.size();
11158            r = null;
11159            for (i=0; i<N; i++) {
11160                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11161                a.info.packageName = pkg.applicationInfo.packageName;
11162                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11163                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11164                a.info.splitNames = pkg.splitNames;
11165                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11166                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11167                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11168                a.info.dataDir = pkg.applicationInfo.dataDir;
11169                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11170                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11171                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11172                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11173                mInstrumentation.put(a.getComponentName(), a);
11174                if (chatty) {
11175                    if (r == null) {
11176                        r = new StringBuilder(256);
11177                    } else {
11178                        r.append(' ');
11179                    }
11180                    r.append(a.info.name);
11181                }
11182            }
11183            if (r != null) {
11184                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11185            }
11186
11187            if (pkg.protectedBroadcasts != null) {
11188                N = pkg.protectedBroadcasts.size();
11189                for (i=0; i<N; i++) {
11190                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11191                }
11192            }
11193        }
11194
11195        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11196    }
11197
11198    /**
11199     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11200     * is derived purely on the basis of the contents of {@code scanFile} and
11201     * {@code cpuAbiOverride}.
11202     *
11203     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11204     */
11205    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11206                                 String cpuAbiOverride, boolean extractLibs,
11207                                 File appLib32InstallDir)
11208            throws PackageManagerException {
11209        // Give ourselves some initial paths; we'll come back for another
11210        // pass once we've determined ABI below.
11211        setNativeLibraryPaths(pkg, appLib32InstallDir);
11212
11213        // We would never need to extract libs for forward-locked and external packages,
11214        // since the container service will do it for us. We shouldn't attempt to
11215        // extract libs from system app when it was not updated.
11216        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11217                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11218            extractLibs = false;
11219        }
11220
11221        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11222        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11223
11224        NativeLibraryHelper.Handle handle = null;
11225        try {
11226            handle = NativeLibraryHelper.Handle.create(pkg);
11227            // TODO(multiArch): This can be null for apps that didn't go through the
11228            // usual installation process. We can calculate it again, like we
11229            // do during install time.
11230            //
11231            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11232            // unnecessary.
11233            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11234
11235            // Null out the abis so that they can be recalculated.
11236            pkg.applicationInfo.primaryCpuAbi = null;
11237            pkg.applicationInfo.secondaryCpuAbi = null;
11238            if (isMultiArch(pkg.applicationInfo)) {
11239                // Warn if we've set an abiOverride for multi-lib packages..
11240                // By definition, we need to copy both 32 and 64 bit libraries for
11241                // such packages.
11242                if (pkg.cpuAbiOverride != null
11243                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11244                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11245                }
11246
11247                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11248                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11249                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11250                    if (extractLibs) {
11251                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11252                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11253                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11254                                useIsaSpecificSubdirs);
11255                    } else {
11256                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11257                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11258                    }
11259                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11260                }
11261
11262                maybeThrowExceptionForMultiArchCopy(
11263                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11264
11265                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11266                    if (extractLibs) {
11267                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11268                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11269                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11270                                useIsaSpecificSubdirs);
11271                    } else {
11272                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11273                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11274                    }
11275                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11276                }
11277
11278                maybeThrowExceptionForMultiArchCopy(
11279                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11280
11281                if (abi64 >= 0) {
11282                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11283                }
11284
11285                if (abi32 >= 0) {
11286                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11287                    if (abi64 >= 0) {
11288                        if (pkg.use32bitAbi) {
11289                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11290                            pkg.applicationInfo.primaryCpuAbi = abi;
11291                        } else {
11292                            pkg.applicationInfo.secondaryCpuAbi = abi;
11293                        }
11294                    } else {
11295                        pkg.applicationInfo.primaryCpuAbi = abi;
11296                    }
11297                }
11298
11299            } else {
11300                String[] abiList = (cpuAbiOverride != null) ?
11301                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11302
11303                // Enable gross and lame hacks for apps that are built with old
11304                // SDK tools. We must scan their APKs for renderscript bitcode and
11305                // not launch them if it's present. Don't bother checking on devices
11306                // that don't have 64 bit support.
11307                boolean needsRenderScriptOverride = false;
11308                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11309                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11310                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11311                    needsRenderScriptOverride = true;
11312                }
11313
11314                final int copyRet;
11315                if (extractLibs) {
11316                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11317                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11318                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11319                } else {
11320                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11321                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11322                }
11323                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11324
11325                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11326                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11327                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11328                }
11329
11330                if (copyRet >= 0) {
11331                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11332                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11333                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11334                } else if (needsRenderScriptOverride) {
11335                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11336                }
11337            }
11338        } catch (IOException ioe) {
11339            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11340        } finally {
11341            IoUtils.closeQuietly(handle);
11342        }
11343
11344        // Now that we've calculated the ABIs and determined if it's an internal app,
11345        // we will go ahead and populate the nativeLibraryPath.
11346        setNativeLibraryPaths(pkg, appLib32InstallDir);
11347    }
11348
11349    /**
11350     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11351     * i.e, so that all packages can be run inside a single process if required.
11352     *
11353     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11354     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11355     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11356     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11357     * updating a package that belongs to a shared user.
11358     *
11359     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11360     * adds unnecessary complexity.
11361     */
11362    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11363            PackageParser.Package scannedPackage) {
11364        String requiredInstructionSet = null;
11365        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11366            requiredInstructionSet = VMRuntime.getInstructionSet(
11367                     scannedPackage.applicationInfo.primaryCpuAbi);
11368        }
11369
11370        PackageSetting requirer = null;
11371        for (PackageSetting ps : packagesForUser) {
11372            // If packagesForUser contains scannedPackage, we skip it. This will happen
11373            // when scannedPackage is an update of an existing package. Without this check,
11374            // we will never be able to change the ABI of any package belonging to a shared
11375            // user, even if it's compatible with other packages.
11376            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11377                if (ps.primaryCpuAbiString == null) {
11378                    continue;
11379                }
11380
11381                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11382                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11383                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11384                    // this but there's not much we can do.
11385                    String errorMessage = "Instruction set mismatch, "
11386                            + ((requirer == null) ? "[caller]" : requirer)
11387                            + " requires " + requiredInstructionSet + " whereas " + ps
11388                            + " requires " + instructionSet;
11389                    Slog.w(TAG, errorMessage);
11390                }
11391
11392                if (requiredInstructionSet == null) {
11393                    requiredInstructionSet = instructionSet;
11394                    requirer = ps;
11395                }
11396            }
11397        }
11398
11399        if (requiredInstructionSet != null) {
11400            String adjustedAbi;
11401            if (requirer != null) {
11402                // requirer != null implies that either scannedPackage was null or that scannedPackage
11403                // did not require an ABI, in which case we have to adjust scannedPackage to match
11404                // the ABI of the set (which is the same as requirer's ABI)
11405                adjustedAbi = requirer.primaryCpuAbiString;
11406                if (scannedPackage != null) {
11407                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11408                }
11409            } else {
11410                // requirer == null implies that we're updating all ABIs in the set to
11411                // match scannedPackage.
11412                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11413            }
11414
11415            for (PackageSetting ps : packagesForUser) {
11416                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11417                    if (ps.primaryCpuAbiString != null) {
11418                        continue;
11419                    }
11420
11421                    ps.primaryCpuAbiString = adjustedAbi;
11422                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11423                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11424                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11425                        if (DEBUG_ABI_SELECTION) {
11426                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11427                                    + " (requirer="
11428                                    + (requirer != null ? requirer.pkg : "null")
11429                                    + ", scannedPackage="
11430                                    + (scannedPackage != null ? scannedPackage : "null")
11431                                    + ")");
11432                        }
11433                        try {
11434                            mInstaller.rmdex(ps.codePathString,
11435                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11436                        } catch (InstallerException ignored) {
11437                        }
11438                    }
11439                }
11440            }
11441        }
11442    }
11443
11444    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11445        synchronized (mPackages) {
11446            mResolverReplaced = true;
11447            // Set up information for custom user intent resolution activity.
11448            mResolveActivity.applicationInfo = pkg.applicationInfo;
11449            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11450            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11451            mResolveActivity.processName = pkg.applicationInfo.packageName;
11452            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11453            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11454                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11455            mResolveActivity.theme = 0;
11456            mResolveActivity.exported = true;
11457            mResolveActivity.enabled = true;
11458            mResolveInfo.activityInfo = mResolveActivity;
11459            mResolveInfo.priority = 0;
11460            mResolveInfo.preferredOrder = 0;
11461            mResolveInfo.match = 0;
11462            mResolveComponentName = mCustomResolverComponentName;
11463            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11464                    mResolveComponentName);
11465        }
11466    }
11467
11468    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11469        if (installerActivity == null) {
11470            if (DEBUG_EPHEMERAL) {
11471                Slog.d(TAG, "Clear ephemeral installer activity");
11472            }
11473            mInstantAppInstallerActivity = null;
11474            return;
11475        }
11476
11477        if (DEBUG_EPHEMERAL) {
11478            Slog.d(TAG, "Set ephemeral installer activity: "
11479                    + installerActivity.getComponentName());
11480        }
11481        // Set up information for ephemeral installer activity
11482        mInstantAppInstallerActivity = installerActivity;
11483        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11484                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11485        mInstantAppInstallerActivity.exported = true;
11486        mInstantAppInstallerActivity.enabled = true;
11487        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11488        mInstantAppInstallerInfo.priority = 0;
11489        mInstantAppInstallerInfo.preferredOrder = 1;
11490        mInstantAppInstallerInfo.isDefault = true;
11491        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11492                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11493    }
11494
11495    private static String calculateBundledApkRoot(final String codePathString) {
11496        final File codePath = new File(codePathString);
11497        final File codeRoot;
11498        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11499            codeRoot = Environment.getRootDirectory();
11500        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11501            codeRoot = Environment.getOemDirectory();
11502        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11503            codeRoot = Environment.getVendorDirectory();
11504        } else {
11505            // Unrecognized code path; take its top real segment as the apk root:
11506            // e.g. /something/app/blah.apk => /something
11507            try {
11508                File f = codePath.getCanonicalFile();
11509                File parent = f.getParentFile();    // non-null because codePath is a file
11510                File tmp;
11511                while ((tmp = parent.getParentFile()) != null) {
11512                    f = parent;
11513                    parent = tmp;
11514                }
11515                codeRoot = f;
11516                Slog.w(TAG, "Unrecognized code path "
11517                        + codePath + " - using " + codeRoot);
11518            } catch (IOException e) {
11519                // Can't canonicalize the code path -- shenanigans?
11520                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11521                return Environment.getRootDirectory().getPath();
11522            }
11523        }
11524        return codeRoot.getPath();
11525    }
11526
11527    /**
11528     * Derive and set the location of native libraries for the given package,
11529     * which varies depending on where and how the package was installed.
11530     */
11531    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11532        final ApplicationInfo info = pkg.applicationInfo;
11533        final String codePath = pkg.codePath;
11534        final File codeFile = new File(codePath);
11535        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11536        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11537
11538        info.nativeLibraryRootDir = null;
11539        info.nativeLibraryRootRequiresIsa = false;
11540        info.nativeLibraryDir = null;
11541        info.secondaryNativeLibraryDir = null;
11542
11543        if (isApkFile(codeFile)) {
11544            // Monolithic install
11545            if (bundledApp) {
11546                // If "/system/lib64/apkname" exists, assume that is the per-package
11547                // native library directory to use; otherwise use "/system/lib/apkname".
11548                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11549                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11550                        getPrimaryInstructionSet(info));
11551
11552                // This is a bundled system app so choose the path based on the ABI.
11553                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11554                // is just the default path.
11555                final String apkName = deriveCodePathName(codePath);
11556                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11557                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11558                        apkName).getAbsolutePath();
11559
11560                if (info.secondaryCpuAbi != null) {
11561                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11562                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11563                            secondaryLibDir, apkName).getAbsolutePath();
11564                }
11565            } else if (asecApp) {
11566                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11567                        .getAbsolutePath();
11568            } else {
11569                final String apkName = deriveCodePathName(codePath);
11570                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11571                        .getAbsolutePath();
11572            }
11573
11574            info.nativeLibraryRootRequiresIsa = false;
11575            info.nativeLibraryDir = info.nativeLibraryRootDir;
11576        } else {
11577            // Cluster install
11578            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11579            info.nativeLibraryRootRequiresIsa = true;
11580
11581            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11582                    getPrimaryInstructionSet(info)).getAbsolutePath();
11583
11584            if (info.secondaryCpuAbi != null) {
11585                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11586                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11587            }
11588        }
11589    }
11590
11591    /**
11592     * Calculate the abis and roots for a bundled app. These can uniquely
11593     * be determined from the contents of the system partition, i.e whether
11594     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11595     * of this information, and instead assume that the system was built
11596     * sensibly.
11597     */
11598    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11599                                           PackageSetting pkgSetting) {
11600        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11601
11602        // If "/system/lib64/apkname" exists, assume that is the per-package
11603        // native library directory to use; otherwise use "/system/lib/apkname".
11604        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11605        setBundledAppAbi(pkg, apkRoot, apkName);
11606        // pkgSetting might be null during rescan following uninstall of updates
11607        // to a bundled app, so accommodate that possibility.  The settings in
11608        // that case will be established later from the parsed package.
11609        //
11610        // If the settings aren't null, sync them up with what we've just derived.
11611        // note that apkRoot isn't stored in the package settings.
11612        if (pkgSetting != null) {
11613            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11614            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11615        }
11616    }
11617
11618    /**
11619     * Deduces the ABI of a bundled app and sets the relevant fields on the
11620     * parsed pkg object.
11621     *
11622     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11623     *        under which system libraries are installed.
11624     * @param apkName the name of the installed package.
11625     */
11626    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11627        final File codeFile = new File(pkg.codePath);
11628
11629        final boolean has64BitLibs;
11630        final boolean has32BitLibs;
11631        if (isApkFile(codeFile)) {
11632            // Monolithic install
11633            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11634            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11635        } else {
11636            // Cluster install
11637            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11638            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11639                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11640                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11641                has64BitLibs = (new File(rootDir, isa)).exists();
11642            } else {
11643                has64BitLibs = false;
11644            }
11645            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11646                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11647                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11648                has32BitLibs = (new File(rootDir, isa)).exists();
11649            } else {
11650                has32BitLibs = false;
11651            }
11652        }
11653
11654        if (has64BitLibs && !has32BitLibs) {
11655            // The package has 64 bit libs, but not 32 bit libs. Its primary
11656            // ABI should be 64 bit. We can safely assume here that the bundled
11657            // native libraries correspond to the most preferred ABI in the list.
11658
11659            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11660            pkg.applicationInfo.secondaryCpuAbi = null;
11661        } else if (has32BitLibs && !has64BitLibs) {
11662            // The package has 32 bit libs but not 64 bit libs. Its primary
11663            // ABI should be 32 bit.
11664
11665            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11666            pkg.applicationInfo.secondaryCpuAbi = null;
11667        } else if (has32BitLibs && has64BitLibs) {
11668            // The application has both 64 and 32 bit bundled libraries. We check
11669            // here that the app declares multiArch support, and warn if it doesn't.
11670            //
11671            // We will be lenient here and record both ABIs. The primary will be the
11672            // ABI that's higher on the list, i.e, a device that's configured to prefer
11673            // 64 bit apps will see a 64 bit primary ABI,
11674
11675            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11676                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11677            }
11678
11679            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11680                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11681                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11682            } else {
11683                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11684                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11685            }
11686        } else {
11687            pkg.applicationInfo.primaryCpuAbi = null;
11688            pkg.applicationInfo.secondaryCpuAbi = null;
11689        }
11690    }
11691
11692    private void killApplication(String pkgName, int appId, String reason) {
11693        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11694    }
11695
11696    private void killApplication(String pkgName, int appId, int userId, String reason) {
11697        // Request the ActivityManager to kill the process(only for existing packages)
11698        // so that we do not end up in a confused state while the user is still using the older
11699        // version of the application while the new one gets installed.
11700        final long token = Binder.clearCallingIdentity();
11701        try {
11702            IActivityManager am = ActivityManager.getService();
11703            if (am != null) {
11704                try {
11705                    am.killApplication(pkgName, appId, userId, reason);
11706                } catch (RemoteException e) {
11707                }
11708            }
11709        } finally {
11710            Binder.restoreCallingIdentity(token);
11711        }
11712    }
11713
11714    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11715        // Remove the parent package setting
11716        PackageSetting ps = (PackageSetting) pkg.mExtras;
11717        if (ps != null) {
11718            removePackageLI(ps, chatty);
11719        }
11720        // Remove the child package setting
11721        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11722        for (int i = 0; i < childCount; i++) {
11723            PackageParser.Package childPkg = pkg.childPackages.get(i);
11724            ps = (PackageSetting) childPkg.mExtras;
11725            if (ps != null) {
11726                removePackageLI(ps, chatty);
11727            }
11728        }
11729    }
11730
11731    void removePackageLI(PackageSetting ps, boolean chatty) {
11732        if (DEBUG_INSTALL) {
11733            if (chatty)
11734                Log.d(TAG, "Removing package " + ps.name);
11735        }
11736
11737        // writer
11738        synchronized (mPackages) {
11739            mPackages.remove(ps.name);
11740            final PackageParser.Package pkg = ps.pkg;
11741            if (pkg != null) {
11742                cleanPackageDataStructuresLILPw(pkg, chatty);
11743            }
11744        }
11745    }
11746
11747    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11748        if (DEBUG_INSTALL) {
11749            if (chatty)
11750                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11751        }
11752
11753        // writer
11754        synchronized (mPackages) {
11755            // Remove the parent package
11756            mPackages.remove(pkg.applicationInfo.packageName);
11757            cleanPackageDataStructuresLILPw(pkg, chatty);
11758
11759            // Remove the child packages
11760            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11761            for (int i = 0; i < childCount; i++) {
11762                PackageParser.Package childPkg = pkg.childPackages.get(i);
11763                mPackages.remove(childPkg.applicationInfo.packageName);
11764                cleanPackageDataStructuresLILPw(childPkg, chatty);
11765            }
11766        }
11767    }
11768
11769    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11770        int N = pkg.providers.size();
11771        StringBuilder r = null;
11772        int i;
11773        for (i=0; i<N; i++) {
11774            PackageParser.Provider p = pkg.providers.get(i);
11775            mProviders.removeProvider(p);
11776            if (p.info.authority == null) {
11777
11778                /* There was another ContentProvider with this authority when
11779                 * this app was installed so this authority is null,
11780                 * Ignore it as we don't have to unregister the provider.
11781                 */
11782                continue;
11783            }
11784            String names[] = p.info.authority.split(";");
11785            for (int j = 0; j < names.length; j++) {
11786                if (mProvidersByAuthority.get(names[j]) == p) {
11787                    mProvidersByAuthority.remove(names[j]);
11788                    if (DEBUG_REMOVE) {
11789                        if (chatty)
11790                            Log.d(TAG, "Unregistered content provider: " + names[j]
11791                                    + ", className = " + p.info.name + ", isSyncable = "
11792                                    + p.info.isSyncable);
11793                    }
11794                }
11795            }
11796            if (DEBUG_REMOVE && chatty) {
11797                if (r == null) {
11798                    r = new StringBuilder(256);
11799                } else {
11800                    r.append(' ');
11801                }
11802                r.append(p.info.name);
11803            }
11804        }
11805        if (r != null) {
11806            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11807        }
11808
11809        N = pkg.services.size();
11810        r = null;
11811        for (i=0; i<N; i++) {
11812            PackageParser.Service s = pkg.services.get(i);
11813            mServices.removeService(s);
11814            if (chatty) {
11815                if (r == null) {
11816                    r = new StringBuilder(256);
11817                } else {
11818                    r.append(' ');
11819                }
11820                r.append(s.info.name);
11821            }
11822        }
11823        if (r != null) {
11824            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11825        }
11826
11827        N = pkg.receivers.size();
11828        r = null;
11829        for (i=0; i<N; i++) {
11830            PackageParser.Activity a = pkg.receivers.get(i);
11831            mReceivers.removeActivity(a, "receiver");
11832            if (DEBUG_REMOVE && chatty) {
11833                if (r == null) {
11834                    r = new StringBuilder(256);
11835                } else {
11836                    r.append(' ');
11837                }
11838                r.append(a.info.name);
11839            }
11840        }
11841        if (r != null) {
11842            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11843        }
11844
11845        N = pkg.activities.size();
11846        r = null;
11847        for (i=0; i<N; i++) {
11848            PackageParser.Activity a = pkg.activities.get(i);
11849            mActivities.removeActivity(a, "activity");
11850            if (DEBUG_REMOVE && chatty) {
11851                if (r == null) {
11852                    r = new StringBuilder(256);
11853                } else {
11854                    r.append(' ');
11855                }
11856                r.append(a.info.name);
11857            }
11858        }
11859        if (r != null) {
11860            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11861        }
11862
11863        N = pkg.permissions.size();
11864        r = null;
11865        for (i=0; i<N; i++) {
11866            PackageParser.Permission p = pkg.permissions.get(i);
11867            BasePermission bp = mSettings.mPermissions.get(p.info.name);
11868            if (bp == null) {
11869                bp = mSettings.mPermissionTrees.get(p.info.name);
11870            }
11871            if (bp != null && bp.perm == p) {
11872                bp.perm = null;
11873                if (DEBUG_REMOVE && chatty) {
11874                    if (r == null) {
11875                        r = new StringBuilder(256);
11876                    } else {
11877                        r.append(' ');
11878                    }
11879                    r.append(p.info.name);
11880                }
11881            }
11882            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11883                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11884                if (appOpPkgs != null) {
11885                    appOpPkgs.remove(pkg.packageName);
11886                }
11887            }
11888        }
11889        if (r != null) {
11890            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11891        }
11892
11893        N = pkg.requestedPermissions.size();
11894        r = null;
11895        for (i=0; i<N; i++) {
11896            String perm = pkg.requestedPermissions.get(i);
11897            BasePermission bp = mSettings.mPermissions.get(perm);
11898            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11899                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11900                if (appOpPkgs != null) {
11901                    appOpPkgs.remove(pkg.packageName);
11902                    if (appOpPkgs.isEmpty()) {
11903                        mAppOpPermissionPackages.remove(perm);
11904                    }
11905                }
11906            }
11907        }
11908        if (r != null) {
11909            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11910        }
11911
11912        N = pkg.instrumentation.size();
11913        r = null;
11914        for (i=0; i<N; i++) {
11915            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11916            mInstrumentation.remove(a.getComponentName());
11917            if (DEBUG_REMOVE && chatty) {
11918                if (r == null) {
11919                    r = new StringBuilder(256);
11920                } else {
11921                    r.append(' ');
11922                }
11923                r.append(a.info.name);
11924            }
11925        }
11926        if (r != null) {
11927            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11928        }
11929
11930        r = null;
11931        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11932            // Only system apps can hold shared libraries.
11933            if (pkg.libraryNames != null) {
11934                for (i = 0; i < pkg.libraryNames.size(); i++) {
11935                    String name = pkg.libraryNames.get(i);
11936                    if (removeSharedLibraryLPw(name, 0)) {
11937                        if (DEBUG_REMOVE && chatty) {
11938                            if (r == null) {
11939                                r = new StringBuilder(256);
11940                            } else {
11941                                r.append(' ');
11942                            }
11943                            r.append(name);
11944                        }
11945                    }
11946                }
11947            }
11948        }
11949
11950        r = null;
11951
11952        // Any package can hold static shared libraries.
11953        if (pkg.staticSharedLibName != null) {
11954            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11955                if (DEBUG_REMOVE && chatty) {
11956                    if (r == null) {
11957                        r = new StringBuilder(256);
11958                    } else {
11959                        r.append(' ');
11960                    }
11961                    r.append(pkg.staticSharedLibName);
11962                }
11963            }
11964        }
11965
11966        if (r != null) {
11967            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11968        }
11969    }
11970
11971    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11972        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11973            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11974                return true;
11975            }
11976        }
11977        return false;
11978    }
11979
11980    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11981    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11982    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11983
11984    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11985        // Update the parent permissions
11986        updatePermissionsLPw(pkg.packageName, pkg, flags);
11987        // Update the child permissions
11988        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11989        for (int i = 0; i < childCount; i++) {
11990            PackageParser.Package childPkg = pkg.childPackages.get(i);
11991            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11992        }
11993    }
11994
11995    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11996            int flags) {
11997        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11998        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11999    }
12000
12001    private void updatePermissionsLPw(String changingPkg,
12002            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12003        // Make sure there are no dangling permission trees.
12004        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12005        while (it.hasNext()) {
12006            final BasePermission bp = it.next();
12007            if (bp.packageSetting == null) {
12008                // We may not yet have parsed the package, so just see if
12009                // we still know about its settings.
12010                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12011            }
12012            if (bp.packageSetting == null) {
12013                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12014                        + " from package " + bp.sourcePackage);
12015                it.remove();
12016            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12017                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12018                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12019                            + " from package " + bp.sourcePackage);
12020                    flags |= UPDATE_PERMISSIONS_ALL;
12021                    it.remove();
12022                }
12023            }
12024        }
12025
12026        // Make sure all dynamic permissions have been assigned to a package,
12027        // and make sure there are no dangling permissions.
12028        it = mSettings.mPermissions.values().iterator();
12029        while (it.hasNext()) {
12030            final BasePermission bp = it.next();
12031            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12032                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12033                        + bp.name + " pkg=" + bp.sourcePackage
12034                        + " info=" + bp.pendingInfo);
12035                if (bp.packageSetting == null && bp.pendingInfo != null) {
12036                    final BasePermission tree = findPermissionTreeLP(bp.name);
12037                    if (tree != null && tree.perm != null) {
12038                        bp.packageSetting = tree.packageSetting;
12039                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12040                                new PermissionInfo(bp.pendingInfo));
12041                        bp.perm.info.packageName = tree.perm.info.packageName;
12042                        bp.perm.info.name = bp.name;
12043                        bp.uid = tree.uid;
12044                    }
12045                }
12046            }
12047            if (bp.packageSetting == null) {
12048                // We may not yet have parsed the package, so just see if
12049                // we still know about its settings.
12050                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12051            }
12052            if (bp.packageSetting == null) {
12053                Slog.w(TAG, "Removing dangling permission: " + bp.name
12054                        + " from package " + bp.sourcePackage);
12055                it.remove();
12056            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12057                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12058                    Slog.i(TAG, "Removing old permission: " + bp.name
12059                            + " from package " + bp.sourcePackage);
12060                    flags |= UPDATE_PERMISSIONS_ALL;
12061                    it.remove();
12062                }
12063            }
12064        }
12065
12066        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12067        // Now update the permissions for all packages, in particular
12068        // replace the granted permissions of the system packages.
12069        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12070            for (PackageParser.Package pkg : mPackages.values()) {
12071                if (pkg != pkgInfo) {
12072                    // Only replace for packages on requested volume
12073                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12074                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12075                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12076                    grantPermissionsLPw(pkg, replace, changingPkg);
12077                }
12078            }
12079        }
12080
12081        if (pkgInfo != null) {
12082            // Only replace for packages on requested volume
12083            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12084            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12085                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12086            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12087        }
12088        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12089    }
12090
12091    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12092            String packageOfInterest) {
12093        // IMPORTANT: There are two types of permissions: install and runtime.
12094        // Install time permissions are granted when the app is installed to
12095        // all device users and users added in the future. Runtime permissions
12096        // are granted at runtime explicitly to specific users. Normal and signature
12097        // protected permissions are install time permissions. Dangerous permissions
12098        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12099        // otherwise they are runtime permissions. This function does not manage
12100        // runtime permissions except for the case an app targeting Lollipop MR1
12101        // being upgraded to target a newer SDK, in which case dangerous permissions
12102        // are transformed from install time to runtime ones.
12103
12104        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12105        if (ps == null) {
12106            return;
12107        }
12108
12109        PermissionsState permissionsState = ps.getPermissionsState();
12110        PermissionsState origPermissions = permissionsState;
12111
12112        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12113
12114        boolean runtimePermissionsRevoked = false;
12115        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12116
12117        boolean changedInstallPermission = false;
12118
12119        if (replace) {
12120            ps.installPermissionsFixed = false;
12121            if (!ps.isSharedUser()) {
12122                origPermissions = new PermissionsState(permissionsState);
12123                permissionsState.reset();
12124            } else {
12125                // We need to know only about runtime permission changes since the
12126                // calling code always writes the install permissions state but
12127                // the runtime ones are written only if changed. The only cases of
12128                // changed runtime permissions here are promotion of an install to
12129                // runtime and revocation of a runtime from a shared user.
12130                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12131                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12132                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12133                    runtimePermissionsRevoked = true;
12134                }
12135            }
12136        }
12137
12138        permissionsState.setGlobalGids(mGlobalGids);
12139
12140        final int N = pkg.requestedPermissions.size();
12141        for (int i=0; i<N; i++) {
12142            final String name = pkg.requestedPermissions.get(i);
12143            final BasePermission bp = mSettings.mPermissions.get(name);
12144            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12145                    >= Build.VERSION_CODES.M;
12146
12147            if (DEBUG_INSTALL) {
12148                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12149            }
12150
12151            if (bp == null || bp.packageSetting == null) {
12152                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12153                    if (DEBUG_PERMISSIONS) {
12154                        Slog.i(TAG, "Unknown permission " + name
12155                                + " in package " + pkg.packageName);
12156                    }
12157                }
12158                continue;
12159            }
12160
12161
12162            // Limit ephemeral apps to ephemeral allowed permissions.
12163            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12164                if (DEBUG_PERMISSIONS) {
12165                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12166                            + pkg.packageName);
12167                }
12168                continue;
12169            }
12170
12171            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12172                if (DEBUG_PERMISSIONS) {
12173                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12174                            + pkg.packageName);
12175                }
12176                continue;
12177            }
12178
12179            final String perm = bp.name;
12180            boolean allowedSig = false;
12181            int grant = GRANT_DENIED;
12182
12183            // Keep track of app op permissions.
12184            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12185                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12186                if (pkgs == null) {
12187                    pkgs = new ArraySet<>();
12188                    mAppOpPermissionPackages.put(bp.name, pkgs);
12189                }
12190                pkgs.add(pkg.packageName);
12191            }
12192
12193            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12194            switch (level) {
12195                case PermissionInfo.PROTECTION_NORMAL: {
12196                    // For all apps normal permissions are install time ones.
12197                    grant = GRANT_INSTALL;
12198                } break;
12199
12200                case PermissionInfo.PROTECTION_DANGEROUS: {
12201                    // If a permission review is required for legacy apps we represent
12202                    // their permissions as always granted runtime ones since we need
12203                    // to keep the review required permission flag per user while an
12204                    // install permission's state is shared across all users.
12205                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12206                        // For legacy apps dangerous permissions are install time ones.
12207                        grant = GRANT_INSTALL;
12208                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12209                        // For legacy apps that became modern, install becomes runtime.
12210                        grant = GRANT_UPGRADE;
12211                    } else if (mPromoteSystemApps
12212                            && isSystemApp(ps)
12213                            && mExistingSystemPackages.contains(ps.name)) {
12214                        // For legacy system apps, install becomes runtime.
12215                        // We cannot check hasInstallPermission() for system apps since those
12216                        // permissions were granted implicitly and not persisted pre-M.
12217                        grant = GRANT_UPGRADE;
12218                    } else {
12219                        // For modern apps keep runtime permissions unchanged.
12220                        grant = GRANT_RUNTIME;
12221                    }
12222                } break;
12223
12224                case PermissionInfo.PROTECTION_SIGNATURE: {
12225                    // For all apps signature permissions are install time ones.
12226                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12227                    if (allowedSig) {
12228                        grant = GRANT_INSTALL;
12229                    }
12230                } break;
12231            }
12232
12233            if (DEBUG_PERMISSIONS) {
12234                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12235            }
12236
12237            if (grant != GRANT_DENIED) {
12238                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12239                    // If this is an existing, non-system package, then
12240                    // we can't add any new permissions to it.
12241                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12242                        // Except...  if this is a permission that was added
12243                        // to the platform (note: need to only do this when
12244                        // updating the platform).
12245                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12246                            grant = GRANT_DENIED;
12247                        }
12248                    }
12249                }
12250
12251                switch (grant) {
12252                    case GRANT_INSTALL: {
12253                        // Revoke this as runtime permission to handle the case of
12254                        // a runtime permission being downgraded to an install one.
12255                        // Also in permission review mode we keep dangerous permissions
12256                        // for legacy apps
12257                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12258                            if (origPermissions.getRuntimePermissionState(
12259                                    bp.name, userId) != null) {
12260                                // Revoke the runtime permission and clear the flags.
12261                                origPermissions.revokeRuntimePermission(bp, userId);
12262                                origPermissions.updatePermissionFlags(bp, userId,
12263                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12264                                // If we revoked a permission permission, we have to write.
12265                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12266                                        changedRuntimePermissionUserIds, userId);
12267                            }
12268                        }
12269                        // Grant an install permission.
12270                        if (permissionsState.grantInstallPermission(bp) !=
12271                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12272                            changedInstallPermission = true;
12273                        }
12274                    } break;
12275
12276                    case GRANT_RUNTIME: {
12277                        // Grant previously granted runtime permissions.
12278                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12279                            PermissionState permissionState = origPermissions
12280                                    .getRuntimePermissionState(bp.name, userId);
12281                            int flags = permissionState != null
12282                                    ? permissionState.getFlags() : 0;
12283                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12284                                // Don't propagate the permission in a permission review mode if
12285                                // the former was revoked, i.e. marked to not propagate on upgrade.
12286                                // Note that in a permission review mode install permissions are
12287                                // represented as constantly granted runtime ones since we need to
12288                                // keep a per user state associated with the permission. Also the
12289                                // revoke on upgrade flag is no longer applicable and is reset.
12290                                final boolean revokeOnUpgrade = (flags & PackageManager
12291                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12292                                if (revokeOnUpgrade) {
12293                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12294                                    // Since we changed the flags, we have to write.
12295                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12296                                            changedRuntimePermissionUserIds, userId);
12297                                }
12298                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12299                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12300                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12301                                        // If we cannot put the permission as it was,
12302                                        // we have to write.
12303                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12304                                                changedRuntimePermissionUserIds, userId);
12305                                    }
12306                                }
12307
12308                                // If the app supports runtime permissions no need for a review.
12309                                if (mPermissionReviewRequired
12310                                        && appSupportsRuntimePermissions
12311                                        && (flags & PackageManager
12312                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12313                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12314                                    // Since we changed the flags, we have to write.
12315                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12316                                            changedRuntimePermissionUserIds, userId);
12317                                }
12318                            } else if (mPermissionReviewRequired
12319                                    && !appSupportsRuntimePermissions) {
12320                                // For legacy apps that need a permission review, every new
12321                                // runtime permission is granted but it is pending a review.
12322                                // We also need to review only platform defined runtime
12323                                // permissions as these are the only ones the platform knows
12324                                // how to disable the API to simulate revocation as legacy
12325                                // apps don't expect to run with revoked permissions.
12326                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12327                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12328                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12329                                        // We changed the flags, hence have to write.
12330                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12331                                                changedRuntimePermissionUserIds, userId);
12332                                    }
12333                                }
12334                                if (permissionsState.grantRuntimePermission(bp, userId)
12335                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12336                                    // We changed the permission, hence have to write.
12337                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12338                                            changedRuntimePermissionUserIds, userId);
12339                                }
12340                            }
12341                            // Propagate the permission flags.
12342                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12343                        }
12344                    } break;
12345
12346                    case GRANT_UPGRADE: {
12347                        // Grant runtime permissions for a previously held install permission.
12348                        PermissionState permissionState = origPermissions
12349                                .getInstallPermissionState(bp.name);
12350                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12351
12352                        if (origPermissions.revokeInstallPermission(bp)
12353                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12354                            // We will be transferring the permission flags, so clear them.
12355                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12356                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12357                            changedInstallPermission = true;
12358                        }
12359
12360                        // If the permission is not to be promoted to runtime we ignore it and
12361                        // also its other flags as they are not applicable to install permissions.
12362                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12363                            for (int userId : currentUserIds) {
12364                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12365                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12366                                    // Transfer the permission flags.
12367                                    permissionsState.updatePermissionFlags(bp, userId,
12368                                            flags, flags);
12369                                    // If we granted the permission, we have to write.
12370                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12371                                            changedRuntimePermissionUserIds, userId);
12372                                }
12373                            }
12374                        }
12375                    } break;
12376
12377                    default: {
12378                        if (packageOfInterest == null
12379                                || packageOfInterest.equals(pkg.packageName)) {
12380                            if (DEBUG_PERMISSIONS) {
12381                                Slog.i(TAG, "Not granting permission " + perm
12382                                        + " to package " + pkg.packageName
12383                                        + " because it was previously installed without");
12384                            }
12385                        }
12386                    } break;
12387                }
12388            } else {
12389                if (permissionsState.revokeInstallPermission(bp) !=
12390                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12391                    // Also drop the permission flags.
12392                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12393                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12394                    changedInstallPermission = true;
12395                    Slog.i(TAG, "Un-granting permission " + perm
12396                            + " from package " + pkg.packageName
12397                            + " (protectionLevel=" + bp.protectionLevel
12398                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12399                            + ")");
12400                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12401                    // Don't print warning for app op permissions, since it is fine for them
12402                    // not to be granted, there is a UI for the user to decide.
12403                    if (DEBUG_PERMISSIONS
12404                            && (packageOfInterest == null
12405                                    || packageOfInterest.equals(pkg.packageName))) {
12406                        Slog.i(TAG, "Not granting permission " + perm
12407                                + " to package " + pkg.packageName
12408                                + " (protectionLevel=" + bp.protectionLevel
12409                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12410                                + ")");
12411                    }
12412                }
12413            }
12414        }
12415
12416        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12417                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12418            // This is the first that we have heard about this package, so the
12419            // permissions we have now selected are fixed until explicitly
12420            // changed.
12421            ps.installPermissionsFixed = true;
12422        }
12423
12424        // Persist the runtime permissions state for users with changes. If permissions
12425        // were revoked because no app in the shared user declares them we have to
12426        // write synchronously to avoid losing runtime permissions state.
12427        for (int userId : changedRuntimePermissionUserIds) {
12428            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12429        }
12430    }
12431
12432    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12433        boolean allowed = false;
12434        final int NP = PackageParser.NEW_PERMISSIONS.length;
12435        for (int ip=0; ip<NP; ip++) {
12436            final PackageParser.NewPermissionInfo npi
12437                    = PackageParser.NEW_PERMISSIONS[ip];
12438            if (npi.name.equals(perm)
12439                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12440                allowed = true;
12441                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12442                        + pkg.packageName);
12443                break;
12444            }
12445        }
12446        return allowed;
12447    }
12448
12449    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12450            BasePermission bp, PermissionsState origPermissions) {
12451        boolean privilegedPermission = (bp.protectionLevel
12452                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12453        boolean privappPermissionsDisable =
12454                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12455        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12456        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12457        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12458                && !platformPackage && platformPermission) {
12459            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12460                    .getPrivAppPermissions(pkg.packageName);
12461            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12462            if (!whitelisted) {
12463                Slog.w(TAG, "Privileged permission " + perm + " for package "
12464                        + pkg.packageName + " - not in privapp-permissions whitelist");
12465                // Only report violations for apps on system image
12466                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12467                    if (mPrivappPermissionsViolations == null) {
12468                        mPrivappPermissionsViolations = new ArraySet<>();
12469                    }
12470                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12471                }
12472                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12473                    return false;
12474                }
12475            }
12476        }
12477        boolean allowed = (compareSignatures(
12478                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12479                        == PackageManager.SIGNATURE_MATCH)
12480                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12481                        == PackageManager.SIGNATURE_MATCH);
12482        if (!allowed && privilegedPermission) {
12483            if (isSystemApp(pkg)) {
12484                // For updated system applications, a system permission
12485                // is granted only if it had been defined by the original application.
12486                if (pkg.isUpdatedSystemApp()) {
12487                    final PackageSetting sysPs = mSettings
12488                            .getDisabledSystemPkgLPr(pkg.packageName);
12489                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12490                        // If the original was granted this permission, we take
12491                        // that grant decision as read and propagate it to the
12492                        // update.
12493                        if (sysPs.isPrivileged()) {
12494                            allowed = true;
12495                        }
12496                    } else {
12497                        // The system apk may have been updated with an older
12498                        // version of the one on the data partition, but which
12499                        // granted a new system permission that it didn't have
12500                        // before.  In this case we do want to allow the app to
12501                        // now get the new permission if the ancestral apk is
12502                        // privileged to get it.
12503                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12504                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12505                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12506                                    allowed = true;
12507                                    break;
12508                                }
12509                            }
12510                        }
12511                        // Also if a privileged parent package on the system image or any of
12512                        // its children requested a privileged permission, the updated child
12513                        // packages can also get the permission.
12514                        if (pkg.parentPackage != null) {
12515                            final PackageSetting disabledSysParentPs = mSettings
12516                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12517                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12518                                    && disabledSysParentPs.isPrivileged()) {
12519                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12520                                    allowed = true;
12521                                } else if (disabledSysParentPs.pkg.childPackages != null) {
12522                                    final int count = disabledSysParentPs.pkg.childPackages.size();
12523                                    for (int i = 0; i < count; i++) {
12524                                        PackageParser.Package disabledSysChildPkg =
12525                                                disabledSysParentPs.pkg.childPackages.get(i);
12526                                        if (isPackageRequestingPermission(disabledSysChildPkg,
12527                                                perm)) {
12528                                            allowed = true;
12529                                            break;
12530                                        }
12531                                    }
12532                                }
12533                            }
12534                        }
12535                    }
12536                } else {
12537                    allowed = isPrivilegedApp(pkg);
12538                }
12539            }
12540        }
12541        if (!allowed) {
12542            if (!allowed && (bp.protectionLevel
12543                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12544                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12545                // If this was a previously normal/dangerous permission that got moved
12546                // to a system permission as part of the runtime permission redesign, then
12547                // we still want to blindly grant it to old apps.
12548                allowed = true;
12549            }
12550            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12551                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12552                // If this permission is to be granted to the system installer and
12553                // this app is an installer, then it gets the permission.
12554                allowed = true;
12555            }
12556            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12557                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12558                // If this permission is to be granted to the system verifier and
12559                // this app is a verifier, then it gets the permission.
12560                allowed = true;
12561            }
12562            if (!allowed && (bp.protectionLevel
12563                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12564                    && isSystemApp(pkg)) {
12565                // Any pre-installed system app is allowed to get this permission.
12566                allowed = true;
12567            }
12568            if (!allowed && (bp.protectionLevel
12569                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12570                // For development permissions, a development permission
12571                // is granted only if it was already granted.
12572                allowed = origPermissions.hasInstallPermission(perm);
12573            }
12574            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12575                    && pkg.packageName.equals(mSetupWizardPackage)) {
12576                // If this permission is to be granted to the system setup wizard and
12577                // this app is a setup wizard, then it gets the permission.
12578                allowed = true;
12579            }
12580        }
12581        return allowed;
12582    }
12583
12584    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12585        final int permCount = pkg.requestedPermissions.size();
12586        for (int j = 0; j < permCount; j++) {
12587            String requestedPermission = pkg.requestedPermissions.get(j);
12588            if (permission.equals(requestedPermission)) {
12589                return true;
12590            }
12591        }
12592        return false;
12593    }
12594
12595    final class ActivityIntentResolver
12596            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12597        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12598                boolean defaultOnly, int userId) {
12599            if (!sUserManager.exists(userId)) return null;
12600            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12601            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12602        }
12603
12604        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12605                int userId) {
12606            if (!sUserManager.exists(userId)) return null;
12607            mFlags = flags;
12608            return super.queryIntent(intent, resolvedType,
12609                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12610                    userId);
12611        }
12612
12613        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12614                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12615            if (!sUserManager.exists(userId)) return null;
12616            if (packageActivities == null) {
12617                return null;
12618            }
12619            mFlags = flags;
12620            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12621            final int N = packageActivities.size();
12622            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12623                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12624
12625            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12626            for (int i = 0; i < N; ++i) {
12627                intentFilters = packageActivities.get(i).intents;
12628                if (intentFilters != null && intentFilters.size() > 0) {
12629                    PackageParser.ActivityIntentInfo[] array =
12630                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12631                    intentFilters.toArray(array);
12632                    listCut.add(array);
12633                }
12634            }
12635            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12636        }
12637
12638        /**
12639         * Finds a privileged activity that matches the specified activity names.
12640         */
12641        private PackageParser.Activity findMatchingActivity(
12642                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12643            for (PackageParser.Activity sysActivity : activityList) {
12644                if (sysActivity.info.name.equals(activityInfo.name)) {
12645                    return sysActivity;
12646                }
12647                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12648                    return sysActivity;
12649                }
12650                if (sysActivity.info.targetActivity != null) {
12651                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12652                        return sysActivity;
12653                    }
12654                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12655                        return sysActivity;
12656                    }
12657                }
12658            }
12659            return null;
12660        }
12661
12662        public class IterGenerator<E> {
12663            public Iterator<E> generate(ActivityIntentInfo info) {
12664                return null;
12665            }
12666        }
12667
12668        public class ActionIterGenerator extends IterGenerator<String> {
12669            @Override
12670            public Iterator<String> generate(ActivityIntentInfo info) {
12671                return info.actionsIterator();
12672            }
12673        }
12674
12675        public class CategoriesIterGenerator extends IterGenerator<String> {
12676            @Override
12677            public Iterator<String> generate(ActivityIntentInfo info) {
12678                return info.categoriesIterator();
12679            }
12680        }
12681
12682        public class SchemesIterGenerator extends IterGenerator<String> {
12683            @Override
12684            public Iterator<String> generate(ActivityIntentInfo info) {
12685                return info.schemesIterator();
12686            }
12687        }
12688
12689        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12690            @Override
12691            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12692                return info.authoritiesIterator();
12693            }
12694        }
12695
12696        /**
12697         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12698         * MODIFIED. Do not pass in a list that should not be changed.
12699         */
12700        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12701                IterGenerator<T> generator, Iterator<T> searchIterator) {
12702            // loop through the set of actions; every one must be found in the intent filter
12703            while (searchIterator.hasNext()) {
12704                // we must have at least one filter in the list to consider a match
12705                if (intentList.size() == 0) {
12706                    break;
12707                }
12708
12709                final T searchAction = searchIterator.next();
12710
12711                // loop through the set of intent filters
12712                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12713                while (intentIter.hasNext()) {
12714                    final ActivityIntentInfo intentInfo = intentIter.next();
12715                    boolean selectionFound = false;
12716
12717                    // loop through the intent filter's selection criteria; at least one
12718                    // of them must match the searched criteria
12719                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12720                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12721                        final T intentSelection = intentSelectionIter.next();
12722                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12723                            selectionFound = true;
12724                            break;
12725                        }
12726                    }
12727
12728                    // the selection criteria wasn't found in this filter's set; this filter
12729                    // is not a potential match
12730                    if (!selectionFound) {
12731                        intentIter.remove();
12732                    }
12733                }
12734            }
12735        }
12736
12737        private boolean isProtectedAction(ActivityIntentInfo filter) {
12738            final Iterator<String> actionsIter = filter.actionsIterator();
12739            while (actionsIter != null && actionsIter.hasNext()) {
12740                final String filterAction = actionsIter.next();
12741                if (PROTECTED_ACTIONS.contains(filterAction)) {
12742                    return true;
12743                }
12744            }
12745            return false;
12746        }
12747
12748        /**
12749         * Adjusts the priority of the given intent filter according to policy.
12750         * <p>
12751         * <ul>
12752         * <li>The priority for non privileged applications is capped to '0'</li>
12753         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12754         * <li>The priority for unbundled updates to privileged applications is capped to the
12755         *      priority defined on the system partition</li>
12756         * </ul>
12757         * <p>
12758         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12759         * allowed to obtain any priority on any action.
12760         */
12761        private void adjustPriority(
12762                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12763            // nothing to do; priority is fine as-is
12764            if (intent.getPriority() <= 0) {
12765                return;
12766            }
12767
12768            final ActivityInfo activityInfo = intent.activity.info;
12769            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12770
12771            final boolean privilegedApp =
12772                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12773            if (!privilegedApp) {
12774                // non-privileged applications can never define a priority >0
12775                if (DEBUG_FILTERS) {
12776                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12777                            + " package: " + applicationInfo.packageName
12778                            + " activity: " + intent.activity.className
12779                            + " origPrio: " + intent.getPriority());
12780                }
12781                intent.setPriority(0);
12782                return;
12783            }
12784
12785            if (systemActivities == null) {
12786                // the system package is not disabled; we're parsing the system partition
12787                if (isProtectedAction(intent)) {
12788                    if (mDeferProtectedFilters) {
12789                        // We can't deal with these just yet. No component should ever obtain a
12790                        // >0 priority for a protected actions, with ONE exception -- the setup
12791                        // wizard. The setup wizard, however, cannot be known until we're able to
12792                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12793                        // until all intent filters have been processed. Chicken, meet egg.
12794                        // Let the filter temporarily have a high priority and rectify the
12795                        // priorities after all system packages have been scanned.
12796                        mProtectedFilters.add(intent);
12797                        if (DEBUG_FILTERS) {
12798                            Slog.i(TAG, "Protected action; save for later;"
12799                                    + " package: " + applicationInfo.packageName
12800                                    + " activity: " + intent.activity.className
12801                                    + " origPrio: " + intent.getPriority());
12802                        }
12803                        return;
12804                    } else {
12805                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12806                            Slog.i(TAG, "No setup wizard;"
12807                                + " All protected intents capped to priority 0");
12808                        }
12809                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12810                            if (DEBUG_FILTERS) {
12811                                Slog.i(TAG, "Found setup wizard;"
12812                                    + " allow priority " + intent.getPriority() + ";"
12813                                    + " package: " + intent.activity.info.packageName
12814                                    + " activity: " + intent.activity.className
12815                                    + " priority: " + intent.getPriority());
12816                            }
12817                            // setup wizard gets whatever it wants
12818                            return;
12819                        }
12820                        if (DEBUG_FILTERS) {
12821                            Slog.i(TAG, "Protected action; cap priority to 0;"
12822                                    + " package: " + intent.activity.info.packageName
12823                                    + " activity: " + intent.activity.className
12824                                    + " origPrio: " + intent.getPriority());
12825                        }
12826                        intent.setPriority(0);
12827                        return;
12828                    }
12829                }
12830                // privileged apps on the system image get whatever priority they request
12831                return;
12832            }
12833
12834            // privileged app unbundled update ... try to find the same activity
12835            final PackageParser.Activity foundActivity =
12836                    findMatchingActivity(systemActivities, activityInfo);
12837            if (foundActivity == null) {
12838                // this is a new activity; it cannot obtain >0 priority
12839                if (DEBUG_FILTERS) {
12840                    Slog.i(TAG, "New activity; cap priority to 0;"
12841                            + " package: " + applicationInfo.packageName
12842                            + " activity: " + intent.activity.className
12843                            + " origPrio: " + intent.getPriority());
12844                }
12845                intent.setPriority(0);
12846                return;
12847            }
12848
12849            // found activity, now check for filter equivalence
12850
12851            // a shallow copy is enough; we modify the list, not its contents
12852            final List<ActivityIntentInfo> intentListCopy =
12853                    new ArrayList<>(foundActivity.intents);
12854            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12855
12856            // find matching action subsets
12857            final Iterator<String> actionsIterator = intent.actionsIterator();
12858            if (actionsIterator != null) {
12859                getIntentListSubset(
12860                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12861                if (intentListCopy.size() == 0) {
12862                    // no more intents to match; we're not equivalent
12863                    if (DEBUG_FILTERS) {
12864                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12865                                + " package: " + applicationInfo.packageName
12866                                + " activity: " + intent.activity.className
12867                                + " origPrio: " + intent.getPriority());
12868                    }
12869                    intent.setPriority(0);
12870                    return;
12871                }
12872            }
12873
12874            // find matching category subsets
12875            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12876            if (categoriesIterator != null) {
12877                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12878                        categoriesIterator);
12879                if (intentListCopy.size() == 0) {
12880                    // no more intents to match; we're not equivalent
12881                    if (DEBUG_FILTERS) {
12882                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12883                                + " package: " + applicationInfo.packageName
12884                                + " activity: " + intent.activity.className
12885                                + " origPrio: " + intent.getPriority());
12886                    }
12887                    intent.setPriority(0);
12888                    return;
12889                }
12890            }
12891
12892            // find matching schemes subsets
12893            final Iterator<String> schemesIterator = intent.schemesIterator();
12894            if (schemesIterator != null) {
12895                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12896                        schemesIterator);
12897                if (intentListCopy.size() == 0) {
12898                    // no more intents to match; we're not equivalent
12899                    if (DEBUG_FILTERS) {
12900                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12901                                + " package: " + applicationInfo.packageName
12902                                + " activity: " + intent.activity.className
12903                                + " origPrio: " + intent.getPriority());
12904                    }
12905                    intent.setPriority(0);
12906                    return;
12907                }
12908            }
12909
12910            // find matching authorities subsets
12911            final Iterator<IntentFilter.AuthorityEntry>
12912                    authoritiesIterator = intent.authoritiesIterator();
12913            if (authoritiesIterator != null) {
12914                getIntentListSubset(intentListCopy,
12915                        new AuthoritiesIterGenerator(),
12916                        authoritiesIterator);
12917                if (intentListCopy.size() == 0) {
12918                    // no more intents to match; we're not equivalent
12919                    if (DEBUG_FILTERS) {
12920                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12921                                + " package: " + applicationInfo.packageName
12922                                + " activity: " + intent.activity.className
12923                                + " origPrio: " + intent.getPriority());
12924                    }
12925                    intent.setPriority(0);
12926                    return;
12927                }
12928            }
12929
12930            // we found matching filter(s); app gets the max priority of all intents
12931            int cappedPriority = 0;
12932            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12933                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12934            }
12935            if (intent.getPriority() > cappedPriority) {
12936                if (DEBUG_FILTERS) {
12937                    Slog.i(TAG, "Found matching filter(s);"
12938                            + " cap priority to " + cappedPriority + ";"
12939                            + " package: " + applicationInfo.packageName
12940                            + " activity: " + intent.activity.className
12941                            + " origPrio: " + intent.getPriority());
12942                }
12943                intent.setPriority(cappedPriority);
12944                return;
12945            }
12946            // all this for nothing; the requested priority was <= what was on the system
12947        }
12948
12949        public final void addActivity(PackageParser.Activity a, String type) {
12950            mActivities.put(a.getComponentName(), a);
12951            if (DEBUG_SHOW_INFO)
12952                Log.v(
12953                TAG, "  " + type + " " +
12954                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12955            if (DEBUG_SHOW_INFO)
12956                Log.v(TAG, "    Class=" + a.info.name);
12957            final int NI = a.intents.size();
12958            for (int j=0; j<NI; j++) {
12959                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12960                if ("activity".equals(type)) {
12961                    final PackageSetting ps =
12962                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12963                    final List<PackageParser.Activity> systemActivities =
12964                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12965                    adjustPriority(systemActivities, intent);
12966                }
12967                if (DEBUG_SHOW_INFO) {
12968                    Log.v(TAG, "    IntentFilter:");
12969                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12970                }
12971                if (!intent.debugCheck()) {
12972                    Log.w(TAG, "==> For Activity " + a.info.name);
12973                }
12974                addFilter(intent);
12975            }
12976        }
12977
12978        public final void removeActivity(PackageParser.Activity a, String type) {
12979            mActivities.remove(a.getComponentName());
12980            if (DEBUG_SHOW_INFO) {
12981                Log.v(TAG, "  " + type + " "
12982                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12983                                : a.info.name) + ":");
12984                Log.v(TAG, "    Class=" + a.info.name);
12985            }
12986            final int NI = a.intents.size();
12987            for (int j=0; j<NI; j++) {
12988                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12989                if (DEBUG_SHOW_INFO) {
12990                    Log.v(TAG, "    IntentFilter:");
12991                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12992                }
12993                removeFilter(intent);
12994            }
12995        }
12996
12997        @Override
12998        protected boolean allowFilterResult(
12999                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13000            ActivityInfo filterAi = filter.activity.info;
13001            for (int i=dest.size()-1; i>=0; i--) {
13002                ActivityInfo destAi = dest.get(i).activityInfo;
13003                if (destAi.name == filterAi.name
13004                        && destAi.packageName == filterAi.packageName) {
13005                    return false;
13006                }
13007            }
13008            return true;
13009        }
13010
13011        @Override
13012        protected ActivityIntentInfo[] newArray(int size) {
13013            return new ActivityIntentInfo[size];
13014        }
13015
13016        @Override
13017        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13018            if (!sUserManager.exists(userId)) return true;
13019            PackageParser.Package p = filter.activity.owner;
13020            if (p != null) {
13021                PackageSetting ps = (PackageSetting)p.mExtras;
13022                if (ps != null) {
13023                    // System apps are never considered stopped for purposes of
13024                    // filtering, because there may be no way for the user to
13025                    // actually re-launch them.
13026                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13027                            && ps.getStopped(userId);
13028                }
13029            }
13030            return false;
13031        }
13032
13033        @Override
13034        protected boolean isPackageForFilter(String packageName,
13035                PackageParser.ActivityIntentInfo info) {
13036            return packageName.equals(info.activity.owner.packageName);
13037        }
13038
13039        @Override
13040        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13041                int match, int userId) {
13042            if (!sUserManager.exists(userId)) return null;
13043            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13044                return null;
13045            }
13046            final PackageParser.Activity activity = info.activity;
13047            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13048            if (ps == null) {
13049                return null;
13050            }
13051            final PackageUserState userState = ps.readUserState(userId);
13052            ActivityInfo ai = generateActivityInfo(activity, mFlags, userState, userId);
13053            if (ai == null) {
13054                return null;
13055            }
13056            final boolean matchExplicitlyVisibleOnly =
13057                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13058            final boolean matchVisibleToInstantApp =
13059                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13060            final boolean componentVisible =
13061                    matchVisibleToInstantApp
13062                    && info.isVisibleToInstantApp()
13063                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13064            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13065            // throw out filters that aren't visible to ephemeral apps
13066            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13067                return null;
13068            }
13069            // throw out instant app filters if we're not explicitly requesting them
13070            if (!matchInstantApp && userState.instantApp) {
13071                return null;
13072            }
13073            // throw out instant app filters if updates are available; will trigger
13074            // instant app resolution
13075            if (userState.instantApp && ps.isUpdateAvailable()) {
13076                return null;
13077            }
13078            final ResolveInfo res = new ResolveInfo();
13079            res.activityInfo = ai;
13080            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13081                res.filter = info;
13082            }
13083            if (info != null) {
13084                res.handleAllWebDataURI = info.handleAllWebDataURI();
13085            }
13086            res.priority = info.getPriority();
13087            res.preferredOrder = activity.owner.mPreferredOrder;
13088            //System.out.println("Result: " + res.activityInfo.className +
13089            //                   " = " + res.priority);
13090            res.match = match;
13091            res.isDefault = info.hasDefault;
13092            res.labelRes = info.labelRes;
13093            res.nonLocalizedLabel = info.nonLocalizedLabel;
13094            if (userNeedsBadging(userId)) {
13095                res.noResourceId = true;
13096            } else {
13097                res.icon = info.icon;
13098            }
13099            res.iconResourceId = info.icon;
13100            res.system = res.activityInfo.applicationInfo.isSystemApp();
13101            res.isInstantAppAvailable = userState.instantApp;
13102            return res;
13103        }
13104
13105        @Override
13106        protected void sortResults(List<ResolveInfo> results) {
13107            Collections.sort(results, mResolvePrioritySorter);
13108        }
13109
13110        @Override
13111        protected void dumpFilter(PrintWriter out, String prefix,
13112                PackageParser.ActivityIntentInfo filter) {
13113            out.print(prefix); out.print(
13114                    Integer.toHexString(System.identityHashCode(filter.activity)));
13115                    out.print(' ');
13116                    filter.activity.printComponentShortName(out);
13117                    out.print(" filter ");
13118                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13119        }
13120
13121        @Override
13122        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13123            return filter.activity;
13124        }
13125
13126        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13127            PackageParser.Activity activity = (PackageParser.Activity)label;
13128            out.print(prefix); out.print(
13129                    Integer.toHexString(System.identityHashCode(activity)));
13130                    out.print(' ');
13131                    activity.printComponentShortName(out);
13132            if (count > 1) {
13133                out.print(" ("); out.print(count); out.print(" filters)");
13134            }
13135            out.println();
13136        }
13137
13138        // Keys are String (activity class name), values are Activity.
13139        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13140                = new ArrayMap<ComponentName, PackageParser.Activity>();
13141        private int mFlags;
13142    }
13143
13144    private final class ServiceIntentResolver
13145            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13146        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13147                boolean defaultOnly, int userId) {
13148            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13149            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13150        }
13151
13152        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13153                int userId) {
13154            if (!sUserManager.exists(userId)) return null;
13155            mFlags = flags;
13156            return super.queryIntent(intent, resolvedType,
13157                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13158                    userId);
13159        }
13160
13161        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13162                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13163            if (!sUserManager.exists(userId)) return null;
13164            if (packageServices == null) {
13165                return null;
13166            }
13167            mFlags = flags;
13168            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13169            final int N = packageServices.size();
13170            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13171                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13172
13173            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13174            for (int i = 0; i < N; ++i) {
13175                intentFilters = packageServices.get(i).intents;
13176                if (intentFilters != null && intentFilters.size() > 0) {
13177                    PackageParser.ServiceIntentInfo[] array =
13178                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13179                    intentFilters.toArray(array);
13180                    listCut.add(array);
13181                }
13182            }
13183            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13184        }
13185
13186        public final void addService(PackageParser.Service s) {
13187            mServices.put(s.getComponentName(), s);
13188            if (DEBUG_SHOW_INFO) {
13189                Log.v(TAG, "  "
13190                        + (s.info.nonLocalizedLabel != null
13191                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13192                Log.v(TAG, "    Class=" + s.info.name);
13193            }
13194            final int NI = s.intents.size();
13195            int j;
13196            for (j=0; j<NI; j++) {
13197                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13198                if (DEBUG_SHOW_INFO) {
13199                    Log.v(TAG, "    IntentFilter:");
13200                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13201                }
13202                if (!intent.debugCheck()) {
13203                    Log.w(TAG, "==> For Service " + s.info.name);
13204                }
13205                addFilter(intent);
13206            }
13207        }
13208
13209        public final void removeService(PackageParser.Service s) {
13210            mServices.remove(s.getComponentName());
13211            if (DEBUG_SHOW_INFO) {
13212                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13213                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13214                Log.v(TAG, "    Class=" + s.info.name);
13215            }
13216            final int NI = s.intents.size();
13217            int j;
13218            for (j=0; j<NI; j++) {
13219                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13220                if (DEBUG_SHOW_INFO) {
13221                    Log.v(TAG, "    IntentFilter:");
13222                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13223                }
13224                removeFilter(intent);
13225            }
13226        }
13227
13228        @Override
13229        protected boolean allowFilterResult(
13230                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13231            ServiceInfo filterSi = filter.service.info;
13232            for (int i=dest.size()-1; i>=0; i--) {
13233                ServiceInfo destAi = dest.get(i).serviceInfo;
13234                if (destAi.name == filterSi.name
13235                        && destAi.packageName == filterSi.packageName) {
13236                    return false;
13237                }
13238            }
13239            return true;
13240        }
13241
13242        @Override
13243        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13244            return new PackageParser.ServiceIntentInfo[size];
13245        }
13246
13247        @Override
13248        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13249            if (!sUserManager.exists(userId)) return true;
13250            PackageParser.Package p = filter.service.owner;
13251            if (p != null) {
13252                PackageSetting ps = (PackageSetting)p.mExtras;
13253                if (ps != null) {
13254                    // System apps are never considered stopped for purposes of
13255                    // filtering, because there may be no way for the user to
13256                    // actually re-launch them.
13257                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13258                            && ps.getStopped(userId);
13259                }
13260            }
13261            return false;
13262        }
13263
13264        @Override
13265        protected boolean isPackageForFilter(String packageName,
13266                PackageParser.ServiceIntentInfo info) {
13267            return packageName.equals(info.service.owner.packageName);
13268        }
13269
13270        @Override
13271        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13272                int match, int userId) {
13273            if (!sUserManager.exists(userId)) return null;
13274            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13275            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13276                return null;
13277            }
13278            final PackageParser.Service service = info.service;
13279            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13280            if (ps == null) {
13281                return null;
13282            }
13283            final PackageUserState userState = ps.readUserState(userId);
13284            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13285                    userState, userId);
13286            if (si == null) {
13287                return null;
13288            }
13289            final boolean matchVisibleToInstantApp =
13290                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13291            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13292            // throw out filters that aren't visible to ephemeral apps
13293            if (matchVisibleToInstantApp
13294                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13295                return null;
13296            }
13297            // throw out ephemeral filters if we're not explicitly requesting them
13298            if (!isInstantApp && userState.instantApp) {
13299                return null;
13300            }
13301            // throw out instant app filters if updates are available; will trigger
13302            // instant app resolution
13303            if (userState.instantApp && ps.isUpdateAvailable()) {
13304                return null;
13305            }
13306            final ResolveInfo res = new ResolveInfo();
13307            res.serviceInfo = si;
13308            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13309                res.filter = filter;
13310            }
13311            res.priority = info.getPriority();
13312            res.preferredOrder = service.owner.mPreferredOrder;
13313            res.match = match;
13314            res.isDefault = info.hasDefault;
13315            res.labelRes = info.labelRes;
13316            res.nonLocalizedLabel = info.nonLocalizedLabel;
13317            res.icon = info.icon;
13318            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13319            return res;
13320        }
13321
13322        @Override
13323        protected void sortResults(List<ResolveInfo> results) {
13324            Collections.sort(results, mResolvePrioritySorter);
13325        }
13326
13327        @Override
13328        protected void dumpFilter(PrintWriter out, String prefix,
13329                PackageParser.ServiceIntentInfo filter) {
13330            out.print(prefix); out.print(
13331                    Integer.toHexString(System.identityHashCode(filter.service)));
13332                    out.print(' ');
13333                    filter.service.printComponentShortName(out);
13334                    out.print(" filter ");
13335                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13336        }
13337
13338        @Override
13339        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13340            return filter.service;
13341        }
13342
13343        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13344            PackageParser.Service service = (PackageParser.Service)label;
13345            out.print(prefix); out.print(
13346                    Integer.toHexString(System.identityHashCode(service)));
13347                    out.print(' ');
13348                    service.printComponentShortName(out);
13349            if (count > 1) {
13350                out.print(" ("); out.print(count); out.print(" filters)");
13351            }
13352            out.println();
13353        }
13354
13355//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13356//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13357//            final List<ResolveInfo> retList = Lists.newArrayList();
13358//            while (i.hasNext()) {
13359//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13360//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13361//                    retList.add(resolveInfo);
13362//                }
13363//            }
13364//            return retList;
13365//        }
13366
13367        // Keys are String (activity class name), values are Activity.
13368        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13369                = new ArrayMap<ComponentName, PackageParser.Service>();
13370        private int mFlags;
13371    }
13372
13373    private final class ProviderIntentResolver
13374            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13375        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13376                boolean defaultOnly, int userId) {
13377            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13378            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13379        }
13380
13381        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13382                int userId) {
13383            if (!sUserManager.exists(userId))
13384                return null;
13385            mFlags = flags;
13386            return super.queryIntent(intent, resolvedType,
13387                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13388                    userId);
13389        }
13390
13391        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13392                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13393            if (!sUserManager.exists(userId))
13394                return null;
13395            if (packageProviders == null) {
13396                return null;
13397            }
13398            mFlags = flags;
13399            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13400            final int N = packageProviders.size();
13401            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13402                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13403
13404            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13405            for (int i = 0; i < N; ++i) {
13406                intentFilters = packageProviders.get(i).intents;
13407                if (intentFilters != null && intentFilters.size() > 0) {
13408                    PackageParser.ProviderIntentInfo[] array =
13409                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13410                    intentFilters.toArray(array);
13411                    listCut.add(array);
13412                }
13413            }
13414            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13415        }
13416
13417        public final void addProvider(PackageParser.Provider p) {
13418            if (mProviders.containsKey(p.getComponentName())) {
13419                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13420                return;
13421            }
13422
13423            mProviders.put(p.getComponentName(), p);
13424            if (DEBUG_SHOW_INFO) {
13425                Log.v(TAG, "  "
13426                        + (p.info.nonLocalizedLabel != null
13427                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13428                Log.v(TAG, "    Class=" + p.info.name);
13429            }
13430            final int NI = p.intents.size();
13431            int j;
13432            for (j = 0; j < NI; j++) {
13433                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13434                if (DEBUG_SHOW_INFO) {
13435                    Log.v(TAG, "    IntentFilter:");
13436                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13437                }
13438                if (!intent.debugCheck()) {
13439                    Log.w(TAG, "==> For Provider " + p.info.name);
13440                }
13441                addFilter(intent);
13442            }
13443        }
13444
13445        public final void removeProvider(PackageParser.Provider p) {
13446            mProviders.remove(p.getComponentName());
13447            if (DEBUG_SHOW_INFO) {
13448                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13449                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13450                Log.v(TAG, "    Class=" + p.info.name);
13451            }
13452            final int NI = p.intents.size();
13453            int j;
13454            for (j = 0; j < NI; j++) {
13455                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13456                if (DEBUG_SHOW_INFO) {
13457                    Log.v(TAG, "    IntentFilter:");
13458                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13459                }
13460                removeFilter(intent);
13461            }
13462        }
13463
13464        @Override
13465        protected boolean allowFilterResult(
13466                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13467            ProviderInfo filterPi = filter.provider.info;
13468            for (int i = dest.size() - 1; i >= 0; i--) {
13469                ProviderInfo destPi = dest.get(i).providerInfo;
13470                if (destPi.name == filterPi.name
13471                        && destPi.packageName == filterPi.packageName) {
13472                    return false;
13473                }
13474            }
13475            return true;
13476        }
13477
13478        @Override
13479        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13480            return new PackageParser.ProviderIntentInfo[size];
13481        }
13482
13483        @Override
13484        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13485            if (!sUserManager.exists(userId))
13486                return true;
13487            PackageParser.Package p = filter.provider.owner;
13488            if (p != null) {
13489                PackageSetting ps = (PackageSetting) p.mExtras;
13490                if (ps != null) {
13491                    // System apps are never considered stopped for purposes of
13492                    // filtering, because there may be no way for the user to
13493                    // actually re-launch them.
13494                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13495                            && ps.getStopped(userId);
13496                }
13497            }
13498            return false;
13499        }
13500
13501        @Override
13502        protected boolean isPackageForFilter(String packageName,
13503                PackageParser.ProviderIntentInfo info) {
13504            return packageName.equals(info.provider.owner.packageName);
13505        }
13506
13507        @Override
13508        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13509                int match, int userId) {
13510            if (!sUserManager.exists(userId))
13511                return null;
13512            final PackageParser.ProviderIntentInfo info = filter;
13513            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13514                return null;
13515            }
13516            final PackageParser.Provider provider = info.provider;
13517            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13518            if (ps == null) {
13519                return null;
13520            }
13521            final PackageUserState userState = ps.readUserState(userId);
13522            final boolean matchVisibleToInstantApp =
13523                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13524            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13525            // throw out filters that aren't visible to instant applications
13526            if (matchVisibleToInstantApp
13527                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13528                return null;
13529            }
13530            // throw out instant application filters if we're not explicitly requesting them
13531            if (!isInstantApp && userState.instantApp) {
13532                return null;
13533            }
13534            // throw out instant application filters if updates are available; will trigger
13535            // instant application resolution
13536            if (userState.instantApp && ps.isUpdateAvailable()) {
13537                return null;
13538            }
13539            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13540                    userState, userId);
13541            if (pi == null) {
13542                return null;
13543            }
13544            final ResolveInfo res = new ResolveInfo();
13545            res.providerInfo = pi;
13546            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13547                res.filter = filter;
13548            }
13549            res.priority = info.getPriority();
13550            res.preferredOrder = provider.owner.mPreferredOrder;
13551            res.match = match;
13552            res.isDefault = info.hasDefault;
13553            res.labelRes = info.labelRes;
13554            res.nonLocalizedLabel = info.nonLocalizedLabel;
13555            res.icon = info.icon;
13556            res.system = res.providerInfo.applicationInfo.isSystemApp();
13557            return res;
13558        }
13559
13560        @Override
13561        protected void sortResults(List<ResolveInfo> results) {
13562            Collections.sort(results, mResolvePrioritySorter);
13563        }
13564
13565        @Override
13566        protected void dumpFilter(PrintWriter out, String prefix,
13567                PackageParser.ProviderIntentInfo filter) {
13568            out.print(prefix);
13569            out.print(
13570                    Integer.toHexString(System.identityHashCode(filter.provider)));
13571            out.print(' ');
13572            filter.provider.printComponentShortName(out);
13573            out.print(" filter ");
13574            out.println(Integer.toHexString(System.identityHashCode(filter)));
13575        }
13576
13577        @Override
13578        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13579            return filter.provider;
13580        }
13581
13582        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13583            PackageParser.Provider provider = (PackageParser.Provider)label;
13584            out.print(prefix); out.print(
13585                    Integer.toHexString(System.identityHashCode(provider)));
13586                    out.print(' ');
13587                    provider.printComponentShortName(out);
13588            if (count > 1) {
13589                out.print(" ("); out.print(count); out.print(" filters)");
13590            }
13591            out.println();
13592        }
13593
13594        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13595                = new ArrayMap<ComponentName, PackageParser.Provider>();
13596        private int mFlags;
13597    }
13598
13599    static final class EphemeralIntentResolver
13600            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13601        /**
13602         * The result that has the highest defined order. Ordering applies on a
13603         * per-package basis. Mapping is from package name to Pair of order and
13604         * EphemeralResolveInfo.
13605         * <p>
13606         * NOTE: This is implemented as a field variable for convenience and efficiency.
13607         * By having a field variable, we're able to track filter ordering as soon as
13608         * a non-zero order is defined. Otherwise, multiple loops across the result set
13609         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13610         * this needs to be contained entirely within {@link #filterResults}.
13611         */
13612        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13613
13614        @Override
13615        protected AuxiliaryResolveInfo[] newArray(int size) {
13616            return new AuxiliaryResolveInfo[size];
13617        }
13618
13619        @Override
13620        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13621            return true;
13622        }
13623
13624        @Override
13625        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13626                int userId) {
13627            if (!sUserManager.exists(userId)) {
13628                return null;
13629            }
13630            final String packageName = responseObj.resolveInfo.getPackageName();
13631            final Integer order = responseObj.getOrder();
13632            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13633                    mOrderResult.get(packageName);
13634            // ordering is enabled and this item's order isn't high enough
13635            if (lastOrderResult != null && lastOrderResult.first >= order) {
13636                return null;
13637            }
13638            final InstantAppResolveInfo res = responseObj.resolveInfo;
13639            if (order > 0) {
13640                // non-zero order, enable ordering
13641                mOrderResult.put(packageName, new Pair<>(order, res));
13642            }
13643            return responseObj;
13644        }
13645
13646        @Override
13647        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13648            // only do work if ordering is enabled [most of the time it won't be]
13649            if (mOrderResult.size() == 0) {
13650                return;
13651            }
13652            int resultSize = results.size();
13653            for (int i = 0; i < resultSize; i++) {
13654                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13655                final String packageName = info.getPackageName();
13656                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13657                if (savedInfo == null) {
13658                    // package doesn't having ordering
13659                    continue;
13660                }
13661                if (savedInfo.second == info) {
13662                    // circled back to the highest ordered item; remove from order list
13663                    mOrderResult.remove(savedInfo);
13664                    if (mOrderResult.size() == 0) {
13665                        // no more ordered items
13666                        break;
13667                    }
13668                    continue;
13669                }
13670                // item has a worse order, remove it from the result list
13671                results.remove(i);
13672                resultSize--;
13673                i--;
13674            }
13675        }
13676    }
13677
13678    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13679            new Comparator<ResolveInfo>() {
13680        public int compare(ResolveInfo r1, ResolveInfo r2) {
13681            int v1 = r1.priority;
13682            int v2 = r2.priority;
13683            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13684            if (v1 != v2) {
13685                return (v1 > v2) ? -1 : 1;
13686            }
13687            v1 = r1.preferredOrder;
13688            v2 = r2.preferredOrder;
13689            if (v1 != v2) {
13690                return (v1 > v2) ? -1 : 1;
13691            }
13692            if (r1.isDefault != r2.isDefault) {
13693                return r1.isDefault ? -1 : 1;
13694            }
13695            v1 = r1.match;
13696            v2 = r2.match;
13697            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13698            if (v1 != v2) {
13699                return (v1 > v2) ? -1 : 1;
13700            }
13701            if (r1.system != r2.system) {
13702                return r1.system ? -1 : 1;
13703            }
13704            if (r1.activityInfo != null) {
13705                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13706            }
13707            if (r1.serviceInfo != null) {
13708                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13709            }
13710            if (r1.providerInfo != null) {
13711                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13712            }
13713            return 0;
13714        }
13715    };
13716
13717    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13718            new Comparator<ProviderInfo>() {
13719        public int compare(ProviderInfo p1, ProviderInfo p2) {
13720            final int v1 = p1.initOrder;
13721            final int v2 = p2.initOrder;
13722            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13723        }
13724    };
13725
13726    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13727            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13728            final int[] userIds) {
13729        mHandler.post(new Runnable() {
13730            @Override
13731            public void run() {
13732                try {
13733                    final IActivityManager am = ActivityManager.getService();
13734                    if (am == null) return;
13735                    final int[] resolvedUserIds;
13736                    if (userIds == null) {
13737                        resolvedUserIds = am.getRunningUserIds();
13738                    } else {
13739                        resolvedUserIds = userIds;
13740                    }
13741                    for (int id : resolvedUserIds) {
13742                        final Intent intent = new Intent(action,
13743                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13744                        if (extras != null) {
13745                            intent.putExtras(extras);
13746                        }
13747                        if (targetPkg != null) {
13748                            intent.setPackage(targetPkg);
13749                        }
13750                        // Modify the UID when posting to other users
13751                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13752                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
13753                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13754                            intent.putExtra(Intent.EXTRA_UID, uid);
13755                        }
13756                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13757                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13758                        if (DEBUG_BROADCASTS) {
13759                            RuntimeException here = new RuntimeException("here");
13760                            here.fillInStackTrace();
13761                            Slog.d(TAG, "Sending to user " + id + ": "
13762                                    + intent.toShortString(false, true, false, false)
13763                                    + " " + intent.getExtras(), here);
13764                        }
13765                        am.broadcastIntent(null, intent, null, finishedReceiver,
13766                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
13767                                null, finishedReceiver != null, false, id);
13768                    }
13769                } catch (RemoteException ex) {
13770                }
13771            }
13772        });
13773    }
13774
13775    /**
13776     * Check if the external storage media is available. This is true if there
13777     * is a mounted external storage medium or if the external storage is
13778     * emulated.
13779     */
13780    private boolean isExternalMediaAvailable() {
13781        return mMediaMounted || Environment.isExternalStorageEmulated();
13782    }
13783
13784    @Override
13785    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13786        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13787            return null;
13788        }
13789        // writer
13790        synchronized (mPackages) {
13791            if (!isExternalMediaAvailable()) {
13792                // If the external storage is no longer mounted at this point,
13793                // the caller may not have been able to delete all of this
13794                // packages files and can not delete any more.  Bail.
13795                return null;
13796            }
13797            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13798            if (lastPackage != null) {
13799                pkgs.remove(lastPackage);
13800            }
13801            if (pkgs.size() > 0) {
13802                return pkgs.get(0);
13803            }
13804        }
13805        return null;
13806    }
13807
13808    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13809        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13810                userId, andCode ? 1 : 0, packageName);
13811        if (mSystemReady) {
13812            msg.sendToTarget();
13813        } else {
13814            if (mPostSystemReadyMessages == null) {
13815                mPostSystemReadyMessages = new ArrayList<>();
13816            }
13817            mPostSystemReadyMessages.add(msg);
13818        }
13819    }
13820
13821    void startCleaningPackages() {
13822        // reader
13823        if (!isExternalMediaAvailable()) {
13824            return;
13825        }
13826        synchronized (mPackages) {
13827            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13828                return;
13829            }
13830        }
13831        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13832        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13833        IActivityManager am = ActivityManager.getService();
13834        if (am != null) {
13835            int dcsUid = -1;
13836            synchronized (mPackages) {
13837                if (!mDefaultContainerWhitelisted) {
13838                    mDefaultContainerWhitelisted = true;
13839                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13840                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13841                }
13842            }
13843            try {
13844                if (dcsUid > 0) {
13845                    am.backgroundWhitelistUid(dcsUid);
13846                }
13847                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13848                        UserHandle.USER_SYSTEM);
13849            } catch (RemoteException e) {
13850            }
13851        }
13852    }
13853
13854    @Override
13855    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
13856            int installFlags, String installerPackageName, int userId) {
13857        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
13858
13859        final int callingUid = Binder.getCallingUid();
13860        enforceCrossUserPermission(callingUid, userId,
13861                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
13862
13863        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13864            try {
13865                if (observer != null) {
13866                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
13867                }
13868            } catch (RemoteException re) {
13869            }
13870            return;
13871        }
13872
13873        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
13874            installFlags |= PackageManager.INSTALL_FROM_ADB;
13875
13876        } else {
13877            // Caller holds INSTALL_PACKAGES permission, so we're less strict
13878            // about installerPackageName.
13879
13880            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
13881            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
13882        }
13883
13884        UserHandle user;
13885        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
13886            user = UserHandle.ALL;
13887        } else {
13888            user = new UserHandle(userId);
13889        }
13890
13891        // Only system components can circumvent runtime permissions when installing.
13892        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
13893                && mContext.checkCallingOrSelfPermission(Manifest.permission
13894                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
13895            throw new SecurityException("You need the "
13896                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
13897                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
13898        }
13899
13900        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
13901                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13902            throw new IllegalArgumentException(
13903                    "New installs into ASEC containers no longer supported");
13904        }
13905
13906        final File originFile = new File(originPath);
13907        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
13908
13909        final Message msg = mHandler.obtainMessage(INIT_COPY);
13910        final VerificationInfo verificationInfo = new VerificationInfo(
13911                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
13912        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
13913                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
13914                null /*packageAbiOverride*/, null /*grantedPermissions*/,
13915                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
13916        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
13917        msg.obj = params;
13918
13919        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
13920                System.identityHashCode(msg.obj));
13921        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13922                System.identityHashCode(msg.obj));
13923
13924        mHandler.sendMessage(msg);
13925    }
13926
13927
13928    /**
13929     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13930     * it is acting on behalf on an enterprise or the user).
13931     *
13932     * Note that the ordering of the conditionals in this method is important. The checks we perform
13933     * are as follows, in this order:
13934     *
13935     * 1) If the install is being performed by a system app, we can trust the app to have set the
13936     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13937     *    what it is.
13938     * 2) If the install is being performed by a device or profile owner app, the install reason
13939     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13940     *    set the install reason correctly. If the app targets an older SDK version where install
13941     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13942     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13943     * 3) In all other cases, the install is being performed by a regular app that is neither part
13944     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13945     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13946     *    set to enterprise policy and if so, change it to unknown instead.
13947     */
13948    private int fixUpInstallReason(String installerPackageName, int installerUid,
13949            int installReason) {
13950        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13951                == PERMISSION_GRANTED) {
13952            // If the install is being performed by a system app, we trust that app to have set the
13953            // install reason correctly.
13954            return installReason;
13955        }
13956
13957        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13958            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13959        if (dpm != null) {
13960            ComponentName owner = null;
13961            try {
13962                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13963                if (owner == null) {
13964                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13965                }
13966            } catch (RemoteException e) {
13967            }
13968            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13969                // If the install is being performed by a device or profile owner, the install
13970                // reason should be enterprise policy.
13971                return PackageManager.INSTALL_REASON_POLICY;
13972            }
13973        }
13974
13975        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13976            // If the install is being performed by a regular app (i.e. neither system app nor
13977            // device or profile owner), we have no reason to believe that the app is acting on
13978            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13979            // change it to unknown instead.
13980            return PackageManager.INSTALL_REASON_UNKNOWN;
13981        }
13982
13983        // If the install is being performed by a regular app and the install reason was set to any
13984        // value but enterprise policy, leave the install reason unchanged.
13985        return installReason;
13986    }
13987
13988    void installStage(String packageName, File stagedDir, String stagedCid,
13989            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13990            String installerPackageName, int installerUid, UserHandle user,
13991            Certificate[][] certificates) {
13992        if (DEBUG_EPHEMERAL) {
13993            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13994                Slog.d(TAG, "Ephemeral install of " + packageName);
13995            }
13996        }
13997        final VerificationInfo verificationInfo = new VerificationInfo(
13998                sessionParams.originatingUri, sessionParams.referrerUri,
13999                sessionParams.originatingUid, installerUid);
14000
14001        final OriginInfo origin;
14002        if (stagedDir != null) {
14003            origin = OriginInfo.fromStagedFile(stagedDir);
14004        } else {
14005            origin = OriginInfo.fromStagedContainer(stagedCid);
14006        }
14007
14008        final Message msg = mHandler.obtainMessage(INIT_COPY);
14009        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14010                sessionParams.installReason);
14011        final InstallParams params = new InstallParams(origin, null, observer,
14012                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14013                verificationInfo, user, sessionParams.abiOverride,
14014                sessionParams.grantedRuntimePermissions, certificates, installReason);
14015        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14016        msg.obj = params;
14017
14018        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14019                System.identityHashCode(msg.obj));
14020        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14021                System.identityHashCode(msg.obj));
14022
14023        mHandler.sendMessage(msg);
14024    }
14025
14026    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14027            int userId) {
14028        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14029        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
14030
14031        // Send a session commit broadcast
14032        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14033        info.installReason = pkgSetting.getInstallReason(userId);
14034        info.appPackageName = packageName;
14035        sendSessionCommitBroadcast(info, userId);
14036    }
14037
14038    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
14039        if (ArrayUtils.isEmpty(userIds)) {
14040            return;
14041        }
14042        Bundle extras = new Bundle(1);
14043        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14044        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14045
14046        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14047                packageName, extras, 0, null, null, userIds);
14048        if (isSystem) {
14049            mHandler.post(() -> {
14050                        for (int userId : userIds) {
14051                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
14052                        }
14053                    }
14054            );
14055        }
14056    }
14057
14058    /**
14059     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14060     * automatically without needing an explicit launch.
14061     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14062     */
14063    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
14064        // If user is not running, the app didn't miss any broadcast
14065        if (!mUserManagerInternal.isUserRunning(userId)) {
14066            return;
14067        }
14068        final IActivityManager am = ActivityManager.getService();
14069        try {
14070            // Deliver LOCKED_BOOT_COMPLETED first
14071            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14072                    .setPackage(packageName);
14073            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14074            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14075                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14076
14077            // Deliver BOOT_COMPLETED only if user is unlocked
14078            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14079                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14080                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14081                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14082            }
14083        } catch (RemoteException e) {
14084            throw e.rethrowFromSystemServer();
14085        }
14086    }
14087
14088    @Override
14089    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14090            int userId) {
14091        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14092        PackageSetting pkgSetting;
14093        final int uid = Binder.getCallingUid();
14094        enforceCrossUserPermission(uid, userId,
14095                true /* requireFullPermission */, true /* checkShell */,
14096                "setApplicationHiddenSetting for user " + userId);
14097
14098        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14099            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14100            return false;
14101        }
14102
14103        long callingId = Binder.clearCallingIdentity();
14104        try {
14105            boolean sendAdded = false;
14106            boolean sendRemoved = false;
14107            // writer
14108            synchronized (mPackages) {
14109                pkgSetting = mSettings.mPackages.get(packageName);
14110                if (pkgSetting == null) {
14111                    return false;
14112                }
14113                // Do not allow "android" is being disabled
14114                if ("android".equals(packageName)) {
14115                    Slog.w(TAG, "Cannot hide package: android");
14116                    return false;
14117                }
14118                // Cannot hide static shared libs as they are considered
14119                // a part of the using app (emulating static linking). Also
14120                // static libs are installed always on internal storage.
14121                PackageParser.Package pkg = mPackages.get(packageName);
14122                if (pkg != null && pkg.staticSharedLibName != null) {
14123                    Slog.w(TAG, "Cannot hide package: " + packageName
14124                            + " providing static shared library: "
14125                            + pkg.staticSharedLibName);
14126                    return false;
14127                }
14128                // Only allow protected packages to hide themselves.
14129                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
14130                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14131                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14132                    return false;
14133                }
14134
14135                if (pkgSetting.getHidden(userId) != hidden) {
14136                    pkgSetting.setHidden(hidden, userId);
14137                    mSettings.writePackageRestrictionsLPr(userId);
14138                    if (hidden) {
14139                        sendRemoved = true;
14140                    } else {
14141                        sendAdded = true;
14142                    }
14143                }
14144            }
14145            if (sendAdded) {
14146                sendPackageAddedForUser(packageName, pkgSetting, userId);
14147                return true;
14148            }
14149            if (sendRemoved) {
14150                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14151                        "hiding pkg");
14152                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14153                return true;
14154            }
14155        } finally {
14156            Binder.restoreCallingIdentity(callingId);
14157        }
14158        return false;
14159    }
14160
14161    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14162            int userId) {
14163        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14164        info.removedPackage = packageName;
14165        info.installerPackageName = pkgSetting.installerPackageName;
14166        info.removedUsers = new int[] {userId};
14167        info.broadcastUsers = new int[] {userId};
14168        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14169        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14170    }
14171
14172    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14173        if (pkgList.length > 0) {
14174            Bundle extras = new Bundle(1);
14175            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14176
14177            sendPackageBroadcast(
14178                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14179                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14180                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14181                    new int[] {userId});
14182        }
14183    }
14184
14185    /**
14186     * Returns true if application is not found or there was an error. Otherwise it returns
14187     * the hidden state of the package for the given user.
14188     */
14189    @Override
14190    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14191        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14192        enforceCrossUserPermission(Binder.getCallingUid(), userId,
14193                true /* requireFullPermission */, false /* checkShell */,
14194                "getApplicationHidden for user " + userId);
14195        PackageSetting pkgSetting;
14196        long callingId = Binder.clearCallingIdentity();
14197        try {
14198            // writer
14199            synchronized (mPackages) {
14200                pkgSetting = mSettings.mPackages.get(packageName);
14201                if (pkgSetting == null) {
14202                    return true;
14203                }
14204                return pkgSetting.getHidden(userId);
14205            }
14206        } finally {
14207            Binder.restoreCallingIdentity(callingId);
14208        }
14209    }
14210
14211    /**
14212     * @hide
14213     */
14214    @Override
14215    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14216            int installReason) {
14217        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14218                null);
14219        PackageSetting pkgSetting;
14220        final int uid = Binder.getCallingUid();
14221        enforceCrossUserPermission(uid, userId,
14222                true /* requireFullPermission */, true /* checkShell */,
14223                "installExistingPackage for user " + userId);
14224        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14225            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14226        }
14227
14228        long callingId = Binder.clearCallingIdentity();
14229        try {
14230            boolean installed = false;
14231            final boolean instantApp =
14232                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14233            final boolean fullApp =
14234                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14235
14236            // writer
14237            synchronized (mPackages) {
14238                pkgSetting = mSettings.mPackages.get(packageName);
14239                if (pkgSetting == null) {
14240                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14241                }
14242                if (!pkgSetting.getInstalled(userId)) {
14243                    pkgSetting.setInstalled(true, userId);
14244                    pkgSetting.setHidden(false, userId);
14245                    pkgSetting.setInstallReason(installReason, userId);
14246                    mSettings.writePackageRestrictionsLPr(userId);
14247                    mSettings.writeKernelMappingLPr(pkgSetting);
14248                    installed = true;
14249                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14250                    // upgrade app from instant to full; we don't allow app downgrade
14251                    installed = true;
14252                }
14253                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14254            }
14255
14256            if (installed) {
14257                if (pkgSetting.pkg != null) {
14258                    synchronized (mInstallLock) {
14259                        // We don't need to freeze for a brand new install
14260                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14261                    }
14262                }
14263                sendPackageAddedForUser(packageName, pkgSetting, userId);
14264                synchronized (mPackages) {
14265                    updateSequenceNumberLP(packageName, new int[]{ userId });
14266                }
14267            }
14268        } finally {
14269            Binder.restoreCallingIdentity(callingId);
14270        }
14271
14272        return PackageManager.INSTALL_SUCCEEDED;
14273    }
14274
14275    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14276            boolean instantApp, boolean fullApp) {
14277        // no state specified; do nothing
14278        if (!instantApp && !fullApp) {
14279            return;
14280        }
14281        if (userId != UserHandle.USER_ALL) {
14282            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14283                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14284            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14285                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14286            }
14287        } else {
14288            for (int currentUserId : sUserManager.getUserIds()) {
14289                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14290                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14291                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14292                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14293                }
14294            }
14295        }
14296    }
14297
14298    boolean isUserRestricted(int userId, String restrictionKey) {
14299        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14300        if (restrictions.getBoolean(restrictionKey, false)) {
14301            Log.w(TAG, "User is restricted: " + restrictionKey);
14302            return true;
14303        }
14304        return false;
14305    }
14306
14307    @Override
14308    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14309            int userId) {
14310        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14311        enforceCrossUserPermission(Binder.getCallingUid(), userId,
14312                true /* requireFullPermission */, true /* checkShell */,
14313                "setPackagesSuspended for user " + userId);
14314
14315        if (ArrayUtils.isEmpty(packageNames)) {
14316            return packageNames;
14317        }
14318
14319        // List of package names for whom the suspended state has changed.
14320        List<String> changedPackages = new ArrayList<>(packageNames.length);
14321        // List of package names for whom the suspended state is not set as requested in this
14322        // method.
14323        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14324        long callingId = Binder.clearCallingIdentity();
14325        try {
14326            for (int i = 0; i < packageNames.length; i++) {
14327                String packageName = packageNames[i];
14328                boolean changed = false;
14329                final int appId;
14330                synchronized (mPackages) {
14331                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14332                    if (pkgSetting == null) {
14333                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14334                                + "\". Skipping suspending/un-suspending.");
14335                        unactionedPackages.add(packageName);
14336                        continue;
14337                    }
14338                    appId = pkgSetting.appId;
14339                    if (pkgSetting.getSuspended(userId) != suspended) {
14340                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14341                            unactionedPackages.add(packageName);
14342                            continue;
14343                        }
14344                        pkgSetting.setSuspended(suspended, userId);
14345                        mSettings.writePackageRestrictionsLPr(userId);
14346                        changed = true;
14347                        changedPackages.add(packageName);
14348                    }
14349                }
14350
14351                if (changed && suspended) {
14352                    killApplication(packageName, UserHandle.getUid(userId, appId),
14353                            "suspending package");
14354                }
14355            }
14356        } finally {
14357            Binder.restoreCallingIdentity(callingId);
14358        }
14359
14360        if (!changedPackages.isEmpty()) {
14361            sendPackagesSuspendedForUser(changedPackages.toArray(
14362                    new String[changedPackages.size()]), userId, suspended);
14363        }
14364
14365        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14366    }
14367
14368    @Override
14369    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14370        final int callingUid = Binder.getCallingUid();
14371        enforceCrossUserPermission(callingUid, userId,
14372                true /* requireFullPermission */, false /* checkShell */,
14373                "isPackageSuspendedForUser for user " + userId);
14374        synchronized (mPackages) {
14375            final PackageSetting ps = mSettings.mPackages.get(packageName);
14376            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14377                throw new IllegalArgumentException("Unknown target package: " + packageName);
14378            }
14379            return ps.getSuspended(userId);
14380        }
14381    }
14382
14383    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14384        if (isPackageDeviceAdmin(packageName, userId)) {
14385            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14386                    + "\": has an active device admin");
14387            return false;
14388        }
14389
14390        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14391        if (packageName.equals(activeLauncherPackageName)) {
14392            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14393                    + "\": contains the active launcher");
14394            return false;
14395        }
14396
14397        if (packageName.equals(mRequiredInstallerPackage)) {
14398            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14399                    + "\": required for package installation");
14400            return false;
14401        }
14402
14403        if (packageName.equals(mRequiredUninstallerPackage)) {
14404            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14405                    + "\": required for package uninstallation");
14406            return false;
14407        }
14408
14409        if (packageName.equals(mRequiredVerifierPackage)) {
14410            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14411                    + "\": required for package verification");
14412            return false;
14413        }
14414
14415        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14416            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14417                    + "\": is the default dialer");
14418            return false;
14419        }
14420
14421        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14422            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14423                    + "\": protected package");
14424            return false;
14425        }
14426
14427        // Cannot suspend static shared libs as they are considered
14428        // a part of the using app (emulating static linking). Also
14429        // static libs are installed always on internal storage.
14430        PackageParser.Package pkg = mPackages.get(packageName);
14431        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14432            Slog.w(TAG, "Cannot suspend package: " + packageName
14433                    + " providing static shared library: "
14434                    + pkg.staticSharedLibName);
14435            return false;
14436        }
14437
14438        return true;
14439    }
14440
14441    private String getActiveLauncherPackageName(int userId) {
14442        Intent intent = new Intent(Intent.ACTION_MAIN);
14443        intent.addCategory(Intent.CATEGORY_HOME);
14444        ResolveInfo resolveInfo = resolveIntent(
14445                intent,
14446                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14447                PackageManager.MATCH_DEFAULT_ONLY,
14448                userId);
14449
14450        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14451    }
14452
14453    private String getDefaultDialerPackageName(int userId) {
14454        synchronized (mPackages) {
14455            return mSettings.getDefaultDialerPackageNameLPw(userId);
14456        }
14457    }
14458
14459    @Override
14460    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14461        mContext.enforceCallingOrSelfPermission(
14462                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14463                "Only package verification agents can verify applications");
14464
14465        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14466        final PackageVerificationResponse response = new PackageVerificationResponse(
14467                verificationCode, Binder.getCallingUid());
14468        msg.arg1 = id;
14469        msg.obj = response;
14470        mHandler.sendMessage(msg);
14471    }
14472
14473    @Override
14474    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14475            long millisecondsToDelay) {
14476        mContext.enforceCallingOrSelfPermission(
14477                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14478                "Only package verification agents can extend verification timeouts");
14479
14480        final PackageVerificationState state = mPendingVerification.get(id);
14481        final PackageVerificationResponse response = new PackageVerificationResponse(
14482                verificationCodeAtTimeout, Binder.getCallingUid());
14483
14484        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14485            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14486        }
14487        if (millisecondsToDelay < 0) {
14488            millisecondsToDelay = 0;
14489        }
14490        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14491                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14492            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14493        }
14494
14495        if ((state != null) && !state.timeoutExtended()) {
14496            state.extendTimeout();
14497
14498            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14499            msg.arg1 = id;
14500            msg.obj = response;
14501            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14502        }
14503    }
14504
14505    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14506            int verificationCode, UserHandle user) {
14507        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14508        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14509        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14510        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14511        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14512
14513        mContext.sendBroadcastAsUser(intent, user,
14514                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14515    }
14516
14517    private ComponentName matchComponentForVerifier(String packageName,
14518            List<ResolveInfo> receivers) {
14519        ActivityInfo targetReceiver = null;
14520
14521        final int NR = receivers.size();
14522        for (int i = 0; i < NR; i++) {
14523            final ResolveInfo info = receivers.get(i);
14524            if (info.activityInfo == null) {
14525                continue;
14526            }
14527
14528            if (packageName.equals(info.activityInfo.packageName)) {
14529                targetReceiver = info.activityInfo;
14530                break;
14531            }
14532        }
14533
14534        if (targetReceiver == null) {
14535            return null;
14536        }
14537
14538        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14539    }
14540
14541    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14542            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14543        if (pkgInfo.verifiers.length == 0) {
14544            return null;
14545        }
14546
14547        final int N = pkgInfo.verifiers.length;
14548        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14549        for (int i = 0; i < N; i++) {
14550            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14551
14552            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14553                    receivers);
14554            if (comp == null) {
14555                continue;
14556            }
14557
14558            final int verifierUid = getUidForVerifier(verifierInfo);
14559            if (verifierUid == -1) {
14560                continue;
14561            }
14562
14563            if (DEBUG_VERIFY) {
14564                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14565                        + " with the correct signature");
14566            }
14567            sufficientVerifiers.add(comp);
14568            verificationState.addSufficientVerifier(verifierUid);
14569        }
14570
14571        return sufficientVerifiers;
14572    }
14573
14574    private int getUidForVerifier(VerifierInfo verifierInfo) {
14575        synchronized (mPackages) {
14576            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14577            if (pkg == null) {
14578                return -1;
14579            } else if (pkg.mSignatures.length != 1) {
14580                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14581                        + " has more than one signature; ignoring");
14582                return -1;
14583            }
14584
14585            /*
14586             * If the public key of the package's signature does not match
14587             * our expected public key, then this is a different package and
14588             * we should skip.
14589             */
14590
14591            final byte[] expectedPublicKey;
14592            try {
14593                final Signature verifierSig = pkg.mSignatures[0];
14594                final PublicKey publicKey = verifierSig.getPublicKey();
14595                expectedPublicKey = publicKey.getEncoded();
14596            } catch (CertificateException e) {
14597                return -1;
14598            }
14599
14600            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14601
14602            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14603                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14604                        + " does not have the expected public key; ignoring");
14605                return -1;
14606            }
14607
14608            return pkg.applicationInfo.uid;
14609        }
14610    }
14611
14612    @Override
14613    public void finishPackageInstall(int token, boolean didLaunch) {
14614        enforceSystemOrRoot("Only the system is allowed to finish installs");
14615
14616        if (DEBUG_INSTALL) {
14617            Slog.v(TAG, "BM finishing package install for " + token);
14618        }
14619        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14620
14621        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14622        mHandler.sendMessage(msg);
14623    }
14624
14625    /**
14626     * Get the verification agent timeout.  Used for both the APK verifier and the
14627     * intent filter verifier.
14628     *
14629     * @return verification timeout in milliseconds
14630     */
14631    private long getVerificationTimeout() {
14632        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14633                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14634                DEFAULT_VERIFICATION_TIMEOUT);
14635    }
14636
14637    /**
14638     * Get the default verification agent response code.
14639     *
14640     * @return default verification response code
14641     */
14642    private int getDefaultVerificationResponse(UserHandle user) {
14643        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14644            return PackageManager.VERIFICATION_REJECT;
14645        }
14646        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14647                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14648                DEFAULT_VERIFICATION_RESPONSE);
14649    }
14650
14651    /**
14652     * Check whether or not package verification has been enabled.
14653     *
14654     * @return true if verification should be performed
14655     */
14656    private boolean isVerificationEnabled(int userId, int installFlags) {
14657        if (!DEFAULT_VERIFY_ENABLE) {
14658            return false;
14659        }
14660
14661        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14662
14663        // Check if installing from ADB
14664        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14665            // Do not run verification in a test harness environment
14666            if (ActivityManager.isRunningInTestHarness()) {
14667                return false;
14668            }
14669            if (ensureVerifyAppsEnabled) {
14670                return true;
14671            }
14672            // Check if the developer does not want package verification for ADB installs
14673            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14674                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14675                return false;
14676            }
14677        }
14678
14679        if (ensureVerifyAppsEnabled) {
14680            return true;
14681        }
14682
14683        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14684                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14685    }
14686
14687    @Override
14688    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14689            throws RemoteException {
14690        mContext.enforceCallingOrSelfPermission(
14691                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14692                "Only intentfilter verification agents can verify applications");
14693
14694        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14695        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14696                Binder.getCallingUid(), verificationCode, failedDomains);
14697        msg.arg1 = id;
14698        msg.obj = response;
14699        mHandler.sendMessage(msg);
14700    }
14701
14702    @Override
14703    public int getIntentVerificationStatus(String packageName, int userId) {
14704        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14705            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14706        }
14707        synchronized (mPackages) {
14708            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14709        }
14710    }
14711
14712    @Override
14713    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14714        mContext.enforceCallingOrSelfPermission(
14715                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14716
14717        boolean result = false;
14718        synchronized (mPackages) {
14719            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14720        }
14721        if (result) {
14722            scheduleWritePackageRestrictionsLocked(userId);
14723        }
14724        return result;
14725    }
14726
14727    @Override
14728    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14729            String packageName) {
14730        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14731            return ParceledListSlice.emptyList();
14732        }
14733        synchronized (mPackages) {
14734            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14735        }
14736    }
14737
14738    @Override
14739    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14740        if (TextUtils.isEmpty(packageName)) {
14741            return ParceledListSlice.emptyList();
14742        }
14743        final int callingUid = Binder.getCallingUid();
14744        final int callingUserId = UserHandle.getUserId(callingUid);
14745        synchronized (mPackages) {
14746            PackageParser.Package pkg = mPackages.get(packageName);
14747            if (pkg == null || pkg.activities == null) {
14748                return ParceledListSlice.emptyList();
14749            }
14750            if (pkg.mExtras == null) {
14751                return ParceledListSlice.emptyList();
14752            }
14753            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14754            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14755                return ParceledListSlice.emptyList();
14756            }
14757            final int count = pkg.activities.size();
14758            ArrayList<IntentFilter> result = new ArrayList<>();
14759            for (int n=0; n<count; n++) {
14760                PackageParser.Activity activity = pkg.activities.get(n);
14761                if (activity.intents != null && activity.intents.size() > 0) {
14762                    result.addAll(activity.intents);
14763                }
14764            }
14765            return new ParceledListSlice<>(result);
14766        }
14767    }
14768
14769    @Override
14770    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14771        mContext.enforceCallingOrSelfPermission(
14772                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14773
14774        synchronized (mPackages) {
14775            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14776            if (packageName != null) {
14777                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
14778                        packageName, userId);
14779            }
14780            return result;
14781        }
14782    }
14783
14784    @Override
14785    public String getDefaultBrowserPackageName(int userId) {
14786        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14787            return null;
14788        }
14789        synchronized (mPackages) {
14790            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14791        }
14792    }
14793
14794    /**
14795     * Get the "allow unknown sources" setting.
14796     *
14797     * @return the current "allow unknown sources" setting
14798     */
14799    private int getUnknownSourcesSettings() {
14800        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14801                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14802                -1);
14803    }
14804
14805    @Override
14806    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14807        final int callingUid = Binder.getCallingUid();
14808        if (getInstantAppPackageName(callingUid) != null) {
14809            return;
14810        }
14811        // writer
14812        synchronized (mPackages) {
14813            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14814            if (targetPackageSetting == null) {
14815                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14816            }
14817
14818            PackageSetting installerPackageSetting;
14819            if (installerPackageName != null) {
14820                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14821                if (installerPackageSetting == null) {
14822                    throw new IllegalArgumentException("Unknown installer package: "
14823                            + installerPackageName);
14824                }
14825            } else {
14826                installerPackageSetting = null;
14827            }
14828
14829            Signature[] callerSignature;
14830            Object obj = mSettings.getUserIdLPr(callingUid);
14831            if (obj != null) {
14832                if (obj instanceof SharedUserSetting) {
14833                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
14834                } else if (obj instanceof PackageSetting) {
14835                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
14836                } else {
14837                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14838                }
14839            } else {
14840                throw new SecurityException("Unknown calling UID: " + callingUid);
14841            }
14842
14843            // Verify: can't set installerPackageName to a package that is
14844            // not signed with the same cert as the caller.
14845            if (installerPackageSetting != null) {
14846                if (compareSignatures(callerSignature,
14847                        installerPackageSetting.signatures.mSignatures)
14848                        != PackageManager.SIGNATURE_MATCH) {
14849                    throw new SecurityException(
14850                            "Caller does not have same cert as new installer package "
14851                            + installerPackageName);
14852                }
14853            }
14854
14855            // Verify: if target already has an installer package, it must
14856            // be signed with the same cert as the caller.
14857            if (targetPackageSetting.installerPackageName != null) {
14858                PackageSetting setting = mSettings.mPackages.get(
14859                        targetPackageSetting.installerPackageName);
14860                // If the currently set package isn't valid, then it's always
14861                // okay to change it.
14862                if (setting != null) {
14863                    if (compareSignatures(callerSignature,
14864                            setting.signatures.mSignatures)
14865                            != PackageManager.SIGNATURE_MATCH) {
14866                        throw new SecurityException(
14867                                "Caller does not have same cert as old installer package "
14868                                + targetPackageSetting.installerPackageName);
14869                    }
14870                }
14871            }
14872
14873            // Okay!
14874            targetPackageSetting.installerPackageName = installerPackageName;
14875            if (installerPackageName != null) {
14876                mSettings.mInstallerPackages.add(installerPackageName);
14877            }
14878            scheduleWriteSettingsLocked();
14879        }
14880    }
14881
14882    @Override
14883    public void setApplicationCategoryHint(String packageName, int categoryHint,
14884            String callerPackageName) {
14885        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14886            throw new SecurityException("Instant applications don't have access to this method");
14887        }
14888        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14889                callerPackageName);
14890        synchronized (mPackages) {
14891            PackageSetting ps = mSettings.mPackages.get(packageName);
14892            if (ps == null) {
14893                throw new IllegalArgumentException("Unknown target package " + packageName);
14894            }
14895
14896            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14897                throw new IllegalArgumentException("Calling package " + callerPackageName
14898                        + " is not installer for " + packageName);
14899            }
14900
14901            if (ps.categoryHint != categoryHint) {
14902                ps.categoryHint = categoryHint;
14903                scheduleWriteSettingsLocked();
14904            }
14905        }
14906    }
14907
14908    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14909        // Queue up an async operation since the package installation may take a little while.
14910        mHandler.post(new Runnable() {
14911            public void run() {
14912                mHandler.removeCallbacks(this);
14913                 // Result object to be returned
14914                PackageInstalledInfo res = new PackageInstalledInfo();
14915                res.setReturnCode(currentStatus);
14916                res.uid = -1;
14917                res.pkg = null;
14918                res.removedInfo = null;
14919                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14920                    args.doPreInstall(res.returnCode);
14921                    synchronized (mInstallLock) {
14922                        installPackageTracedLI(args, res);
14923                    }
14924                    args.doPostInstall(res.returnCode, res.uid);
14925                }
14926
14927                // A restore should be performed at this point if (a) the install
14928                // succeeded, (b) the operation is not an update, and (c) the new
14929                // package has not opted out of backup participation.
14930                final boolean update = res.removedInfo != null
14931                        && res.removedInfo.removedPackage != null;
14932                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14933                boolean doRestore = !update
14934                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14935
14936                // Set up the post-install work request bookkeeping.  This will be used
14937                // and cleaned up by the post-install event handling regardless of whether
14938                // there's a restore pass performed.  Token values are >= 1.
14939                int token;
14940                if (mNextInstallToken < 0) mNextInstallToken = 1;
14941                token = mNextInstallToken++;
14942
14943                PostInstallData data = new PostInstallData(args, res);
14944                mRunningInstalls.put(token, data);
14945                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14946
14947                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14948                    // Pass responsibility to the Backup Manager.  It will perform a
14949                    // restore if appropriate, then pass responsibility back to the
14950                    // Package Manager to run the post-install observer callbacks
14951                    // and broadcasts.
14952                    IBackupManager bm = IBackupManager.Stub.asInterface(
14953                            ServiceManager.getService(Context.BACKUP_SERVICE));
14954                    if (bm != null) {
14955                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14956                                + " to BM for possible restore");
14957                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14958                        try {
14959                            // TODO: http://b/22388012
14960                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14961                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14962                            } else {
14963                                doRestore = false;
14964                            }
14965                        } catch (RemoteException e) {
14966                            // can't happen; the backup manager is local
14967                        } catch (Exception e) {
14968                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14969                            doRestore = false;
14970                        }
14971                    } else {
14972                        Slog.e(TAG, "Backup Manager not found!");
14973                        doRestore = false;
14974                    }
14975                }
14976
14977                if (!doRestore) {
14978                    // No restore possible, or the Backup Manager was mysteriously not
14979                    // available -- just fire the post-install work request directly.
14980                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14981
14982                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14983
14984                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14985                    mHandler.sendMessage(msg);
14986                }
14987            }
14988        });
14989    }
14990
14991    /**
14992     * Callback from PackageSettings whenever an app is first transitioned out of the
14993     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14994     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14995     * here whether the app is the target of an ongoing install, and only send the
14996     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14997     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14998     * handling.
14999     */
15000    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15001        // Serialize this with the rest of the install-process message chain.  In the
15002        // restore-at-install case, this Runnable will necessarily run before the
15003        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15004        // are coherent.  In the non-restore case, the app has already completed install
15005        // and been launched through some other means, so it is not in a problematic
15006        // state for observers to see the FIRST_LAUNCH signal.
15007        mHandler.post(new Runnable() {
15008            @Override
15009            public void run() {
15010                for (int i = 0; i < mRunningInstalls.size(); i++) {
15011                    final PostInstallData data = mRunningInstalls.valueAt(i);
15012                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15013                        continue;
15014                    }
15015                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15016                        // right package; but is it for the right user?
15017                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15018                            if (userId == data.res.newUsers[uIndex]) {
15019                                if (DEBUG_BACKUP) {
15020                                    Slog.i(TAG, "Package " + pkgName
15021                                            + " being restored so deferring FIRST_LAUNCH");
15022                                }
15023                                return;
15024                            }
15025                        }
15026                    }
15027                }
15028                // didn't find it, so not being restored
15029                if (DEBUG_BACKUP) {
15030                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15031                }
15032                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15033            }
15034        });
15035    }
15036
15037    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15038        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15039                installerPkg, null, userIds);
15040    }
15041
15042    private abstract class HandlerParams {
15043        private static final int MAX_RETRIES = 4;
15044
15045        /**
15046         * Number of times startCopy() has been attempted and had a non-fatal
15047         * error.
15048         */
15049        private int mRetries = 0;
15050
15051        /** User handle for the user requesting the information or installation. */
15052        private final UserHandle mUser;
15053        String traceMethod;
15054        int traceCookie;
15055
15056        HandlerParams(UserHandle user) {
15057            mUser = user;
15058        }
15059
15060        UserHandle getUser() {
15061            return mUser;
15062        }
15063
15064        HandlerParams setTraceMethod(String traceMethod) {
15065            this.traceMethod = traceMethod;
15066            return this;
15067        }
15068
15069        HandlerParams setTraceCookie(int traceCookie) {
15070            this.traceCookie = traceCookie;
15071            return this;
15072        }
15073
15074        final boolean startCopy() {
15075            boolean res;
15076            try {
15077                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15078
15079                if (++mRetries > MAX_RETRIES) {
15080                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15081                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15082                    handleServiceError();
15083                    return false;
15084                } else {
15085                    handleStartCopy();
15086                    res = true;
15087                }
15088            } catch (RemoteException e) {
15089                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15090                mHandler.sendEmptyMessage(MCS_RECONNECT);
15091                res = false;
15092            }
15093            handleReturnCode();
15094            return res;
15095        }
15096
15097        final void serviceError() {
15098            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15099            handleServiceError();
15100            handleReturnCode();
15101        }
15102
15103        abstract void handleStartCopy() throws RemoteException;
15104        abstract void handleServiceError();
15105        abstract void handleReturnCode();
15106    }
15107
15108    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15109        for (File path : paths) {
15110            try {
15111                mcs.clearDirectory(path.getAbsolutePath());
15112            } catch (RemoteException e) {
15113            }
15114        }
15115    }
15116
15117    static class OriginInfo {
15118        /**
15119         * Location where install is coming from, before it has been
15120         * copied/renamed into place. This could be a single monolithic APK
15121         * file, or a cluster directory. This location may be untrusted.
15122         */
15123        final File file;
15124        final String cid;
15125
15126        /**
15127         * Flag indicating that {@link #file} or {@link #cid} has already been
15128         * staged, meaning downstream users don't need to defensively copy the
15129         * contents.
15130         */
15131        final boolean staged;
15132
15133        /**
15134         * Flag indicating that {@link #file} or {@link #cid} is an already
15135         * installed app that is being moved.
15136         */
15137        final boolean existing;
15138
15139        final String resolvedPath;
15140        final File resolvedFile;
15141
15142        static OriginInfo fromNothing() {
15143            return new OriginInfo(null, null, false, false);
15144        }
15145
15146        static OriginInfo fromUntrustedFile(File file) {
15147            return new OriginInfo(file, null, false, false);
15148        }
15149
15150        static OriginInfo fromExistingFile(File file) {
15151            return new OriginInfo(file, null, false, true);
15152        }
15153
15154        static OriginInfo fromStagedFile(File file) {
15155            return new OriginInfo(file, null, true, false);
15156        }
15157
15158        static OriginInfo fromStagedContainer(String cid) {
15159            return new OriginInfo(null, cid, true, false);
15160        }
15161
15162        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15163            this.file = file;
15164            this.cid = cid;
15165            this.staged = staged;
15166            this.existing = existing;
15167
15168            if (cid != null) {
15169                resolvedPath = PackageHelper.getSdDir(cid);
15170                resolvedFile = new File(resolvedPath);
15171            } else if (file != null) {
15172                resolvedPath = file.getAbsolutePath();
15173                resolvedFile = file;
15174            } else {
15175                resolvedPath = null;
15176                resolvedFile = null;
15177            }
15178        }
15179    }
15180
15181    static class MoveInfo {
15182        final int moveId;
15183        final String fromUuid;
15184        final String toUuid;
15185        final String packageName;
15186        final String dataAppName;
15187        final int appId;
15188        final String seinfo;
15189        final int targetSdkVersion;
15190
15191        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15192                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15193            this.moveId = moveId;
15194            this.fromUuid = fromUuid;
15195            this.toUuid = toUuid;
15196            this.packageName = packageName;
15197            this.dataAppName = dataAppName;
15198            this.appId = appId;
15199            this.seinfo = seinfo;
15200            this.targetSdkVersion = targetSdkVersion;
15201        }
15202    }
15203
15204    static class VerificationInfo {
15205        /** A constant used to indicate that a uid value is not present. */
15206        public static final int NO_UID = -1;
15207
15208        /** URI referencing where the package was downloaded from. */
15209        final Uri originatingUri;
15210
15211        /** HTTP referrer URI associated with the originatingURI. */
15212        final Uri referrer;
15213
15214        /** UID of the application that the install request originated from. */
15215        final int originatingUid;
15216
15217        /** UID of application requesting the install */
15218        final int installerUid;
15219
15220        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15221            this.originatingUri = originatingUri;
15222            this.referrer = referrer;
15223            this.originatingUid = originatingUid;
15224            this.installerUid = installerUid;
15225        }
15226    }
15227
15228    class InstallParams extends HandlerParams {
15229        final OriginInfo origin;
15230        final MoveInfo move;
15231        final IPackageInstallObserver2 observer;
15232        int installFlags;
15233        final String installerPackageName;
15234        final String volumeUuid;
15235        private InstallArgs mArgs;
15236        private int mRet;
15237        final String packageAbiOverride;
15238        final String[] grantedRuntimePermissions;
15239        final VerificationInfo verificationInfo;
15240        final Certificate[][] certificates;
15241        final int installReason;
15242
15243        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15244                int installFlags, String installerPackageName, String volumeUuid,
15245                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15246                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15247            super(user);
15248            this.origin = origin;
15249            this.move = move;
15250            this.observer = observer;
15251            this.installFlags = installFlags;
15252            this.installerPackageName = installerPackageName;
15253            this.volumeUuid = volumeUuid;
15254            this.verificationInfo = verificationInfo;
15255            this.packageAbiOverride = packageAbiOverride;
15256            this.grantedRuntimePermissions = grantedPermissions;
15257            this.certificates = certificates;
15258            this.installReason = installReason;
15259        }
15260
15261        @Override
15262        public String toString() {
15263            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15264                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15265        }
15266
15267        private int installLocationPolicy(PackageInfoLite pkgLite) {
15268            String packageName = pkgLite.packageName;
15269            int installLocation = pkgLite.installLocation;
15270            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15271            // reader
15272            synchronized (mPackages) {
15273                // Currently installed package which the new package is attempting to replace or
15274                // null if no such package is installed.
15275                PackageParser.Package installedPkg = mPackages.get(packageName);
15276                // Package which currently owns the data which the new package will own if installed.
15277                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15278                // will be null whereas dataOwnerPkg will contain information about the package
15279                // which was uninstalled while keeping its data.
15280                PackageParser.Package dataOwnerPkg = installedPkg;
15281                if (dataOwnerPkg  == null) {
15282                    PackageSetting ps = mSettings.mPackages.get(packageName);
15283                    if (ps != null) {
15284                        dataOwnerPkg = ps.pkg;
15285                    }
15286                }
15287
15288                if (dataOwnerPkg != null) {
15289                    // If installed, the package will get access to data left on the device by its
15290                    // predecessor. As a security measure, this is permited only if this is not a
15291                    // version downgrade or if the predecessor package is marked as debuggable and
15292                    // a downgrade is explicitly requested.
15293                    //
15294                    // On debuggable platform builds, downgrades are permitted even for
15295                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15296                    // not offer security guarantees and thus it's OK to disable some security
15297                    // mechanisms to make debugging/testing easier on those builds. However, even on
15298                    // debuggable builds downgrades of packages are permitted only if requested via
15299                    // installFlags. This is because we aim to keep the behavior of debuggable
15300                    // platform builds as close as possible to the behavior of non-debuggable
15301                    // platform builds.
15302                    final boolean downgradeRequested =
15303                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15304                    final boolean packageDebuggable =
15305                                (dataOwnerPkg.applicationInfo.flags
15306                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15307                    final boolean downgradePermitted =
15308                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15309                    if (!downgradePermitted) {
15310                        try {
15311                            checkDowngrade(dataOwnerPkg, pkgLite);
15312                        } catch (PackageManagerException e) {
15313                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15314                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15315                        }
15316                    }
15317                }
15318
15319                if (installedPkg != null) {
15320                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15321                        // Check for updated system application.
15322                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15323                            if (onSd) {
15324                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15325                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15326                            }
15327                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15328                        } else {
15329                            if (onSd) {
15330                                // Install flag overrides everything.
15331                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15332                            }
15333                            // If current upgrade specifies particular preference
15334                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15335                                // Application explicitly specified internal.
15336                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15337                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15338                                // App explictly prefers external. Let policy decide
15339                            } else {
15340                                // Prefer previous location
15341                                if (isExternal(installedPkg)) {
15342                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15343                                }
15344                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15345                            }
15346                        }
15347                    } else {
15348                        // Invalid install. Return error code
15349                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15350                    }
15351                }
15352            }
15353            // All the special cases have been taken care of.
15354            // Return result based on recommended install location.
15355            if (onSd) {
15356                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15357            }
15358            return pkgLite.recommendedInstallLocation;
15359        }
15360
15361        /*
15362         * Invoke remote method to get package information and install
15363         * location values. Override install location based on default
15364         * policy if needed and then create install arguments based
15365         * on the install location.
15366         */
15367        public void handleStartCopy() throws RemoteException {
15368            int ret = PackageManager.INSTALL_SUCCEEDED;
15369
15370            // If we're already staged, we've firmly committed to an install location
15371            if (origin.staged) {
15372                if (origin.file != null) {
15373                    installFlags |= PackageManager.INSTALL_INTERNAL;
15374                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15375                } else if (origin.cid != null) {
15376                    installFlags |= PackageManager.INSTALL_EXTERNAL;
15377                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
15378                } else {
15379                    throw new IllegalStateException("Invalid stage location");
15380                }
15381            }
15382
15383            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15384            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15385            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15386            PackageInfoLite pkgLite = null;
15387
15388            if (onInt && onSd) {
15389                // Check if both bits are set.
15390                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15391                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15392            } else if (onSd && ephemeral) {
15393                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15394                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15395            } else {
15396                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15397                        packageAbiOverride);
15398
15399                if (DEBUG_EPHEMERAL && ephemeral) {
15400                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15401                }
15402
15403                /*
15404                 * If we have too little free space, try to free cache
15405                 * before giving up.
15406                 */
15407                if (!origin.staged && pkgLite.recommendedInstallLocation
15408                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15409                    // TODO: focus freeing disk space on the target device
15410                    final StorageManager storage = StorageManager.from(mContext);
15411                    final long lowThreshold = storage.getStorageLowBytes(
15412                            Environment.getDataDirectory());
15413
15414                    final long sizeBytes = mContainerService.calculateInstalledSize(
15415                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
15416
15417                    try {
15418                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
15419                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15420                                installFlags, packageAbiOverride);
15421                    } catch (InstallerException e) {
15422                        Slog.w(TAG, "Failed to free cache", e);
15423                    }
15424
15425                    /*
15426                     * The cache free must have deleted the file we
15427                     * downloaded to install.
15428                     *
15429                     * TODO: fix the "freeCache" call to not delete
15430                     *       the file we care about.
15431                     */
15432                    if (pkgLite.recommendedInstallLocation
15433                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15434                        pkgLite.recommendedInstallLocation
15435                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15436                    }
15437                }
15438            }
15439
15440            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15441                int loc = pkgLite.recommendedInstallLocation;
15442                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15443                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15444                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15445                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15446                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15447                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15448                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15449                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15450                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15451                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15452                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15453                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15454                } else {
15455                    // Override with defaults if needed.
15456                    loc = installLocationPolicy(pkgLite);
15457                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15458                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15459                    } else if (!onSd && !onInt) {
15460                        // Override install location with flags
15461                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15462                            // Set the flag to install on external media.
15463                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15464                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15465                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15466                            if (DEBUG_EPHEMERAL) {
15467                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15468                            }
15469                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15470                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15471                                    |PackageManager.INSTALL_INTERNAL);
15472                        } else {
15473                            // Make sure the flag for installing on external
15474                            // media is unset
15475                            installFlags |= PackageManager.INSTALL_INTERNAL;
15476                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15477                        }
15478                    }
15479                }
15480            }
15481
15482            final InstallArgs args = createInstallArgs(this);
15483            mArgs = args;
15484
15485            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15486                // TODO: http://b/22976637
15487                // Apps installed for "all" users use the device owner to verify the app
15488                UserHandle verifierUser = getUser();
15489                if (verifierUser == UserHandle.ALL) {
15490                    verifierUser = UserHandle.SYSTEM;
15491                }
15492
15493                /*
15494                 * Determine if we have any installed package verifiers. If we
15495                 * do, then we'll defer to them to verify the packages.
15496                 */
15497                final int requiredUid = mRequiredVerifierPackage == null ? -1
15498                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15499                                verifierUser.getIdentifier());
15500                if (!origin.existing && requiredUid != -1
15501                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
15502                    final Intent verification = new Intent(
15503                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15504                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15505                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15506                            PACKAGE_MIME_TYPE);
15507                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15508
15509                    // Query all live verifiers based on current user state
15510                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15511                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15512
15513                    if (DEBUG_VERIFY) {
15514                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15515                                + verification.toString() + " with " + pkgLite.verifiers.length
15516                                + " optional verifiers");
15517                    }
15518
15519                    final int verificationId = mPendingVerificationToken++;
15520
15521                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15522
15523                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15524                            installerPackageName);
15525
15526                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15527                            installFlags);
15528
15529                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15530                            pkgLite.packageName);
15531
15532                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15533                            pkgLite.versionCode);
15534
15535                    if (verificationInfo != null) {
15536                        if (verificationInfo.originatingUri != null) {
15537                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15538                                    verificationInfo.originatingUri);
15539                        }
15540                        if (verificationInfo.referrer != null) {
15541                            verification.putExtra(Intent.EXTRA_REFERRER,
15542                                    verificationInfo.referrer);
15543                        }
15544                        if (verificationInfo.originatingUid >= 0) {
15545                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15546                                    verificationInfo.originatingUid);
15547                        }
15548                        if (verificationInfo.installerUid >= 0) {
15549                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15550                                    verificationInfo.installerUid);
15551                        }
15552                    }
15553
15554                    final PackageVerificationState verificationState = new PackageVerificationState(
15555                            requiredUid, args);
15556
15557                    mPendingVerification.append(verificationId, verificationState);
15558
15559                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15560                            receivers, verificationState);
15561
15562                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15563                    final long idleDuration = getVerificationTimeout();
15564
15565                    /*
15566                     * If any sufficient verifiers were listed in the package
15567                     * manifest, attempt to ask them.
15568                     */
15569                    if (sufficientVerifiers != null) {
15570                        final int N = sufficientVerifiers.size();
15571                        if (N == 0) {
15572                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15573                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15574                        } else {
15575                            for (int i = 0; i < N; i++) {
15576                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15577                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15578                                        verifierComponent.getPackageName(), idleDuration,
15579                                        verifierUser.getIdentifier(), false, "package verifier");
15580
15581                                final Intent sufficientIntent = new Intent(verification);
15582                                sufficientIntent.setComponent(verifierComponent);
15583                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15584                            }
15585                        }
15586                    }
15587
15588                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15589                            mRequiredVerifierPackage, receivers);
15590                    if (ret == PackageManager.INSTALL_SUCCEEDED
15591                            && mRequiredVerifierPackage != null) {
15592                        Trace.asyncTraceBegin(
15593                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15594                        /*
15595                         * Send the intent to the required verification agent,
15596                         * but only start the verification timeout after the
15597                         * target BroadcastReceivers have run.
15598                         */
15599                        verification.setComponent(requiredVerifierComponent);
15600                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15601                                mRequiredVerifierPackage, idleDuration,
15602                                verifierUser.getIdentifier(), false, "package verifier");
15603                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15604                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15605                                new BroadcastReceiver() {
15606                                    @Override
15607                                    public void onReceive(Context context, Intent intent) {
15608                                        final Message msg = mHandler
15609                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15610                                        msg.arg1 = verificationId;
15611                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15612                                    }
15613                                }, null, 0, null, null);
15614
15615                        /*
15616                         * We don't want the copy to proceed until verification
15617                         * succeeds, so null out this field.
15618                         */
15619                        mArgs = null;
15620                    }
15621                } else {
15622                    /*
15623                     * No package verification is enabled, so immediately start
15624                     * the remote call to initiate copy using temporary file.
15625                     */
15626                    ret = args.copyApk(mContainerService, true);
15627                }
15628            }
15629
15630            mRet = ret;
15631        }
15632
15633        @Override
15634        void handleReturnCode() {
15635            // If mArgs is null, then MCS couldn't be reached. When it
15636            // reconnects, it will try again to install. At that point, this
15637            // will succeed.
15638            if (mArgs != null) {
15639                processPendingInstall(mArgs, mRet);
15640            }
15641        }
15642
15643        @Override
15644        void handleServiceError() {
15645            mArgs = createInstallArgs(this);
15646            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15647        }
15648
15649        public boolean isForwardLocked() {
15650            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15651        }
15652    }
15653
15654    /**
15655     * Used during creation of InstallArgs
15656     *
15657     * @param installFlags package installation flags
15658     * @return true if should be installed on external storage
15659     */
15660    private static boolean installOnExternalAsec(int installFlags) {
15661        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
15662            return false;
15663        }
15664        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
15665            return true;
15666        }
15667        return false;
15668    }
15669
15670    /**
15671     * Used during creation of InstallArgs
15672     *
15673     * @param installFlags package installation flags
15674     * @return true if should be installed as forward locked
15675     */
15676    private static boolean installForwardLocked(int installFlags) {
15677        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15678    }
15679
15680    private InstallArgs createInstallArgs(InstallParams params) {
15681        if (params.move != null) {
15682            return new MoveInstallArgs(params);
15683        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
15684            return new AsecInstallArgs(params);
15685        } else {
15686            return new FileInstallArgs(params);
15687        }
15688    }
15689
15690    /**
15691     * Create args that describe an existing installed package. Typically used
15692     * when cleaning up old installs, or used as a move source.
15693     */
15694    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15695            String resourcePath, String[] instructionSets) {
15696        final boolean isInAsec;
15697        if (installOnExternalAsec(installFlags)) {
15698            /* Apps on SD card are always in ASEC containers. */
15699            isInAsec = true;
15700        } else if (installForwardLocked(installFlags)
15701                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
15702            /*
15703             * Forward-locked apps are only in ASEC containers if they're the
15704             * new style
15705             */
15706            isInAsec = true;
15707        } else {
15708            isInAsec = false;
15709        }
15710
15711        if (isInAsec) {
15712            return new AsecInstallArgs(codePath, instructionSets,
15713                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
15714        } else {
15715            return new FileInstallArgs(codePath, resourcePath, instructionSets);
15716        }
15717    }
15718
15719    static abstract class InstallArgs {
15720        /** @see InstallParams#origin */
15721        final OriginInfo origin;
15722        /** @see InstallParams#move */
15723        final MoveInfo move;
15724
15725        final IPackageInstallObserver2 observer;
15726        // Always refers to PackageManager flags only
15727        final int installFlags;
15728        final String installerPackageName;
15729        final String volumeUuid;
15730        final UserHandle user;
15731        final String abiOverride;
15732        final String[] installGrantPermissions;
15733        /** If non-null, drop an async trace when the install completes */
15734        final String traceMethod;
15735        final int traceCookie;
15736        final Certificate[][] certificates;
15737        final int installReason;
15738
15739        // The list of instruction sets supported by this app. This is currently
15740        // only used during the rmdex() phase to clean up resources. We can get rid of this
15741        // if we move dex files under the common app path.
15742        /* nullable */ String[] instructionSets;
15743
15744        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15745                int installFlags, String installerPackageName, String volumeUuid,
15746                UserHandle user, String[] instructionSets,
15747                String abiOverride, String[] installGrantPermissions,
15748                String traceMethod, int traceCookie, Certificate[][] certificates,
15749                int installReason) {
15750            this.origin = origin;
15751            this.move = move;
15752            this.installFlags = installFlags;
15753            this.observer = observer;
15754            this.installerPackageName = installerPackageName;
15755            this.volumeUuid = volumeUuid;
15756            this.user = user;
15757            this.instructionSets = instructionSets;
15758            this.abiOverride = abiOverride;
15759            this.installGrantPermissions = installGrantPermissions;
15760            this.traceMethod = traceMethod;
15761            this.traceCookie = traceCookie;
15762            this.certificates = certificates;
15763            this.installReason = installReason;
15764        }
15765
15766        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15767        abstract int doPreInstall(int status);
15768
15769        /**
15770         * Rename package into final resting place. All paths on the given
15771         * scanned package should be updated to reflect the rename.
15772         */
15773        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15774        abstract int doPostInstall(int status, int uid);
15775
15776        /** @see PackageSettingBase#codePathString */
15777        abstract String getCodePath();
15778        /** @see PackageSettingBase#resourcePathString */
15779        abstract String getResourcePath();
15780
15781        // Need installer lock especially for dex file removal.
15782        abstract void cleanUpResourcesLI();
15783        abstract boolean doPostDeleteLI(boolean delete);
15784
15785        /**
15786         * Called before the source arguments are copied. This is used mostly
15787         * for MoveParams when it needs to read the source file to put it in the
15788         * destination.
15789         */
15790        int doPreCopy() {
15791            return PackageManager.INSTALL_SUCCEEDED;
15792        }
15793
15794        /**
15795         * Called after the source arguments are copied. This is used mostly for
15796         * MoveParams when it needs to read the source file to put it in the
15797         * destination.
15798         */
15799        int doPostCopy(int uid) {
15800            return PackageManager.INSTALL_SUCCEEDED;
15801        }
15802
15803        protected boolean isFwdLocked() {
15804            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15805        }
15806
15807        protected boolean isExternalAsec() {
15808            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15809        }
15810
15811        protected boolean isEphemeral() {
15812            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15813        }
15814
15815        UserHandle getUser() {
15816            return user;
15817        }
15818    }
15819
15820    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15821        if (!allCodePaths.isEmpty()) {
15822            if (instructionSets == null) {
15823                throw new IllegalStateException("instructionSet == null");
15824            }
15825            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15826            for (String codePath : allCodePaths) {
15827                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15828                    try {
15829                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15830                    } catch (InstallerException ignored) {
15831                    }
15832                }
15833            }
15834        }
15835    }
15836
15837    /**
15838     * Logic to handle installation of non-ASEC applications, including copying
15839     * and renaming logic.
15840     */
15841    class FileInstallArgs extends InstallArgs {
15842        private File codeFile;
15843        private File resourceFile;
15844
15845        // Example topology:
15846        // /data/app/com.example/base.apk
15847        // /data/app/com.example/split_foo.apk
15848        // /data/app/com.example/lib/arm/libfoo.so
15849        // /data/app/com.example/lib/arm64/libfoo.so
15850        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15851
15852        /** New install */
15853        FileInstallArgs(InstallParams params) {
15854            super(params.origin, params.move, params.observer, params.installFlags,
15855                    params.installerPackageName, params.volumeUuid,
15856                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15857                    params.grantedRuntimePermissions,
15858                    params.traceMethod, params.traceCookie, params.certificates,
15859                    params.installReason);
15860            if (isFwdLocked()) {
15861                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15862            }
15863        }
15864
15865        /** Existing install */
15866        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15867            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15868                    null, null, null, 0, null /*certificates*/,
15869                    PackageManager.INSTALL_REASON_UNKNOWN);
15870            this.codeFile = (codePath != null) ? new File(codePath) : null;
15871            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15872        }
15873
15874        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15875            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15876            try {
15877                return doCopyApk(imcs, temp);
15878            } finally {
15879                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15880            }
15881        }
15882
15883        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15884            if (origin.staged) {
15885                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15886                codeFile = origin.file;
15887                resourceFile = origin.file;
15888                return PackageManager.INSTALL_SUCCEEDED;
15889            }
15890
15891            try {
15892                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15893                final File tempDir =
15894                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15895                codeFile = tempDir;
15896                resourceFile = tempDir;
15897            } catch (IOException e) {
15898                Slog.w(TAG, "Failed to create copy file: " + e);
15899                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15900            }
15901
15902            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15903                @Override
15904                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15905                    if (!FileUtils.isValidExtFilename(name)) {
15906                        throw new IllegalArgumentException("Invalid filename: " + name);
15907                    }
15908                    try {
15909                        final File file = new File(codeFile, name);
15910                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15911                                O_RDWR | O_CREAT, 0644);
15912                        Os.chmod(file.getAbsolutePath(), 0644);
15913                        return new ParcelFileDescriptor(fd);
15914                    } catch (ErrnoException e) {
15915                        throw new RemoteException("Failed to open: " + e.getMessage());
15916                    }
15917                }
15918            };
15919
15920            int ret = PackageManager.INSTALL_SUCCEEDED;
15921            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15922            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15923                Slog.e(TAG, "Failed to copy package");
15924                return ret;
15925            }
15926
15927            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15928            NativeLibraryHelper.Handle handle = null;
15929            try {
15930                handle = NativeLibraryHelper.Handle.create(codeFile);
15931                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15932                        abiOverride);
15933            } catch (IOException e) {
15934                Slog.e(TAG, "Copying native libraries failed", e);
15935                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15936            } finally {
15937                IoUtils.closeQuietly(handle);
15938            }
15939
15940            return ret;
15941        }
15942
15943        int doPreInstall(int status) {
15944            if (status != PackageManager.INSTALL_SUCCEEDED) {
15945                cleanUp();
15946            }
15947            return status;
15948        }
15949
15950        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15951            if (status != PackageManager.INSTALL_SUCCEEDED) {
15952                cleanUp();
15953                return false;
15954            }
15955
15956            final File targetDir = codeFile.getParentFile();
15957            final File beforeCodeFile = codeFile;
15958            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15959
15960            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15961            try {
15962                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15963            } catch (ErrnoException e) {
15964                Slog.w(TAG, "Failed to rename", e);
15965                return false;
15966            }
15967
15968            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15969                Slog.w(TAG, "Failed to restorecon");
15970                return false;
15971            }
15972
15973            // Reflect the rename internally
15974            codeFile = afterCodeFile;
15975            resourceFile = afterCodeFile;
15976
15977            // Reflect the rename in scanned details
15978            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15979            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15980                    afterCodeFile, pkg.baseCodePath));
15981            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15982                    afterCodeFile, pkg.splitCodePaths));
15983
15984            // Reflect the rename in app info
15985            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15986            pkg.setApplicationInfoCodePath(pkg.codePath);
15987            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15988            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15989            pkg.setApplicationInfoResourcePath(pkg.codePath);
15990            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15991            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15992
15993            return true;
15994        }
15995
15996        int doPostInstall(int status, int uid) {
15997            if (status != PackageManager.INSTALL_SUCCEEDED) {
15998                cleanUp();
15999            }
16000            return status;
16001        }
16002
16003        @Override
16004        String getCodePath() {
16005            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16006        }
16007
16008        @Override
16009        String getResourcePath() {
16010            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16011        }
16012
16013        private boolean cleanUp() {
16014            if (codeFile == null || !codeFile.exists()) {
16015                return false;
16016            }
16017
16018            removeCodePathLI(codeFile);
16019
16020            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16021                resourceFile.delete();
16022            }
16023
16024            return true;
16025        }
16026
16027        void cleanUpResourcesLI() {
16028            // Try enumerating all code paths before deleting
16029            List<String> allCodePaths = Collections.EMPTY_LIST;
16030            if (codeFile != null && codeFile.exists()) {
16031                try {
16032                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16033                    allCodePaths = pkg.getAllCodePaths();
16034                } catch (PackageParserException e) {
16035                    // Ignored; we tried our best
16036                }
16037            }
16038
16039            cleanUp();
16040            removeDexFiles(allCodePaths, instructionSets);
16041        }
16042
16043        boolean doPostDeleteLI(boolean delete) {
16044            // XXX err, shouldn't we respect the delete flag?
16045            cleanUpResourcesLI();
16046            return true;
16047        }
16048    }
16049
16050    private boolean isAsecExternal(String cid) {
16051        final String asecPath = PackageHelper.getSdFilesystem(cid);
16052        return !asecPath.startsWith(mAsecInternalPath);
16053    }
16054
16055    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16056            PackageManagerException {
16057        if (copyRet < 0) {
16058            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16059                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16060                throw new PackageManagerException(copyRet, message);
16061            }
16062        }
16063    }
16064
16065    /**
16066     * Extract the StorageManagerService "container ID" from the full code path of an
16067     * .apk.
16068     */
16069    static String cidFromCodePath(String fullCodePath) {
16070        int eidx = fullCodePath.lastIndexOf("/");
16071        String subStr1 = fullCodePath.substring(0, eidx);
16072        int sidx = subStr1.lastIndexOf("/");
16073        return subStr1.substring(sidx+1, eidx);
16074    }
16075
16076    /**
16077     * Logic to handle installation of ASEC applications, including copying and
16078     * renaming logic.
16079     */
16080    class AsecInstallArgs extends InstallArgs {
16081        static final String RES_FILE_NAME = "pkg.apk";
16082        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16083
16084        String cid;
16085        String packagePath;
16086        String resourcePath;
16087
16088        /** New install */
16089        AsecInstallArgs(InstallParams params) {
16090            super(params.origin, params.move, params.observer, params.installFlags,
16091                    params.installerPackageName, params.volumeUuid,
16092                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16093                    params.grantedRuntimePermissions,
16094                    params.traceMethod, params.traceCookie, params.certificates,
16095                    params.installReason);
16096        }
16097
16098        /** Existing install */
16099        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16100                        boolean isExternal, boolean isForwardLocked) {
16101            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16102                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16103                    instructionSets, null, null, null, 0, null /*certificates*/,
16104                    PackageManager.INSTALL_REASON_UNKNOWN);
16105            // Hackily pretend we're still looking at a full code path
16106            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16107                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16108            }
16109
16110            // Extract cid from fullCodePath
16111            int eidx = fullCodePath.lastIndexOf("/");
16112            String subStr1 = fullCodePath.substring(0, eidx);
16113            int sidx = subStr1.lastIndexOf("/");
16114            cid = subStr1.substring(sidx+1, eidx);
16115            setMountPath(subStr1);
16116        }
16117
16118        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16119            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16120                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16121                    instructionSets, null, null, null, 0, null /*certificates*/,
16122                    PackageManager.INSTALL_REASON_UNKNOWN);
16123            this.cid = cid;
16124            setMountPath(PackageHelper.getSdDir(cid));
16125        }
16126
16127        void createCopyFile() {
16128            cid = mInstallerService.allocateExternalStageCidLegacy();
16129        }
16130
16131        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16132            if (origin.staged && origin.cid != null) {
16133                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16134                cid = origin.cid;
16135                setMountPath(PackageHelper.getSdDir(cid));
16136                return PackageManager.INSTALL_SUCCEEDED;
16137            }
16138
16139            if (temp) {
16140                createCopyFile();
16141            } else {
16142                /*
16143                 * Pre-emptively destroy the container since it's destroyed if
16144                 * copying fails due to it existing anyway.
16145                 */
16146                PackageHelper.destroySdDir(cid);
16147            }
16148
16149            final String newMountPath = imcs.copyPackageToContainer(
16150                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16151                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16152
16153            if (newMountPath != null) {
16154                setMountPath(newMountPath);
16155                return PackageManager.INSTALL_SUCCEEDED;
16156            } else {
16157                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16158            }
16159        }
16160
16161        @Override
16162        String getCodePath() {
16163            return packagePath;
16164        }
16165
16166        @Override
16167        String getResourcePath() {
16168            return resourcePath;
16169        }
16170
16171        int doPreInstall(int status) {
16172            if (status != PackageManager.INSTALL_SUCCEEDED) {
16173                // Destroy container
16174                PackageHelper.destroySdDir(cid);
16175            } else {
16176                boolean mounted = PackageHelper.isContainerMounted(cid);
16177                if (!mounted) {
16178                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16179                            Process.SYSTEM_UID);
16180                    if (newMountPath != null) {
16181                        setMountPath(newMountPath);
16182                    } else {
16183                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16184                    }
16185                }
16186            }
16187            return status;
16188        }
16189
16190        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16191            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16192            String newMountPath = null;
16193            if (PackageHelper.isContainerMounted(cid)) {
16194                // Unmount the container
16195                if (!PackageHelper.unMountSdDir(cid)) {
16196                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16197                    return false;
16198                }
16199            }
16200            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16201                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16202                        " which might be stale. Will try to clean up.");
16203                // Clean up the stale container and proceed to recreate.
16204                if (!PackageHelper.destroySdDir(newCacheId)) {
16205                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16206                    return false;
16207                }
16208                // Successfully cleaned up stale container. Try to rename again.
16209                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16210                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16211                            + " inspite of cleaning it up.");
16212                    return false;
16213                }
16214            }
16215            if (!PackageHelper.isContainerMounted(newCacheId)) {
16216                Slog.w(TAG, "Mounting container " + newCacheId);
16217                newMountPath = PackageHelper.mountSdDir(newCacheId,
16218                        getEncryptKey(), Process.SYSTEM_UID);
16219            } else {
16220                newMountPath = PackageHelper.getSdDir(newCacheId);
16221            }
16222            if (newMountPath == null) {
16223                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16224                return false;
16225            }
16226            Log.i(TAG, "Succesfully renamed " + cid +
16227                    " to " + newCacheId +
16228                    " at new path: " + newMountPath);
16229            cid = newCacheId;
16230
16231            final File beforeCodeFile = new File(packagePath);
16232            setMountPath(newMountPath);
16233            final File afterCodeFile = new File(packagePath);
16234
16235            // Reflect the rename in scanned details
16236            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16237            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16238                    afterCodeFile, pkg.baseCodePath));
16239            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16240                    afterCodeFile, pkg.splitCodePaths));
16241
16242            // Reflect the rename in app info
16243            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16244            pkg.setApplicationInfoCodePath(pkg.codePath);
16245            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16246            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16247            pkg.setApplicationInfoResourcePath(pkg.codePath);
16248            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16249            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16250
16251            return true;
16252        }
16253
16254        private void setMountPath(String mountPath) {
16255            final File mountFile = new File(mountPath);
16256
16257            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16258            if (monolithicFile.exists()) {
16259                packagePath = monolithicFile.getAbsolutePath();
16260                if (isFwdLocked()) {
16261                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16262                } else {
16263                    resourcePath = packagePath;
16264                }
16265            } else {
16266                packagePath = mountFile.getAbsolutePath();
16267                resourcePath = packagePath;
16268            }
16269        }
16270
16271        int doPostInstall(int status, int uid) {
16272            if (status != PackageManager.INSTALL_SUCCEEDED) {
16273                cleanUp();
16274            } else {
16275                final int groupOwner;
16276                final String protectedFile;
16277                if (isFwdLocked()) {
16278                    groupOwner = UserHandle.getSharedAppGid(uid);
16279                    protectedFile = RES_FILE_NAME;
16280                } else {
16281                    groupOwner = -1;
16282                    protectedFile = null;
16283                }
16284
16285                if (uid < Process.FIRST_APPLICATION_UID
16286                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16287                    Slog.e(TAG, "Failed to finalize " + cid);
16288                    PackageHelper.destroySdDir(cid);
16289                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16290                }
16291
16292                boolean mounted = PackageHelper.isContainerMounted(cid);
16293                if (!mounted) {
16294                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16295                }
16296            }
16297            return status;
16298        }
16299
16300        private void cleanUp() {
16301            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16302
16303            // Destroy secure container
16304            PackageHelper.destroySdDir(cid);
16305        }
16306
16307        private List<String> getAllCodePaths() {
16308            final File codeFile = new File(getCodePath());
16309            if (codeFile != null && codeFile.exists()) {
16310                try {
16311                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16312                    return pkg.getAllCodePaths();
16313                } catch (PackageParserException e) {
16314                    // Ignored; we tried our best
16315                }
16316            }
16317            return Collections.EMPTY_LIST;
16318        }
16319
16320        void cleanUpResourcesLI() {
16321            // Enumerate all code paths before deleting
16322            cleanUpResourcesLI(getAllCodePaths());
16323        }
16324
16325        private void cleanUpResourcesLI(List<String> allCodePaths) {
16326            cleanUp();
16327            removeDexFiles(allCodePaths, instructionSets);
16328        }
16329
16330        String getPackageName() {
16331            return getAsecPackageName(cid);
16332        }
16333
16334        boolean doPostDeleteLI(boolean delete) {
16335            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
16336            final List<String> allCodePaths = getAllCodePaths();
16337            boolean mounted = PackageHelper.isContainerMounted(cid);
16338            if (mounted) {
16339                // Unmount first
16340                if (PackageHelper.unMountSdDir(cid)) {
16341                    mounted = false;
16342                }
16343            }
16344            if (!mounted && delete) {
16345                cleanUpResourcesLI(allCodePaths);
16346            }
16347            return !mounted;
16348        }
16349
16350        @Override
16351        int doPreCopy() {
16352            if (isFwdLocked()) {
16353                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
16354                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
16355                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16356                }
16357            }
16358
16359            return PackageManager.INSTALL_SUCCEEDED;
16360        }
16361
16362        @Override
16363        int doPostCopy(int uid) {
16364            if (isFwdLocked()) {
16365                if (uid < Process.FIRST_APPLICATION_UID
16366                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
16367                                RES_FILE_NAME)) {
16368                    Slog.e(TAG, "Failed to finalize " + cid);
16369                    PackageHelper.destroySdDir(cid);
16370                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16371                }
16372            }
16373
16374            return PackageManager.INSTALL_SUCCEEDED;
16375        }
16376    }
16377
16378    /**
16379     * Logic to handle movement of existing installed applications.
16380     */
16381    class MoveInstallArgs extends InstallArgs {
16382        private File codeFile;
16383        private File resourceFile;
16384
16385        /** New install */
16386        MoveInstallArgs(InstallParams params) {
16387            super(params.origin, params.move, params.observer, params.installFlags,
16388                    params.installerPackageName, params.volumeUuid,
16389                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16390                    params.grantedRuntimePermissions,
16391                    params.traceMethod, params.traceCookie, params.certificates,
16392                    params.installReason);
16393        }
16394
16395        int copyApk(IMediaContainerService imcs, boolean temp) {
16396            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16397                    + move.fromUuid + " to " + move.toUuid);
16398            synchronized (mInstaller) {
16399                try {
16400                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16401                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16402                } catch (InstallerException e) {
16403                    Slog.w(TAG, "Failed to move app", e);
16404                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16405                }
16406            }
16407
16408            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16409            resourceFile = codeFile;
16410            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16411
16412            return PackageManager.INSTALL_SUCCEEDED;
16413        }
16414
16415        int doPreInstall(int status) {
16416            if (status != PackageManager.INSTALL_SUCCEEDED) {
16417                cleanUp(move.toUuid);
16418            }
16419            return status;
16420        }
16421
16422        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16423            if (status != PackageManager.INSTALL_SUCCEEDED) {
16424                cleanUp(move.toUuid);
16425                return false;
16426            }
16427
16428            // Reflect the move in app info
16429            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16430            pkg.setApplicationInfoCodePath(pkg.codePath);
16431            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16432            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16433            pkg.setApplicationInfoResourcePath(pkg.codePath);
16434            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16435            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16436
16437            return true;
16438        }
16439
16440        int doPostInstall(int status, int uid) {
16441            if (status == PackageManager.INSTALL_SUCCEEDED) {
16442                cleanUp(move.fromUuid);
16443            } else {
16444                cleanUp(move.toUuid);
16445            }
16446            return status;
16447        }
16448
16449        @Override
16450        String getCodePath() {
16451            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16452        }
16453
16454        @Override
16455        String getResourcePath() {
16456            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16457        }
16458
16459        private boolean cleanUp(String volumeUuid) {
16460            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16461                    move.dataAppName);
16462            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16463            final int[] userIds = sUserManager.getUserIds();
16464            synchronized (mInstallLock) {
16465                // Clean up both app data and code
16466                // All package moves are frozen until finished
16467                for (int userId : userIds) {
16468                    try {
16469                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16470                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16471                    } catch (InstallerException e) {
16472                        Slog.w(TAG, String.valueOf(e));
16473                    }
16474                }
16475                removeCodePathLI(codeFile);
16476            }
16477            return true;
16478        }
16479
16480        void cleanUpResourcesLI() {
16481            throw new UnsupportedOperationException();
16482        }
16483
16484        boolean doPostDeleteLI(boolean delete) {
16485            throw new UnsupportedOperationException();
16486        }
16487    }
16488
16489    static String getAsecPackageName(String packageCid) {
16490        int idx = packageCid.lastIndexOf("-");
16491        if (idx == -1) {
16492            return packageCid;
16493        }
16494        return packageCid.substring(0, idx);
16495    }
16496
16497    // Utility method used to create code paths based on package name and available index.
16498    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16499        String idxStr = "";
16500        int idx = 1;
16501        // Fall back to default value of idx=1 if prefix is not
16502        // part of oldCodePath
16503        if (oldCodePath != null) {
16504            String subStr = oldCodePath;
16505            // Drop the suffix right away
16506            if (suffix != null && subStr.endsWith(suffix)) {
16507                subStr = subStr.substring(0, subStr.length() - suffix.length());
16508            }
16509            // If oldCodePath already contains prefix find out the
16510            // ending index to either increment or decrement.
16511            int sidx = subStr.lastIndexOf(prefix);
16512            if (sidx != -1) {
16513                subStr = subStr.substring(sidx + prefix.length());
16514                if (subStr != null) {
16515                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16516                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16517                    }
16518                    try {
16519                        idx = Integer.parseInt(subStr);
16520                        if (idx <= 1) {
16521                            idx++;
16522                        } else {
16523                            idx--;
16524                        }
16525                    } catch(NumberFormatException e) {
16526                    }
16527                }
16528            }
16529        }
16530        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16531        return prefix + idxStr;
16532    }
16533
16534    private File getNextCodePath(File targetDir, String packageName) {
16535        File result;
16536        SecureRandom random = new SecureRandom();
16537        byte[] bytes = new byte[16];
16538        do {
16539            random.nextBytes(bytes);
16540            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16541            result = new File(targetDir, packageName + "-" + suffix);
16542        } while (result.exists());
16543        return result;
16544    }
16545
16546    // Utility method that returns the relative package path with respect
16547    // to the installation directory. Like say for /data/data/com.test-1.apk
16548    // string com.test-1 is returned.
16549    static String deriveCodePathName(String codePath) {
16550        if (codePath == null) {
16551            return null;
16552        }
16553        final File codeFile = new File(codePath);
16554        final String name = codeFile.getName();
16555        if (codeFile.isDirectory()) {
16556            return name;
16557        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16558            final int lastDot = name.lastIndexOf('.');
16559            return name.substring(0, lastDot);
16560        } else {
16561            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16562            return null;
16563        }
16564    }
16565
16566    static class PackageInstalledInfo {
16567        String name;
16568        int uid;
16569        // The set of users that originally had this package installed.
16570        int[] origUsers;
16571        // The set of users that now have this package installed.
16572        int[] newUsers;
16573        PackageParser.Package pkg;
16574        int returnCode;
16575        String returnMsg;
16576        PackageRemovedInfo removedInfo;
16577        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16578
16579        public void setError(int code, String msg) {
16580            setReturnCode(code);
16581            setReturnMessage(msg);
16582            Slog.w(TAG, msg);
16583        }
16584
16585        public void setError(String msg, PackageParserException e) {
16586            setReturnCode(e.error);
16587            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16588            Slog.w(TAG, msg, e);
16589        }
16590
16591        public void setError(String msg, PackageManagerException e) {
16592            returnCode = e.error;
16593            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16594            Slog.w(TAG, msg, e);
16595        }
16596
16597        public void setReturnCode(int returnCode) {
16598            this.returnCode = returnCode;
16599            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16600            for (int i = 0; i < childCount; i++) {
16601                addedChildPackages.valueAt(i).returnCode = returnCode;
16602            }
16603        }
16604
16605        private void setReturnMessage(String returnMsg) {
16606            this.returnMsg = returnMsg;
16607            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16608            for (int i = 0; i < childCount; i++) {
16609                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16610            }
16611        }
16612
16613        // In some error cases we want to convey more info back to the observer
16614        String origPackage;
16615        String origPermission;
16616    }
16617
16618    /*
16619     * Install a non-existing package.
16620     */
16621    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
16622            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
16623            PackageInstalledInfo res, int installReason) {
16624        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16625
16626        // Remember this for later, in case we need to rollback this install
16627        String pkgName = pkg.packageName;
16628
16629        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16630
16631        synchronized(mPackages) {
16632            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16633            if (renamedPackage != null) {
16634                // A package with the same name is already installed, though
16635                // it has been renamed to an older name.  The package we
16636                // are trying to install should be installed as an update to
16637                // the existing one, but that has not been requested, so bail.
16638                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16639                        + " without first uninstalling package running as "
16640                        + renamedPackage);
16641                return;
16642            }
16643            if (mPackages.containsKey(pkgName)) {
16644                // Don't allow installation over an existing package with the same name.
16645                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16646                        + " without first uninstalling.");
16647                return;
16648            }
16649        }
16650
16651        try {
16652            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
16653                    System.currentTimeMillis(), user);
16654
16655            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16656
16657            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16658                prepareAppDataAfterInstallLIF(newPackage);
16659
16660            } else {
16661                // Remove package from internal structures, but keep around any
16662                // data that might have already existed
16663                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16664                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16665            }
16666        } catch (PackageManagerException e) {
16667            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16668        }
16669
16670        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16671    }
16672
16673    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
16674        // Can't rotate keys during boot or if sharedUser.
16675        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
16676                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
16677            return false;
16678        }
16679        // app is using upgradeKeySets; make sure all are valid
16680        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16681        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
16682        for (int i = 0; i < upgradeKeySets.length; i++) {
16683            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
16684                Slog.wtf(TAG, "Package "
16685                         + (oldPs.name != null ? oldPs.name : "<null>")
16686                         + " contains upgrade-key-set reference to unknown key-set: "
16687                         + upgradeKeySets[i]
16688                         + " reverting to signatures check.");
16689                return false;
16690            }
16691        }
16692        return true;
16693    }
16694
16695    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
16696        // Upgrade keysets are being used.  Determine if new package has a superset of the
16697        // required keys.
16698        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
16699        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16700        for (int i = 0; i < upgradeKeySets.length; i++) {
16701            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
16702            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
16703                return true;
16704            }
16705        }
16706        return false;
16707    }
16708
16709    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16710        try (DigestInputStream digestStream =
16711                new DigestInputStream(new FileInputStream(file), digest)) {
16712            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16713        }
16714    }
16715
16716    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
16717            UserHandle user, String installerPackageName, PackageInstalledInfo res,
16718            int installReason) {
16719        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16720
16721        final PackageParser.Package oldPackage;
16722        final PackageSetting ps;
16723        final String pkgName = pkg.packageName;
16724        final int[] allUsers;
16725        final int[] installedUsers;
16726
16727        synchronized(mPackages) {
16728            oldPackage = mPackages.get(pkgName);
16729            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16730
16731            // don't allow upgrade to target a release SDK from a pre-release SDK
16732            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16733                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16734            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16735                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16736            if (oldTargetsPreRelease
16737                    && !newTargetsPreRelease
16738                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16739                Slog.w(TAG, "Can't install package targeting released sdk");
16740                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16741                return;
16742            }
16743
16744            ps = mSettings.mPackages.get(pkgName);
16745
16746            // verify signatures are valid
16747            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
16748                if (!checkUpgradeKeySetLP(ps, pkg)) {
16749                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16750                            "New package not signed by keys specified by upgrade-keysets: "
16751                                    + pkgName);
16752                    return;
16753                }
16754            } else {
16755                // default to original signature matching
16756                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
16757                        != PackageManager.SIGNATURE_MATCH) {
16758                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16759                            "New package has a different signature: " + pkgName);
16760                    return;
16761                }
16762            }
16763
16764            // don't allow a system upgrade unless the upgrade hash matches
16765            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
16766                byte[] digestBytes = null;
16767                try {
16768                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16769                    updateDigest(digest, new File(pkg.baseCodePath));
16770                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16771                        for (String path : pkg.splitCodePaths) {
16772                            updateDigest(digest, new File(path));
16773                        }
16774                    }
16775                    digestBytes = digest.digest();
16776                } catch (NoSuchAlgorithmException | IOException e) {
16777                    res.setError(INSTALL_FAILED_INVALID_APK,
16778                            "Could not compute hash: " + pkgName);
16779                    return;
16780                }
16781                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16782                    res.setError(INSTALL_FAILED_INVALID_APK,
16783                            "New package fails restrict-update check: " + pkgName);
16784                    return;
16785                }
16786                // retain upgrade restriction
16787                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16788            }
16789
16790            // Check for shared user id changes
16791            String invalidPackageName =
16792                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16793            if (invalidPackageName != null) {
16794                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16795                        "Package " + invalidPackageName + " tried to change user "
16796                                + oldPackage.mSharedUserId);
16797                return;
16798            }
16799
16800            // In case of rollback, remember per-user/profile install state
16801            allUsers = sUserManager.getUserIds();
16802            installedUsers = ps.queryInstalledUsers(allUsers, true);
16803
16804            // don't allow an upgrade from full to ephemeral
16805            if (isInstantApp) {
16806                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16807                    for (int currentUser : allUsers) {
16808                        if (!ps.getInstantApp(currentUser)) {
16809                            // can't downgrade from full to instant
16810                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16811                                    + " for user: " + currentUser);
16812                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16813                            return;
16814                        }
16815                    }
16816                } else if (!ps.getInstantApp(user.getIdentifier())) {
16817                    // can't downgrade from full to instant
16818                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16819                            + " for user: " + user.getIdentifier());
16820                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16821                    return;
16822                }
16823            }
16824        }
16825
16826        // Update what is removed
16827        res.removedInfo = new PackageRemovedInfo(this);
16828        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16829        res.removedInfo.removedPackage = oldPackage.packageName;
16830        res.removedInfo.installerPackageName = ps.installerPackageName;
16831        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16832        res.removedInfo.isUpdate = true;
16833        res.removedInfo.origUsers = installedUsers;
16834        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16835        for (int i = 0; i < installedUsers.length; i++) {
16836            final int userId = installedUsers[i];
16837            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16838        }
16839
16840        final int childCount = (oldPackage.childPackages != null)
16841                ? oldPackage.childPackages.size() : 0;
16842        for (int i = 0; i < childCount; i++) {
16843            boolean childPackageUpdated = false;
16844            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16845            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16846            if (res.addedChildPackages != null) {
16847                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16848                if (childRes != null) {
16849                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16850                    childRes.removedInfo.removedPackage = childPkg.packageName;
16851                    if (childPs != null) {
16852                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16853                    }
16854                    childRes.removedInfo.isUpdate = true;
16855                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16856                    childPackageUpdated = true;
16857                }
16858            }
16859            if (!childPackageUpdated) {
16860                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16861                childRemovedRes.removedPackage = childPkg.packageName;
16862                if (childPs != null) {
16863                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16864                }
16865                childRemovedRes.isUpdate = false;
16866                childRemovedRes.dataRemoved = true;
16867                synchronized (mPackages) {
16868                    if (childPs != null) {
16869                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16870                    }
16871                }
16872                if (res.removedInfo.removedChildPackages == null) {
16873                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16874                }
16875                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16876            }
16877        }
16878
16879        boolean sysPkg = (isSystemApp(oldPackage));
16880        if (sysPkg) {
16881            // Set the system/privileged flags as needed
16882            final boolean privileged =
16883                    (oldPackage.applicationInfo.privateFlags
16884                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16885            final int systemPolicyFlags = policyFlags
16886                    | PackageParser.PARSE_IS_SYSTEM
16887                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
16888
16889            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
16890                    user, allUsers, installerPackageName, res, installReason);
16891        } else {
16892            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
16893                    user, allUsers, installerPackageName, res, installReason);
16894        }
16895    }
16896
16897    @Override
16898    public List<String> getPreviousCodePaths(String packageName) {
16899        final List<String> result = new ArrayList<>();
16900        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
16901            return result;
16902        }
16903        final PackageSetting ps = mSettings.mPackages.get(packageName);
16904        if (ps != null && ps.oldCodePaths != null) {
16905            result.addAll(ps.oldCodePaths);
16906        }
16907        return result;
16908    }
16909
16910    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16911            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16912            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16913            int installReason) {
16914        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16915                + deletedPackage);
16916
16917        String pkgName = deletedPackage.packageName;
16918        boolean deletedPkg = true;
16919        boolean addedPkg = false;
16920        boolean updatedSettings = false;
16921        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16922        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16923                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16924
16925        final long origUpdateTime = (pkg.mExtras != null)
16926                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16927
16928        // First delete the existing package while retaining the data directory
16929        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16930                res.removedInfo, true, pkg)) {
16931            // If the existing package wasn't successfully deleted
16932            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16933            deletedPkg = false;
16934        } else {
16935            // Successfully deleted the old package; proceed with replace.
16936
16937            // If deleted package lived in a container, give users a chance to
16938            // relinquish resources before killing.
16939            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16940                if (DEBUG_INSTALL) {
16941                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16942                }
16943                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16944                final ArrayList<String> pkgList = new ArrayList<String>(1);
16945                pkgList.add(deletedPackage.applicationInfo.packageName);
16946                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16947            }
16948
16949            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16950                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16951            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16952
16953            try {
16954                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
16955                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16956                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16957                        installReason);
16958
16959                // Update the in-memory copy of the previous code paths.
16960                PackageSetting ps = mSettings.mPackages.get(pkgName);
16961                if (!killApp) {
16962                    if (ps.oldCodePaths == null) {
16963                        ps.oldCodePaths = new ArraySet<>();
16964                    }
16965                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16966                    if (deletedPackage.splitCodePaths != null) {
16967                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16968                    }
16969                } else {
16970                    ps.oldCodePaths = null;
16971                }
16972                if (ps.childPackageNames != null) {
16973                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16974                        final String childPkgName = ps.childPackageNames.get(i);
16975                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16976                        childPs.oldCodePaths = ps.oldCodePaths;
16977                    }
16978                }
16979                // set instant app status, but, only if it's explicitly specified
16980                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16981                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16982                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16983                prepareAppDataAfterInstallLIF(newPackage);
16984                addedPkg = true;
16985                mDexManager.notifyPackageUpdated(newPackage.packageName,
16986                        newPackage.baseCodePath, newPackage.splitCodePaths);
16987            } catch (PackageManagerException e) {
16988                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16989            }
16990        }
16991
16992        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16993            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16994
16995            // Revert all internal state mutations and added folders for the failed install
16996            if (addedPkg) {
16997                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16998                        res.removedInfo, true, null);
16999            }
17000
17001            // Restore the old package
17002            if (deletedPkg) {
17003                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17004                File restoreFile = new File(deletedPackage.codePath);
17005                // Parse old package
17006                boolean oldExternal = isExternal(deletedPackage);
17007                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17008                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17009                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17010                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17011                try {
17012                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17013                            null);
17014                } catch (PackageManagerException e) {
17015                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17016                            + e.getMessage());
17017                    return;
17018                }
17019
17020                synchronized (mPackages) {
17021                    // Ensure the installer package name up to date
17022                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17023
17024                    // Update permissions for restored package
17025                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17026
17027                    mSettings.writeLPr();
17028                }
17029
17030                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17031            }
17032        } else {
17033            synchronized (mPackages) {
17034                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17035                if (ps != null) {
17036                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17037                    if (res.removedInfo.removedChildPackages != null) {
17038                        final int childCount = res.removedInfo.removedChildPackages.size();
17039                        // Iterate in reverse as we may modify the collection
17040                        for (int i = childCount - 1; i >= 0; i--) {
17041                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17042                            if (res.addedChildPackages.containsKey(childPackageName)) {
17043                                res.removedInfo.removedChildPackages.removeAt(i);
17044                            } else {
17045                                PackageRemovedInfo childInfo = res.removedInfo
17046                                        .removedChildPackages.valueAt(i);
17047                                childInfo.removedForAllUsers = mPackages.get(
17048                                        childInfo.removedPackage) == null;
17049                            }
17050                        }
17051                    }
17052                }
17053            }
17054        }
17055    }
17056
17057    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17058            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17059            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17060            int installReason) {
17061        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17062                + ", old=" + deletedPackage);
17063
17064        final boolean disabledSystem;
17065
17066        // Remove existing system package
17067        removePackageLI(deletedPackage, true);
17068
17069        synchronized (mPackages) {
17070            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17071        }
17072        if (!disabledSystem) {
17073            // We didn't need to disable the .apk as a current system package,
17074            // which means we are replacing another update that is already
17075            // installed.  We need to make sure to delete the older one's .apk.
17076            res.removedInfo.args = createInstallArgsForExisting(0,
17077                    deletedPackage.applicationInfo.getCodePath(),
17078                    deletedPackage.applicationInfo.getResourcePath(),
17079                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17080        } else {
17081            res.removedInfo.args = null;
17082        }
17083
17084        // Successfully disabled the old package. Now proceed with re-installation
17085        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17086                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17087        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17088
17089        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17090        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17091                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17092
17093        PackageParser.Package newPackage = null;
17094        try {
17095            // Add the package to the internal data structures
17096            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17097
17098            // Set the update and install times
17099            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17100            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17101                    System.currentTimeMillis());
17102
17103            // Update the package dynamic state if succeeded
17104            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17105                // Now that the install succeeded make sure we remove data
17106                // directories for any child package the update removed.
17107                final int deletedChildCount = (deletedPackage.childPackages != null)
17108                        ? deletedPackage.childPackages.size() : 0;
17109                final int newChildCount = (newPackage.childPackages != null)
17110                        ? newPackage.childPackages.size() : 0;
17111                for (int i = 0; i < deletedChildCount; i++) {
17112                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17113                    boolean childPackageDeleted = true;
17114                    for (int j = 0; j < newChildCount; j++) {
17115                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17116                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17117                            childPackageDeleted = false;
17118                            break;
17119                        }
17120                    }
17121                    if (childPackageDeleted) {
17122                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17123                                deletedChildPkg.packageName);
17124                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17125                            PackageRemovedInfo removedChildRes = res.removedInfo
17126                                    .removedChildPackages.get(deletedChildPkg.packageName);
17127                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17128                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17129                        }
17130                    }
17131                }
17132
17133                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17134                        installReason);
17135                prepareAppDataAfterInstallLIF(newPackage);
17136
17137                mDexManager.notifyPackageUpdated(newPackage.packageName,
17138                            newPackage.baseCodePath, newPackage.splitCodePaths);
17139            }
17140        } catch (PackageManagerException e) {
17141            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17142            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17143        }
17144
17145        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17146            // Re installation failed. Restore old information
17147            // Remove new pkg information
17148            if (newPackage != null) {
17149                removeInstalledPackageLI(newPackage, true);
17150            }
17151            // Add back the old system package
17152            try {
17153                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17154            } catch (PackageManagerException e) {
17155                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17156            }
17157
17158            synchronized (mPackages) {
17159                if (disabledSystem) {
17160                    enableSystemPackageLPw(deletedPackage);
17161                }
17162
17163                // Ensure the installer package name up to date
17164                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17165
17166                // Update permissions for restored package
17167                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17168
17169                mSettings.writeLPr();
17170            }
17171
17172            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17173                    + " after failed upgrade");
17174        }
17175    }
17176
17177    /**
17178     * Checks whether the parent or any of the child packages have a change shared
17179     * user. For a package to be a valid update the shred users of the parent and
17180     * the children should match. We may later support changing child shared users.
17181     * @param oldPkg The updated package.
17182     * @param newPkg The update package.
17183     * @return The shared user that change between the versions.
17184     */
17185    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17186            PackageParser.Package newPkg) {
17187        // Check parent shared user
17188        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17189            return newPkg.packageName;
17190        }
17191        // Check child shared users
17192        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17193        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17194        for (int i = 0; i < newChildCount; i++) {
17195            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17196            // If this child was present, did it have the same shared user?
17197            for (int j = 0; j < oldChildCount; j++) {
17198                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17199                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17200                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17201                    return newChildPkg.packageName;
17202                }
17203            }
17204        }
17205        return null;
17206    }
17207
17208    private void removeNativeBinariesLI(PackageSetting ps) {
17209        // Remove the lib path for the parent package
17210        if (ps != null) {
17211            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17212            // Remove the lib path for the child packages
17213            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17214            for (int i = 0; i < childCount; i++) {
17215                PackageSetting childPs = null;
17216                synchronized (mPackages) {
17217                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17218                }
17219                if (childPs != null) {
17220                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17221                            .legacyNativeLibraryPathString);
17222                }
17223            }
17224        }
17225    }
17226
17227    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17228        // Enable the parent package
17229        mSettings.enableSystemPackageLPw(pkg.packageName);
17230        // Enable the child packages
17231        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17232        for (int i = 0; i < childCount; i++) {
17233            PackageParser.Package childPkg = pkg.childPackages.get(i);
17234            mSettings.enableSystemPackageLPw(childPkg.packageName);
17235        }
17236    }
17237
17238    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17239            PackageParser.Package newPkg) {
17240        // Disable the parent package (parent always replaced)
17241        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17242        // Disable the child packages
17243        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17244        for (int i = 0; i < childCount; i++) {
17245            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17246            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17247            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17248        }
17249        return disabled;
17250    }
17251
17252    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17253            String installerPackageName) {
17254        // Enable the parent package
17255        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17256        // Enable the child packages
17257        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17258        for (int i = 0; i < childCount; i++) {
17259            PackageParser.Package childPkg = pkg.childPackages.get(i);
17260            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17261        }
17262    }
17263
17264    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17265        // Collect all used permissions in the UID
17266        ArraySet<String> usedPermissions = new ArraySet<>();
17267        final int packageCount = su.packages.size();
17268        for (int i = 0; i < packageCount; i++) {
17269            PackageSetting ps = su.packages.valueAt(i);
17270            if (ps.pkg == null) {
17271                continue;
17272            }
17273            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17274            for (int j = 0; j < requestedPermCount; j++) {
17275                String permission = ps.pkg.requestedPermissions.get(j);
17276                BasePermission bp = mSettings.mPermissions.get(permission);
17277                if (bp != null) {
17278                    usedPermissions.add(permission);
17279                }
17280            }
17281        }
17282
17283        PermissionsState permissionsState = su.getPermissionsState();
17284        // Prune install permissions
17285        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17286        final int installPermCount = installPermStates.size();
17287        for (int i = installPermCount - 1; i >= 0;  i--) {
17288            PermissionState permissionState = installPermStates.get(i);
17289            if (!usedPermissions.contains(permissionState.getName())) {
17290                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17291                if (bp != null) {
17292                    permissionsState.revokeInstallPermission(bp);
17293                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17294                            PackageManager.MASK_PERMISSION_FLAGS, 0);
17295                }
17296            }
17297        }
17298
17299        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17300
17301        // Prune runtime permissions
17302        for (int userId : allUserIds) {
17303            List<PermissionState> runtimePermStates = permissionsState
17304                    .getRuntimePermissionStates(userId);
17305            final int runtimePermCount = runtimePermStates.size();
17306            for (int i = runtimePermCount - 1; i >= 0; i--) {
17307                PermissionState permissionState = runtimePermStates.get(i);
17308                if (!usedPermissions.contains(permissionState.getName())) {
17309                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17310                    if (bp != null) {
17311                        permissionsState.revokeRuntimePermission(bp, userId);
17312                        permissionsState.updatePermissionFlags(bp, userId,
17313                                PackageManager.MASK_PERMISSION_FLAGS, 0);
17314                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
17315                                runtimePermissionChangedUserIds, userId);
17316                    }
17317                }
17318            }
17319        }
17320
17321        return runtimePermissionChangedUserIds;
17322    }
17323
17324    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17325            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17326        // Update the parent package setting
17327        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17328                res, user, installReason);
17329        // Update the child packages setting
17330        final int childCount = (newPackage.childPackages != null)
17331                ? newPackage.childPackages.size() : 0;
17332        for (int i = 0; i < childCount; i++) {
17333            PackageParser.Package childPackage = newPackage.childPackages.get(i);
17334            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17335            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17336                    childRes.origUsers, childRes, user, installReason);
17337        }
17338    }
17339
17340    private void updateSettingsInternalLI(PackageParser.Package newPackage,
17341            String installerPackageName, int[] allUsers, int[] installedForUsers,
17342            PackageInstalledInfo res, UserHandle user, int installReason) {
17343        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17344
17345        String pkgName = newPackage.packageName;
17346        synchronized (mPackages) {
17347            //write settings. the installStatus will be incomplete at this stage.
17348            //note that the new package setting would have already been
17349            //added to mPackages. It hasn't been persisted yet.
17350            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17351            // TODO: Remove this write? It's also written at the end of this method
17352            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17353            mSettings.writeLPr();
17354            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17355        }
17356
17357        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17358        synchronized (mPackages) {
17359            updatePermissionsLPw(newPackage.packageName, newPackage,
17360                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17361                            ? UPDATE_PERMISSIONS_ALL : 0));
17362            // For system-bundled packages, we assume that installing an upgraded version
17363            // of the package implies that the user actually wants to run that new code,
17364            // so we enable the package.
17365            PackageSetting ps = mSettings.mPackages.get(pkgName);
17366            final int userId = user.getIdentifier();
17367            if (ps != null) {
17368                if (isSystemApp(newPackage)) {
17369                    if (DEBUG_INSTALL) {
17370                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17371                    }
17372                    // Enable system package for requested users
17373                    if (res.origUsers != null) {
17374                        for (int origUserId : res.origUsers) {
17375                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17376                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17377                                        origUserId, installerPackageName);
17378                            }
17379                        }
17380                    }
17381                    // Also convey the prior install/uninstall state
17382                    if (allUsers != null && installedForUsers != null) {
17383                        for (int currentUserId : allUsers) {
17384                            final boolean installed = ArrayUtils.contains(
17385                                    installedForUsers, currentUserId);
17386                            if (DEBUG_INSTALL) {
17387                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17388                            }
17389                            ps.setInstalled(installed, currentUserId);
17390                        }
17391                        // these install state changes will be persisted in the
17392                        // upcoming call to mSettings.writeLPr().
17393                    }
17394                }
17395                // It's implied that when a user requests installation, they want the app to be
17396                // installed and enabled.
17397                if (userId != UserHandle.USER_ALL) {
17398                    ps.setInstalled(true, userId);
17399                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17400                }
17401
17402                // When replacing an existing package, preserve the original install reason for all
17403                // users that had the package installed before.
17404                final Set<Integer> previousUserIds = new ArraySet<>();
17405                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17406                    final int installReasonCount = res.removedInfo.installReasons.size();
17407                    for (int i = 0; i < installReasonCount; i++) {
17408                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17409                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17410                        ps.setInstallReason(previousInstallReason, previousUserId);
17411                        previousUserIds.add(previousUserId);
17412                    }
17413                }
17414
17415                // Set install reason for users that are having the package newly installed.
17416                if (userId == UserHandle.USER_ALL) {
17417                    for (int currentUserId : sUserManager.getUserIds()) {
17418                        if (!previousUserIds.contains(currentUserId)) {
17419                            ps.setInstallReason(installReason, currentUserId);
17420                        }
17421                    }
17422                } else if (!previousUserIds.contains(userId)) {
17423                    ps.setInstallReason(installReason, userId);
17424                }
17425                mSettings.writeKernelMappingLPr(ps);
17426            }
17427            res.name = pkgName;
17428            res.uid = newPackage.applicationInfo.uid;
17429            res.pkg = newPackage;
17430            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17431            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17432            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17433            //to update install status
17434            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17435            mSettings.writeLPr();
17436            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17437        }
17438
17439        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17440    }
17441
17442    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17443        try {
17444            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17445            installPackageLI(args, res);
17446        } finally {
17447            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17448        }
17449    }
17450
17451    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17452        final int installFlags = args.installFlags;
17453        final String installerPackageName = args.installerPackageName;
17454        final String volumeUuid = args.volumeUuid;
17455        final File tmpPackageFile = new File(args.getCodePath());
17456        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17457        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17458                || (args.volumeUuid != null));
17459        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17460        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17461        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17462        boolean replace = false;
17463        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17464        if (args.move != null) {
17465            // moving a complete application; perform an initial scan on the new install location
17466            scanFlags |= SCAN_INITIAL;
17467        }
17468        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17469            scanFlags |= SCAN_DONT_KILL_APP;
17470        }
17471        if (instantApp) {
17472            scanFlags |= SCAN_AS_INSTANT_APP;
17473        }
17474        if (fullApp) {
17475            scanFlags |= SCAN_AS_FULL_APP;
17476        }
17477
17478        // Result object to be returned
17479        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17480
17481        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17482
17483        // Sanity check
17484        if (instantApp && (forwardLocked || onExternal)) {
17485            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17486                    + " external=" + onExternal);
17487            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17488            return;
17489        }
17490
17491        // Retrieve PackageSettings and parse package
17492        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17493                | PackageParser.PARSE_ENFORCE_CODE
17494                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17495                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17496                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17497                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17498        PackageParser pp = new PackageParser();
17499        pp.setSeparateProcesses(mSeparateProcesses);
17500        pp.setDisplayMetrics(mMetrics);
17501        pp.setCallback(mPackageParserCallback);
17502
17503        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17504        final PackageParser.Package pkg;
17505        try {
17506            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17507        } catch (PackageParserException e) {
17508            res.setError("Failed parse during installPackageLI", e);
17509            return;
17510        } finally {
17511            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17512        }
17513
17514        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17515        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17516            Slog.w(TAG, "Instant app package " + pkg.packageName
17517                    + " does not target O, this will be a fatal error.");
17518            // STOPSHIP: Make this a fatal error
17519            pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O;
17520        }
17521        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17522            Slog.w(TAG, "Instant app package " + pkg.packageName
17523                    + " does not target targetSandboxVersion 2, this will be a fatal error.");
17524            // STOPSHIP: Make this a fatal error
17525            pkg.applicationInfo.targetSandboxVersion = 2;
17526        }
17527
17528        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17529            // Static shared libraries have synthetic package names
17530            renameStaticSharedLibraryPackage(pkg);
17531
17532            // No static shared libs on external storage
17533            if (onExternal) {
17534                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17535                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17536                        "Packages declaring static-shared libs cannot be updated");
17537                return;
17538            }
17539        }
17540
17541        // If we are installing a clustered package add results for the children
17542        if (pkg.childPackages != null) {
17543            synchronized (mPackages) {
17544                final int childCount = pkg.childPackages.size();
17545                for (int i = 0; i < childCount; i++) {
17546                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17547                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17548                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17549                    childRes.pkg = childPkg;
17550                    childRes.name = childPkg.packageName;
17551                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17552                    if (childPs != null) {
17553                        childRes.origUsers = childPs.queryInstalledUsers(
17554                                sUserManager.getUserIds(), true);
17555                    }
17556                    if ((mPackages.containsKey(childPkg.packageName))) {
17557                        childRes.removedInfo = new PackageRemovedInfo(this);
17558                        childRes.removedInfo.removedPackage = childPkg.packageName;
17559                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17560                    }
17561                    if (res.addedChildPackages == null) {
17562                        res.addedChildPackages = new ArrayMap<>();
17563                    }
17564                    res.addedChildPackages.put(childPkg.packageName, childRes);
17565                }
17566            }
17567        }
17568
17569        // If package doesn't declare API override, mark that we have an install
17570        // time CPU ABI override.
17571        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17572            pkg.cpuAbiOverride = args.abiOverride;
17573        }
17574
17575        String pkgName = res.name = pkg.packageName;
17576        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17577            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17578                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17579                return;
17580            }
17581        }
17582
17583        try {
17584            // either use what we've been given or parse directly from the APK
17585            if (args.certificates != null) {
17586                try {
17587                    PackageParser.populateCertificates(pkg, args.certificates);
17588                } catch (PackageParserException e) {
17589                    // there was something wrong with the certificates we were given;
17590                    // try to pull them from the APK
17591                    PackageParser.collectCertificates(pkg, parseFlags);
17592                }
17593            } else {
17594                PackageParser.collectCertificates(pkg, parseFlags);
17595            }
17596        } catch (PackageParserException e) {
17597            res.setError("Failed collect during installPackageLI", e);
17598            return;
17599        }
17600
17601        // Get rid of all references to package scan path via parser.
17602        pp = null;
17603        String oldCodePath = null;
17604        boolean systemApp = false;
17605        synchronized (mPackages) {
17606            // Check if installing already existing package
17607            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17608                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17609                if (pkg.mOriginalPackages != null
17610                        && pkg.mOriginalPackages.contains(oldName)
17611                        && mPackages.containsKey(oldName)) {
17612                    // This package is derived from an original package,
17613                    // and this device has been updating from that original
17614                    // name.  We must continue using the original name, so
17615                    // rename the new package here.
17616                    pkg.setPackageName(oldName);
17617                    pkgName = pkg.packageName;
17618                    replace = true;
17619                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17620                            + oldName + " pkgName=" + pkgName);
17621                } else if (mPackages.containsKey(pkgName)) {
17622                    // This package, under its official name, already exists
17623                    // on the device; we should replace it.
17624                    replace = true;
17625                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17626                }
17627
17628                // Child packages are installed through the parent package
17629                if (pkg.parentPackage != null) {
17630                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17631                            "Package " + pkg.packageName + " is child of package "
17632                                    + pkg.parentPackage.parentPackage + ". Child packages "
17633                                    + "can be updated only through the parent package.");
17634                    return;
17635                }
17636
17637                if (replace) {
17638                    // Prevent apps opting out from runtime permissions
17639                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17640                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17641                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17642                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17643                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17644                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17645                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17646                                        + " doesn't support runtime permissions but the old"
17647                                        + " target SDK " + oldTargetSdk + " does.");
17648                        return;
17649                    }
17650                    // Prevent apps from downgrading their targetSandbox.
17651                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17652                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17653                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17654                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17655                                "Package " + pkg.packageName + " new target sandbox "
17656                                + newTargetSandbox + " is incompatible with the previous value of"
17657                                + oldTargetSandbox + ".");
17658                        return;
17659                    }
17660
17661                    // Prevent installing of child packages
17662                    if (oldPackage.parentPackage != null) {
17663                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17664                                "Package " + pkg.packageName + " is child of package "
17665                                        + oldPackage.parentPackage + ". Child packages "
17666                                        + "can be updated only through the parent package.");
17667                        return;
17668                    }
17669                }
17670            }
17671
17672            PackageSetting ps = mSettings.mPackages.get(pkgName);
17673            if (ps != null) {
17674                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17675
17676                // Static shared libs have same package with different versions where
17677                // we internally use a synthetic package name to allow multiple versions
17678                // of the same package, therefore we need to compare signatures against
17679                // the package setting for the latest library version.
17680                PackageSetting signatureCheckPs = ps;
17681                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17682                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17683                    if (libraryEntry != null) {
17684                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17685                    }
17686                }
17687
17688                // Quick sanity check that we're signed correctly if updating;
17689                // we'll check this again later when scanning, but we want to
17690                // bail early here before tripping over redefined permissions.
17691                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
17692                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
17693                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17694                                + pkg.packageName + " upgrade keys do not match the "
17695                                + "previously installed version");
17696                        return;
17697                    }
17698                } else {
17699                    try {
17700                        verifySignaturesLP(signatureCheckPs, pkg);
17701                    } catch (PackageManagerException e) {
17702                        res.setError(e.error, e.getMessage());
17703                        return;
17704                    }
17705                }
17706
17707                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17708                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17709                    systemApp = (ps.pkg.applicationInfo.flags &
17710                            ApplicationInfo.FLAG_SYSTEM) != 0;
17711                }
17712                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17713            }
17714
17715            int N = pkg.permissions.size();
17716            for (int i = N-1; i >= 0; i--) {
17717                PackageParser.Permission perm = pkg.permissions.get(i);
17718                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
17719
17720                // Don't allow anyone but the system to define ephemeral permissions.
17721                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
17722                        && !systemApp) {
17723                    Slog.w(TAG, "Non-System package " + pkg.packageName
17724                            + " attempting to delcare ephemeral permission "
17725                            + perm.info.name + "; Removing ephemeral.");
17726                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
17727                }
17728                // Check whether the newly-scanned package wants to define an already-defined perm
17729                if (bp != null) {
17730                    // If the defining package is signed with our cert, it's okay.  This
17731                    // also includes the "updating the same package" case, of course.
17732                    // "updating same package" could also involve key-rotation.
17733                    final boolean sigsOk;
17734                    if (bp.sourcePackage.equals(pkg.packageName)
17735                            && (bp.packageSetting instanceof PackageSetting)
17736                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
17737                                    scanFlags))) {
17738                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
17739                    } else {
17740                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
17741                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
17742                    }
17743                    if (!sigsOk) {
17744                        // If the owning package is the system itself, we log but allow
17745                        // install to proceed; we fail the install on all other permission
17746                        // redefinitions.
17747                        if (!bp.sourcePackage.equals("android")) {
17748                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17749                                    + pkg.packageName + " attempting to redeclare permission "
17750                                    + perm.info.name + " already owned by " + bp.sourcePackage);
17751                            res.origPermission = perm.info.name;
17752                            res.origPackage = bp.sourcePackage;
17753                            return;
17754                        } else {
17755                            Slog.w(TAG, "Package " + pkg.packageName
17756                                    + " attempting to redeclare system permission "
17757                                    + perm.info.name + "; ignoring new declaration");
17758                            pkg.permissions.remove(i);
17759                        }
17760                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17761                        // Prevent apps to change protection level to dangerous from any other
17762                        // type as this would allow a privilege escalation where an app adds a
17763                        // normal/signature permission in other app's group and later redefines
17764                        // it as dangerous leading to the group auto-grant.
17765                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17766                                == PermissionInfo.PROTECTION_DANGEROUS) {
17767                            if (bp != null && !bp.isRuntime()) {
17768                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17769                                        + "non-runtime permission " + perm.info.name
17770                                        + " to runtime; keeping old protection level");
17771                                perm.info.protectionLevel = bp.protectionLevel;
17772                            }
17773                        }
17774                    }
17775                }
17776            }
17777        }
17778
17779        if (systemApp) {
17780            if (onExternal) {
17781                // Abort update; system app can't be replaced with app on sdcard
17782                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17783                        "Cannot install updates to system apps on sdcard");
17784                return;
17785            } else if (instantApp) {
17786                // Abort update; system app can't be replaced with an instant app
17787                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17788                        "Cannot update a system app with an instant app");
17789                return;
17790            }
17791        }
17792
17793        if (args.move != null) {
17794            // We did an in-place move, so dex is ready to roll
17795            scanFlags |= SCAN_NO_DEX;
17796            scanFlags |= SCAN_MOVE;
17797
17798            synchronized (mPackages) {
17799                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17800                if (ps == null) {
17801                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17802                            "Missing settings for moved package " + pkgName);
17803                }
17804
17805                // We moved the entire application as-is, so bring over the
17806                // previously derived ABI information.
17807                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17808                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17809            }
17810
17811        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17812            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17813            scanFlags |= SCAN_NO_DEX;
17814
17815            try {
17816                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17817                    args.abiOverride : pkg.cpuAbiOverride);
17818                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
17819                        true /*extractLibs*/, mAppLib32InstallDir);
17820            } catch (PackageManagerException pme) {
17821                Slog.e(TAG, "Error deriving application ABI", pme);
17822                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17823                return;
17824            }
17825
17826            // Shared libraries for the package need to be updated.
17827            synchronized (mPackages) {
17828                try {
17829                    updateSharedLibrariesLPr(pkg, null);
17830                } catch (PackageManagerException e) {
17831                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17832                }
17833            }
17834
17835            // dexopt can take some time to complete, so, for instant apps, we skip this
17836            // step during installation. Instead, we'll take extra time the first time the
17837            // instant app starts. It's preferred to do it this way to provide continuous
17838            // progress to the user instead of mysteriously blocking somewhere in the
17839            // middle of running an instant app.
17840            if (!instantApp) {
17841                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17842                // Do not run PackageDexOptimizer through the local performDexOpt
17843                // method because `pkg` may not be in `mPackages` yet.
17844                //
17845                // Also, don't fail application installs if the dexopt step fails.
17846                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17847                        null /* instructionSets */, false /* checkProfiles */,
17848                        getCompilerFilterForReason(REASON_INSTALL),
17849                        getOrCreateCompilerPackageStats(pkg),
17850                        mDexManager.isUsedByOtherApps(pkg.packageName));
17851                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17852            }
17853
17854            // Notify BackgroundDexOptService that the package has been changed.
17855            // If this is an update of a package which used to fail to compile,
17856            // BDOS will remove it from its blacklist.
17857            // TODO: Layering violation
17858            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17859        }
17860
17861        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17862            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17863            return;
17864        }
17865
17866        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17867
17868        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17869                "installPackageLI")) {
17870            if (replace) {
17871                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17872                    // Static libs have a synthetic package name containing the version
17873                    // and cannot be updated as an update would get a new package name,
17874                    // unless this is the exact same version code which is useful for
17875                    // development.
17876                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17877                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
17878                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17879                                + "static-shared libs cannot be updated");
17880                        return;
17881                    }
17882                }
17883                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
17884                        installerPackageName, res, args.installReason);
17885            } else {
17886                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17887                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17888            }
17889        }
17890
17891        synchronized (mPackages) {
17892            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17893            if (ps != null) {
17894                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17895                ps.setUpdateAvailable(false /*updateAvailable*/);
17896            }
17897
17898            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17899            for (int i = 0; i < childCount; i++) {
17900                PackageParser.Package childPkg = pkg.childPackages.get(i);
17901                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17902                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17903                if (childPs != null) {
17904                    childRes.newUsers = childPs.queryInstalledUsers(
17905                            sUserManager.getUserIds(), true);
17906                }
17907            }
17908
17909            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17910                updateSequenceNumberLP(pkgName, res.newUsers);
17911                updateInstantAppInstallerLocked(pkgName);
17912            }
17913        }
17914    }
17915
17916    private void startIntentFilterVerifications(int userId, boolean replacing,
17917            PackageParser.Package pkg) {
17918        if (mIntentFilterVerifierComponent == null) {
17919            Slog.w(TAG, "No IntentFilter verification will not be done as "
17920                    + "there is no IntentFilterVerifier available!");
17921            return;
17922        }
17923
17924        final int verifierUid = getPackageUid(
17925                mIntentFilterVerifierComponent.getPackageName(),
17926                MATCH_DEBUG_TRIAGED_MISSING,
17927                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17928
17929        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17930        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17931        mHandler.sendMessage(msg);
17932
17933        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17934        for (int i = 0; i < childCount; i++) {
17935            PackageParser.Package childPkg = pkg.childPackages.get(i);
17936            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17937            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17938            mHandler.sendMessage(msg);
17939        }
17940    }
17941
17942    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17943            PackageParser.Package pkg) {
17944        int size = pkg.activities.size();
17945        if (size == 0) {
17946            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17947                    "No activity, so no need to verify any IntentFilter!");
17948            return;
17949        }
17950
17951        final boolean hasDomainURLs = hasDomainURLs(pkg);
17952        if (!hasDomainURLs) {
17953            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17954                    "No domain URLs, so no need to verify any IntentFilter!");
17955            return;
17956        }
17957
17958        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17959                + " if any IntentFilter from the " + size
17960                + " Activities needs verification ...");
17961
17962        int count = 0;
17963        final String packageName = pkg.packageName;
17964
17965        synchronized (mPackages) {
17966            // If this is a new install and we see that we've already run verification for this
17967            // package, we have nothing to do: it means the state was restored from backup.
17968            if (!replacing) {
17969                IntentFilterVerificationInfo ivi =
17970                        mSettings.getIntentFilterVerificationLPr(packageName);
17971                if (ivi != null) {
17972                    if (DEBUG_DOMAIN_VERIFICATION) {
17973                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17974                                + ivi.getStatusString());
17975                    }
17976                    return;
17977                }
17978            }
17979
17980            // If any filters need to be verified, then all need to be.
17981            boolean needToVerify = false;
17982            for (PackageParser.Activity a : pkg.activities) {
17983                for (ActivityIntentInfo filter : a.intents) {
17984                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17985                        if (DEBUG_DOMAIN_VERIFICATION) {
17986                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
17987                        }
17988                        needToVerify = true;
17989                        break;
17990                    }
17991                }
17992            }
17993
17994            if (needToVerify) {
17995                final int verificationId = mIntentFilterVerificationToken++;
17996                for (PackageParser.Activity a : pkg.activities) {
17997                    for (ActivityIntentInfo filter : a.intents) {
17998                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17999                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18000                                    "Verification needed for IntentFilter:" + filter.toString());
18001                            mIntentFilterVerifier.addOneIntentFilterVerification(
18002                                    verifierUid, userId, verificationId, filter, packageName);
18003                            count++;
18004                        }
18005                    }
18006                }
18007            }
18008        }
18009
18010        if (count > 0) {
18011            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18012                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18013                    +  " for userId:" + userId);
18014            mIntentFilterVerifier.startVerifications(userId);
18015        } else {
18016            if (DEBUG_DOMAIN_VERIFICATION) {
18017                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18018            }
18019        }
18020    }
18021
18022    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18023        final ComponentName cn  = filter.activity.getComponentName();
18024        final String packageName = cn.getPackageName();
18025
18026        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18027                packageName);
18028        if (ivi == null) {
18029            return true;
18030        }
18031        int status = ivi.getStatus();
18032        switch (status) {
18033            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18034            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18035                return true;
18036
18037            default:
18038                // Nothing to do
18039                return false;
18040        }
18041    }
18042
18043    private static boolean isMultiArch(ApplicationInfo info) {
18044        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18045    }
18046
18047    private static boolean isExternal(PackageParser.Package pkg) {
18048        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18049    }
18050
18051    private static boolean isExternal(PackageSetting ps) {
18052        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18053    }
18054
18055    private static boolean isSystemApp(PackageParser.Package pkg) {
18056        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18057    }
18058
18059    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18060        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18061    }
18062
18063    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18064        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18065    }
18066
18067    private static boolean isSystemApp(PackageSetting ps) {
18068        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18069    }
18070
18071    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18072        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18073    }
18074
18075    private int packageFlagsToInstallFlags(PackageSetting ps) {
18076        int installFlags = 0;
18077        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18078            // This existing package was an external ASEC install when we have
18079            // the external flag without a UUID
18080            installFlags |= PackageManager.INSTALL_EXTERNAL;
18081        }
18082        if (ps.isForwardLocked()) {
18083            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18084        }
18085        return installFlags;
18086    }
18087
18088    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18089        if (isExternal(pkg)) {
18090            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18091                return StorageManager.UUID_PRIMARY_PHYSICAL;
18092            } else {
18093                return pkg.volumeUuid;
18094            }
18095        } else {
18096            return StorageManager.UUID_PRIVATE_INTERNAL;
18097        }
18098    }
18099
18100    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18101        if (isExternal(pkg)) {
18102            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18103                return mSettings.getExternalVersion();
18104            } else {
18105                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18106            }
18107        } else {
18108            return mSettings.getInternalVersion();
18109        }
18110    }
18111
18112    private void deleteTempPackageFiles() {
18113        final FilenameFilter filter = new FilenameFilter() {
18114            public boolean accept(File dir, String name) {
18115                return name.startsWith("vmdl") && name.endsWith(".tmp");
18116            }
18117        };
18118        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18119            file.delete();
18120        }
18121    }
18122
18123    @Override
18124    public void deletePackageAsUser(String packageName, int versionCode,
18125            IPackageDeleteObserver observer, int userId, int flags) {
18126        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18127                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18128    }
18129
18130    @Override
18131    public void deletePackageVersioned(VersionedPackage versionedPackage,
18132            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18133        mContext.enforceCallingOrSelfPermission(
18134                android.Manifest.permission.DELETE_PACKAGES, null);
18135        Preconditions.checkNotNull(versionedPackage);
18136        Preconditions.checkNotNull(observer);
18137        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18138                PackageManager.VERSION_CODE_HIGHEST,
18139                Integer.MAX_VALUE, "versionCode must be >= -1");
18140
18141        final String packageName = versionedPackage.getPackageName();
18142        final int versionCode = versionedPackage.getVersionCode();
18143        final String internalPackageName;
18144        synchronized (mPackages) {
18145            // Normalize package name to handle renamed packages and static libs
18146            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18147                    versionedPackage.getVersionCode());
18148        }
18149
18150        final int uid = Binder.getCallingUid();
18151        if (!isOrphaned(internalPackageName)
18152                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18153            try {
18154                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18155                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18156                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18157                observer.onUserActionRequired(intent);
18158            } catch (RemoteException re) {
18159            }
18160            return;
18161        }
18162        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18163        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18164        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18165            mContext.enforceCallingOrSelfPermission(
18166                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18167                    "deletePackage for user " + userId);
18168        }
18169
18170        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18171            try {
18172                observer.onPackageDeleted(packageName,
18173                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18174            } catch (RemoteException re) {
18175            }
18176            return;
18177        }
18178
18179        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18180            try {
18181                observer.onPackageDeleted(packageName,
18182                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18183            } catch (RemoteException re) {
18184            }
18185            return;
18186        }
18187
18188        if (DEBUG_REMOVE) {
18189            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18190                    + " deleteAllUsers: " + deleteAllUsers + " version="
18191                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18192                    ? "VERSION_CODE_HIGHEST" : versionCode));
18193        }
18194        // Queue up an async operation since the package deletion may take a little while.
18195        mHandler.post(new Runnable() {
18196            public void run() {
18197                mHandler.removeCallbacks(this);
18198                int returnCode;
18199                if (!deleteAllUsers) {
18200                    returnCode = deletePackageX(internalPackageName, versionCode,
18201                            userId, deleteFlags);
18202                } else {
18203                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
18204                            internalPackageName, users);
18205                    // If nobody is blocking uninstall, proceed with delete for all users
18206                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18207                        returnCode = deletePackageX(internalPackageName, versionCode,
18208                                userId, deleteFlags);
18209                    } else {
18210                        // Otherwise uninstall individually for users with blockUninstalls=false
18211                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18212                        for (int userId : users) {
18213                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18214                                returnCode = deletePackageX(internalPackageName, versionCode,
18215                                        userId, userFlags);
18216                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18217                                    Slog.w(TAG, "Package delete failed for user " + userId
18218                                            + ", returnCode " + returnCode);
18219                                }
18220                            }
18221                        }
18222                        // The app has only been marked uninstalled for certain users.
18223                        // We still need to report that delete was blocked
18224                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18225                    }
18226                }
18227                try {
18228                    observer.onPackageDeleted(packageName, returnCode, null);
18229                } catch (RemoteException e) {
18230                    Log.i(TAG, "Observer no longer exists.");
18231                } //end catch
18232            } //end run
18233        });
18234    }
18235
18236    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18237        if (pkg.staticSharedLibName != null) {
18238            return pkg.manifestPackageName;
18239        }
18240        return pkg.packageName;
18241    }
18242
18243    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18244        // Handle renamed packages
18245        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18246        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18247
18248        // Is this a static library?
18249        SparseArray<SharedLibraryEntry> versionedLib =
18250                mStaticLibsByDeclaringPackage.get(packageName);
18251        if (versionedLib == null || versionedLib.size() <= 0) {
18252            return packageName;
18253        }
18254
18255        // Figure out which lib versions the caller can see
18256        SparseIntArray versionsCallerCanSee = null;
18257        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18258        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18259                && callingAppId != Process.ROOT_UID) {
18260            versionsCallerCanSee = new SparseIntArray();
18261            String libName = versionedLib.valueAt(0).info.getName();
18262            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18263            if (uidPackages != null) {
18264                for (String uidPackage : uidPackages) {
18265                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18266                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18267                    if (libIdx >= 0) {
18268                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18269                        versionsCallerCanSee.append(libVersion, libVersion);
18270                    }
18271                }
18272            }
18273        }
18274
18275        // Caller can see nothing - done
18276        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18277            return packageName;
18278        }
18279
18280        // Find the version the caller can see and the app version code
18281        SharedLibraryEntry highestVersion = null;
18282        final int versionCount = versionedLib.size();
18283        for (int i = 0; i < versionCount; i++) {
18284            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18285            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18286                    libEntry.info.getVersion()) < 0) {
18287                continue;
18288            }
18289            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18290            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18291                if (libVersionCode == versionCode) {
18292                    return libEntry.apk;
18293                }
18294            } else if (highestVersion == null) {
18295                highestVersion = libEntry;
18296            } else if (libVersionCode  > highestVersion.info
18297                    .getDeclaringPackage().getVersionCode()) {
18298                highestVersion = libEntry;
18299            }
18300        }
18301
18302        if (highestVersion != null) {
18303            return highestVersion.apk;
18304        }
18305
18306        return packageName;
18307    }
18308
18309    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18310        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18311              || callingUid == Process.SYSTEM_UID) {
18312            return true;
18313        }
18314        final int callingUserId = UserHandle.getUserId(callingUid);
18315        // If the caller installed the pkgName, then allow it to silently uninstall.
18316        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18317            return true;
18318        }
18319
18320        // Allow package verifier to silently uninstall.
18321        if (mRequiredVerifierPackage != null &&
18322                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18323            return true;
18324        }
18325
18326        // Allow package uninstaller to silently uninstall.
18327        if (mRequiredUninstallerPackage != null &&
18328                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18329            return true;
18330        }
18331
18332        // Allow storage manager to silently uninstall.
18333        if (mStorageManagerPackage != null &&
18334                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18335            return true;
18336        }
18337
18338        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18339        // uninstall for device owner provisioning.
18340        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18341                == PERMISSION_GRANTED) {
18342            return true;
18343        }
18344
18345        return false;
18346    }
18347
18348    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18349        int[] result = EMPTY_INT_ARRAY;
18350        for (int userId : userIds) {
18351            if (getBlockUninstallForUser(packageName, userId)) {
18352                result = ArrayUtils.appendInt(result, userId);
18353            }
18354        }
18355        return result;
18356    }
18357
18358    @Override
18359    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18360        final int callingUid = Binder.getCallingUid();
18361        if (getInstantAppPackageName(callingUid) != null
18362                && !isCallerSameApp(packageName, callingUid)) {
18363            return false;
18364        }
18365        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18366    }
18367
18368    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18369        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18370                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18371        try {
18372            if (dpm != null) {
18373                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18374                        /* callingUserOnly =*/ false);
18375                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18376                        : deviceOwnerComponentName.getPackageName();
18377                // Does the package contains the device owner?
18378                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18379                // this check is probably not needed, since DO should be registered as a device
18380                // admin on some user too. (Original bug for this: b/17657954)
18381                if (packageName.equals(deviceOwnerPackageName)) {
18382                    return true;
18383                }
18384                // Does it contain a device admin for any user?
18385                int[] users;
18386                if (userId == UserHandle.USER_ALL) {
18387                    users = sUserManager.getUserIds();
18388                } else {
18389                    users = new int[]{userId};
18390                }
18391                for (int i = 0; i < users.length; ++i) {
18392                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18393                        return true;
18394                    }
18395                }
18396            }
18397        } catch (RemoteException e) {
18398        }
18399        return false;
18400    }
18401
18402    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18403        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18404    }
18405
18406    /**
18407     *  This method is an internal method that could be get invoked either
18408     *  to delete an installed package or to clean up a failed installation.
18409     *  After deleting an installed package, a broadcast is sent to notify any
18410     *  listeners that the package has been removed. For cleaning up a failed
18411     *  installation, the broadcast is not necessary since the package's
18412     *  installation wouldn't have sent the initial broadcast either
18413     *  The key steps in deleting a package are
18414     *  deleting the package information in internal structures like mPackages,
18415     *  deleting the packages base directories through installd
18416     *  updating mSettings to reflect current status
18417     *  persisting settings for later use
18418     *  sending a broadcast if necessary
18419     */
18420    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18421        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18422        final boolean res;
18423
18424        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18425                ? UserHandle.USER_ALL : userId;
18426
18427        if (isPackageDeviceAdmin(packageName, removeUser)) {
18428            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18429            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18430        }
18431
18432        PackageSetting uninstalledPs = null;
18433        PackageParser.Package pkg = null;
18434
18435        // for the uninstall-updates case and restricted profiles, remember the per-
18436        // user handle installed state
18437        int[] allUsers;
18438        synchronized (mPackages) {
18439            uninstalledPs = mSettings.mPackages.get(packageName);
18440            if (uninstalledPs == null) {
18441                Slog.w(TAG, "Not removing non-existent package " + packageName);
18442                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18443            }
18444
18445            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18446                    && uninstalledPs.versionCode != versionCode) {
18447                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18448                        + uninstalledPs.versionCode + " != " + versionCode);
18449                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18450            }
18451
18452            // Static shared libs can be declared by any package, so let us not
18453            // allow removing a package if it provides a lib others depend on.
18454            pkg = mPackages.get(packageName);
18455
18456            allUsers = sUserManager.getUserIds();
18457
18458            if (pkg != null && pkg.staticSharedLibName != null) {
18459                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18460                        pkg.staticSharedLibVersion);
18461                if (libEntry != null) {
18462                    for (int currUserId : allUsers) {
18463                        if (userId != UserHandle.USER_ALL && userId != currUserId) {
18464                            continue;
18465                        }
18466                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18467                                libEntry.info, 0, currUserId);
18468                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18469                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18470                                    + " hosting lib " + libEntry.info.getName() + " version "
18471                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18472                                    + " for user " + currUserId);
18473                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18474                        }
18475                    }
18476                }
18477            }
18478
18479            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18480        }
18481
18482        final int freezeUser;
18483        if (isUpdatedSystemApp(uninstalledPs)
18484                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18485            // We're downgrading a system app, which will apply to all users, so
18486            // freeze them all during the downgrade
18487            freezeUser = UserHandle.USER_ALL;
18488        } else {
18489            freezeUser = removeUser;
18490        }
18491
18492        synchronized (mInstallLock) {
18493            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18494            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18495                    deleteFlags, "deletePackageX")) {
18496                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18497                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18498            }
18499            synchronized (mPackages) {
18500                if (res) {
18501                    if (pkg != null) {
18502                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18503                    }
18504                    updateSequenceNumberLP(packageName, info.removedUsers);
18505                    updateInstantAppInstallerLocked(packageName);
18506                }
18507            }
18508        }
18509
18510        if (res) {
18511            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18512            info.sendPackageRemovedBroadcasts(killApp);
18513            info.sendSystemPackageUpdatedBroadcasts();
18514            info.sendSystemPackageAppearedBroadcasts();
18515        }
18516        // Force a gc here.
18517        Runtime.getRuntime().gc();
18518        // Delete the resources here after sending the broadcast to let
18519        // other processes clean up before deleting resources.
18520        if (info.args != null) {
18521            synchronized (mInstallLock) {
18522                info.args.doPostDeleteLI(true);
18523            }
18524        }
18525
18526        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18527    }
18528
18529    static class PackageRemovedInfo {
18530        final PackageSender packageSender;
18531        String removedPackage;
18532        String installerPackageName;
18533        int uid = -1;
18534        int removedAppId = -1;
18535        int[] origUsers;
18536        int[] removedUsers = null;
18537        int[] broadcastUsers = null;
18538        SparseArray<Integer> installReasons;
18539        boolean isRemovedPackageSystemUpdate = false;
18540        boolean isUpdate;
18541        boolean dataRemoved;
18542        boolean removedForAllUsers;
18543        boolean isStaticSharedLib;
18544        // Clean up resources deleted packages.
18545        InstallArgs args = null;
18546        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18547        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18548
18549        PackageRemovedInfo(PackageSender packageSender) {
18550            this.packageSender = packageSender;
18551        }
18552
18553        void sendPackageRemovedBroadcasts(boolean killApp) {
18554            sendPackageRemovedBroadcastInternal(killApp);
18555            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18556            for (int i = 0; i < childCount; i++) {
18557                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18558                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18559            }
18560        }
18561
18562        void sendSystemPackageUpdatedBroadcasts() {
18563            if (isRemovedPackageSystemUpdate) {
18564                sendSystemPackageUpdatedBroadcastsInternal();
18565                final int childCount = (removedChildPackages != null)
18566                        ? removedChildPackages.size() : 0;
18567                for (int i = 0; i < childCount; i++) {
18568                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18569                    if (childInfo.isRemovedPackageSystemUpdate) {
18570                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18571                    }
18572                }
18573            }
18574        }
18575
18576        void sendSystemPackageAppearedBroadcasts() {
18577            final int packageCount = (appearedChildPackages != null)
18578                    ? appearedChildPackages.size() : 0;
18579            for (int i = 0; i < packageCount; i++) {
18580                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18581                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18582                    true, UserHandle.getAppId(installedInfo.uid),
18583                    installedInfo.newUsers);
18584            }
18585        }
18586
18587        private void sendSystemPackageUpdatedBroadcastsInternal() {
18588            Bundle extras = new Bundle(2);
18589            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18590            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18591            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18592                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18593            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18594                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18595            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18596                null, null, 0, removedPackage, null, null);
18597            if (installerPackageName != null) {
18598                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18599                        removedPackage, extras, 0 /*flags*/,
18600                        installerPackageName, null, null);
18601                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18602                        removedPackage, extras, 0 /*flags*/,
18603                        installerPackageName, null, null);
18604            }
18605        }
18606
18607        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18608            // Don't send static shared library removal broadcasts as these
18609            // libs are visible only the the apps that depend on them an one
18610            // cannot remove the library if it has a dependency.
18611            if (isStaticSharedLib) {
18612                return;
18613            }
18614            Bundle extras = new Bundle(2);
18615            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18616            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18617            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18618            if (isUpdate || isRemovedPackageSystemUpdate) {
18619                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18620            }
18621            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18622            if (removedPackage != null) {
18623                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18624                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
18625                if (installerPackageName != null) {
18626                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18627                            removedPackage, extras, 0 /*flags*/,
18628                            installerPackageName, null, broadcastUsers);
18629                }
18630                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18631                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18632                        removedPackage, extras,
18633                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18634                        null, null, broadcastUsers);
18635                }
18636            }
18637            if (removedAppId >= 0) {
18638                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18639                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18640                    null, null, broadcastUsers);
18641            }
18642        }
18643
18644        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18645            removedUsers = userIds;
18646            if (removedUsers == null) {
18647                broadcastUsers = null;
18648                return;
18649            }
18650
18651            broadcastUsers = EMPTY_INT_ARRAY;
18652            for (int i = userIds.length - 1; i >= 0; --i) {
18653                final int userId = userIds[i];
18654                if (deletedPackageSetting.getInstantApp(userId)) {
18655                    continue;
18656                }
18657                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18658            }
18659        }
18660    }
18661
18662    /*
18663     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18664     * flag is not set, the data directory is removed as well.
18665     * make sure this flag is set for partially installed apps. If not its meaningless to
18666     * delete a partially installed application.
18667     */
18668    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18669            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18670        String packageName = ps.name;
18671        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18672        // Retrieve object to delete permissions for shared user later on
18673        final PackageParser.Package deletedPkg;
18674        final PackageSetting deletedPs;
18675        // reader
18676        synchronized (mPackages) {
18677            deletedPkg = mPackages.get(packageName);
18678            deletedPs = mSettings.mPackages.get(packageName);
18679            if (outInfo != null) {
18680                outInfo.removedPackage = packageName;
18681                outInfo.installerPackageName = ps.installerPackageName;
18682                outInfo.isStaticSharedLib = deletedPkg != null
18683                        && deletedPkg.staticSharedLibName != null;
18684                outInfo.populateUsers(deletedPs == null ? null
18685                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18686            }
18687        }
18688
18689        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
18690
18691        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18692            final PackageParser.Package resolvedPkg;
18693            if (deletedPkg != null) {
18694                resolvedPkg = deletedPkg;
18695            } else {
18696                // We don't have a parsed package when it lives on an ejected
18697                // adopted storage device, so fake something together
18698                resolvedPkg = new PackageParser.Package(ps.name);
18699                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18700            }
18701            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18702                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18703            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18704            if (outInfo != null) {
18705                outInfo.dataRemoved = true;
18706            }
18707            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18708        }
18709
18710        int removedAppId = -1;
18711
18712        // writer
18713        synchronized (mPackages) {
18714            boolean installedStateChanged = false;
18715            if (deletedPs != null) {
18716                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18717                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18718                    clearDefaultBrowserIfNeeded(packageName);
18719                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18720                    removedAppId = mSettings.removePackageLPw(packageName);
18721                    if (outInfo != null) {
18722                        outInfo.removedAppId = removedAppId;
18723                    }
18724                    updatePermissionsLPw(deletedPs.name, null, 0);
18725                    if (deletedPs.sharedUser != null) {
18726                        // Remove permissions associated with package. Since runtime
18727                        // permissions are per user we have to kill the removed package
18728                        // or packages running under the shared user of the removed
18729                        // package if revoking the permissions requested only by the removed
18730                        // package is successful and this causes a change in gids.
18731                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18732                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18733                                    userId);
18734                            if (userIdToKill == UserHandle.USER_ALL
18735                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18736                                // If gids changed for this user, kill all affected packages.
18737                                mHandler.post(new Runnable() {
18738                                    @Override
18739                                    public void run() {
18740                                        // This has to happen with no lock held.
18741                                        killApplication(deletedPs.name, deletedPs.appId,
18742                                                KILL_APP_REASON_GIDS_CHANGED);
18743                                    }
18744                                });
18745                                break;
18746                            }
18747                        }
18748                    }
18749                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18750                }
18751                // make sure to preserve per-user disabled state if this removal was just
18752                // a downgrade of a system app to the factory package
18753                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18754                    if (DEBUG_REMOVE) {
18755                        Slog.d(TAG, "Propagating install state across downgrade");
18756                    }
18757                    for (int userId : allUserHandles) {
18758                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18759                        if (DEBUG_REMOVE) {
18760                            Slog.d(TAG, "    user " + userId + " => " + installed);
18761                        }
18762                        if (installed != ps.getInstalled(userId)) {
18763                            installedStateChanged = true;
18764                        }
18765                        ps.setInstalled(installed, userId);
18766                    }
18767                }
18768            }
18769            // can downgrade to reader
18770            if (writeSettings) {
18771                // Save settings now
18772                mSettings.writeLPr();
18773            }
18774            if (installedStateChanged) {
18775                mSettings.writeKernelMappingLPr(ps);
18776            }
18777        }
18778        if (removedAppId != -1) {
18779            // A user ID was deleted here. Go through all users and remove it
18780            // from KeyStore.
18781            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18782        }
18783    }
18784
18785    static boolean locationIsPrivileged(File path) {
18786        try {
18787            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
18788                    .getCanonicalPath();
18789            return path.getCanonicalPath().startsWith(privilegedAppDir);
18790        } catch (IOException e) {
18791            Slog.e(TAG, "Unable to access code path " + path);
18792        }
18793        return false;
18794    }
18795
18796    /*
18797     * Tries to delete system package.
18798     */
18799    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18800            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18801            boolean writeSettings) {
18802        if (deletedPs.parentPackageName != null) {
18803            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18804            return false;
18805        }
18806
18807        final boolean applyUserRestrictions
18808                = (allUserHandles != null) && (outInfo.origUsers != null);
18809        final PackageSetting disabledPs;
18810        // Confirm if the system package has been updated
18811        // An updated system app can be deleted. This will also have to restore
18812        // the system pkg from system partition
18813        // reader
18814        synchronized (mPackages) {
18815            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18816        }
18817
18818        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18819                + " disabledPs=" + disabledPs);
18820
18821        if (disabledPs == null) {
18822            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18823            return false;
18824        } else if (DEBUG_REMOVE) {
18825            Slog.d(TAG, "Deleting system pkg from data partition");
18826        }
18827
18828        if (DEBUG_REMOVE) {
18829            if (applyUserRestrictions) {
18830                Slog.d(TAG, "Remembering install states:");
18831                for (int userId : allUserHandles) {
18832                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18833                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18834                }
18835            }
18836        }
18837
18838        // Delete the updated package
18839        outInfo.isRemovedPackageSystemUpdate = true;
18840        if (outInfo.removedChildPackages != null) {
18841            final int childCount = (deletedPs.childPackageNames != null)
18842                    ? deletedPs.childPackageNames.size() : 0;
18843            for (int i = 0; i < childCount; i++) {
18844                String childPackageName = deletedPs.childPackageNames.get(i);
18845                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18846                        .contains(childPackageName)) {
18847                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18848                            childPackageName);
18849                    if (childInfo != null) {
18850                        childInfo.isRemovedPackageSystemUpdate = true;
18851                    }
18852                }
18853            }
18854        }
18855
18856        if (disabledPs.versionCode < deletedPs.versionCode) {
18857            // Delete data for downgrades
18858            flags &= ~PackageManager.DELETE_KEEP_DATA;
18859        } else {
18860            // Preserve data by setting flag
18861            flags |= PackageManager.DELETE_KEEP_DATA;
18862        }
18863
18864        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18865                outInfo, writeSettings, disabledPs.pkg);
18866        if (!ret) {
18867            return false;
18868        }
18869
18870        // writer
18871        synchronized (mPackages) {
18872            // Reinstate the old system package
18873            enableSystemPackageLPw(disabledPs.pkg);
18874            // Remove any native libraries from the upgraded package.
18875            removeNativeBinariesLI(deletedPs);
18876        }
18877
18878        // Install the system package
18879        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18880        int parseFlags = mDefParseFlags
18881                | PackageParser.PARSE_MUST_BE_APK
18882                | PackageParser.PARSE_IS_SYSTEM
18883                | PackageParser.PARSE_IS_SYSTEM_DIR;
18884        if (locationIsPrivileged(disabledPs.codePath)) {
18885            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
18886        }
18887
18888        final PackageParser.Package newPkg;
18889        try {
18890            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
18891                0 /* currentTime */, null);
18892        } catch (PackageManagerException e) {
18893            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18894                    + e.getMessage());
18895            return false;
18896        }
18897
18898        try {
18899            // update shared libraries for the newly re-installed system package
18900            updateSharedLibrariesLPr(newPkg, null);
18901        } catch (PackageManagerException e) {
18902            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18903        }
18904
18905        prepareAppDataAfterInstallLIF(newPkg);
18906
18907        // writer
18908        synchronized (mPackages) {
18909            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
18910
18911            // Propagate the permissions state as we do not want to drop on the floor
18912            // runtime permissions. The update permissions method below will take
18913            // care of removing obsolete permissions and grant install permissions.
18914            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
18915            updatePermissionsLPw(newPkg.packageName, newPkg,
18916                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
18917
18918            if (applyUserRestrictions) {
18919                boolean installedStateChanged = false;
18920                if (DEBUG_REMOVE) {
18921                    Slog.d(TAG, "Propagating install state across reinstall");
18922                }
18923                for (int userId : allUserHandles) {
18924                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18925                    if (DEBUG_REMOVE) {
18926                        Slog.d(TAG, "    user " + userId + " => " + installed);
18927                    }
18928                    if (installed != ps.getInstalled(userId)) {
18929                        installedStateChanged = true;
18930                    }
18931                    ps.setInstalled(installed, userId);
18932
18933                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18934                }
18935                // Regardless of writeSettings we need to ensure that this restriction
18936                // state propagation is persisted
18937                mSettings.writeAllUsersPackageRestrictionsLPr();
18938                if (installedStateChanged) {
18939                    mSettings.writeKernelMappingLPr(ps);
18940                }
18941            }
18942            // can downgrade to reader here
18943            if (writeSettings) {
18944                mSettings.writeLPr();
18945            }
18946        }
18947        return true;
18948    }
18949
18950    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18951            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18952            PackageRemovedInfo outInfo, boolean writeSettings,
18953            PackageParser.Package replacingPackage) {
18954        synchronized (mPackages) {
18955            if (outInfo != null) {
18956                outInfo.uid = ps.appId;
18957            }
18958
18959            if (outInfo != null && outInfo.removedChildPackages != null) {
18960                final int childCount = (ps.childPackageNames != null)
18961                        ? ps.childPackageNames.size() : 0;
18962                for (int i = 0; i < childCount; i++) {
18963                    String childPackageName = ps.childPackageNames.get(i);
18964                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18965                    if (childPs == null) {
18966                        return false;
18967                    }
18968                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18969                            childPackageName);
18970                    if (childInfo != null) {
18971                        childInfo.uid = childPs.appId;
18972                    }
18973                }
18974            }
18975        }
18976
18977        // Delete package data from internal structures and also remove data if flag is set
18978        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18979
18980        // Delete the child packages data
18981        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18982        for (int i = 0; i < childCount; i++) {
18983            PackageSetting childPs;
18984            synchronized (mPackages) {
18985                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18986            }
18987            if (childPs != null) {
18988                PackageRemovedInfo childOutInfo = (outInfo != null
18989                        && outInfo.removedChildPackages != null)
18990                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18991                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18992                        && (replacingPackage != null
18993                        && !replacingPackage.hasChildPackage(childPs.name))
18994                        ? flags & ~DELETE_KEEP_DATA : flags;
18995                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18996                        deleteFlags, writeSettings);
18997            }
18998        }
18999
19000        // Delete application code and resources only for parent packages
19001        if (ps.parentPackageName == null) {
19002            if (deleteCodeAndResources && (outInfo != null)) {
19003                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19004                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19005                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19006            }
19007        }
19008
19009        return true;
19010    }
19011
19012    @Override
19013    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19014            int userId) {
19015        mContext.enforceCallingOrSelfPermission(
19016                android.Manifest.permission.DELETE_PACKAGES, null);
19017        synchronized (mPackages) {
19018            // Cannot block uninstall of static shared libs as they are
19019            // considered a part of the using app (emulating static linking).
19020            // Also static libs are installed always on internal storage.
19021            PackageParser.Package pkg = mPackages.get(packageName);
19022            if (pkg != null && pkg.staticSharedLibName != null) {
19023                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19024                        + " providing static shared library: " + pkg.staticSharedLibName);
19025                return false;
19026            }
19027            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19028            mSettings.writePackageRestrictionsLPr(userId);
19029        }
19030        return true;
19031    }
19032
19033    @Override
19034    public boolean getBlockUninstallForUser(String packageName, int userId) {
19035        synchronized (mPackages) {
19036            return mSettings.getBlockUninstallLPr(userId, packageName);
19037        }
19038    }
19039
19040    @Override
19041    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19042        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19043        synchronized (mPackages) {
19044            PackageSetting ps = mSettings.mPackages.get(packageName);
19045            if (ps == null) {
19046                Log.w(TAG, "Package doesn't exist: " + packageName);
19047                return false;
19048            }
19049            if (systemUserApp) {
19050                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19051            } else {
19052                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19053            }
19054            mSettings.writeLPr();
19055        }
19056        return true;
19057    }
19058
19059    /*
19060     * This method handles package deletion in general
19061     */
19062    private boolean deletePackageLIF(String packageName, UserHandle user,
19063            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19064            PackageRemovedInfo outInfo, boolean writeSettings,
19065            PackageParser.Package replacingPackage) {
19066        if (packageName == null) {
19067            Slog.w(TAG, "Attempt to delete null packageName.");
19068            return false;
19069        }
19070
19071        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19072
19073        PackageSetting ps;
19074        synchronized (mPackages) {
19075            ps = mSettings.mPackages.get(packageName);
19076            if (ps == null) {
19077                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19078                return false;
19079            }
19080
19081            if (ps.parentPackageName != null && (!isSystemApp(ps)
19082                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19083                if (DEBUG_REMOVE) {
19084                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19085                            + ((user == null) ? UserHandle.USER_ALL : user));
19086                }
19087                final int removedUserId = (user != null) ? user.getIdentifier()
19088                        : UserHandle.USER_ALL;
19089                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19090                    return false;
19091                }
19092                markPackageUninstalledForUserLPw(ps, user);
19093                scheduleWritePackageRestrictionsLocked(user);
19094                return true;
19095            }
19096        }
19097
19098        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19099                && user.getIdentifier() != UserHandle.USER_ALL)) {
19100            // The caller is asking that the package only be deleted for a single
19101            // user.  To do this, we just mark its uninstalled state and delete
19102            // its data. If this is a system app, we only allow this to happen if
19103            // they have set the special DELETE_SYSTEM_APP which requests different
19104            // semantics than normal for uninstalling system apps.
19105            markPackageUninstalledForUserLPw(ps, user);
19106
19107            if (!isSystemApp(ps)) {
19108                // Do not uninstall the APK if an app should be cached
19109                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19110                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19111                    // Other user still have this package installed, so all
19112                    // we need to do is clear this user's data and save that
19113                    // it is uninstalled.
19114                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19115                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19116                        return false;
19117                    }
19118                    scheduleWritePackageRestrictionsLocked(user);
19119                    return true;
19120                } else {
19121                    // We need to set it back to 'installed' so the uninstall
19122                    // broadcasts will be sent correctly.
19123                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19124                    ps.setInstalled(true, user.getIdentifier());
19125                    mSettings.writeKernelMappingLPr(ps);
19126                }
19127            } else {
19128                // This is a system app, so we assume that the
19129                // other users still have this package installed, so all
19130                // we need to do is clear this user's data and save that
19131                // it is uninstalled.
19132                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19133                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19134                    return false;
19135                }
19136                scheduleWritePackageRestrictionsLocked(user);
19137                return true;
19138            }
19139        }
19140
19141        // If we are deleting a composite package for all users, keep track
19142        // of result for each child.
19143        if (ps.childPackageNames != null && outInfo != null) {
19144            synchronized (mPackages) {
19145                final int childCount = ps.childPackageNames.size();
19146                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19147                for (int i = 0; i < childCount; i++) {
19148                    String childPackageName = ps.childPackageNames.get(i);
19149                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19150                    childInfo.removedPackage = childPackageName;
19151                    childInfo.installerPackageName = ps.installerPackageName;
19152                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19153                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19154                    if (childPs != null) {
19155                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19156                    }
19157                }
19158            }
19159        }
19160
19161        boolean ret = false;
19162        if (isSystemApp(ps)) {
19163            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19164            // When an updated system application is deleted we delete the existing resources
19165            // as well and fall back to existing code in system partition
19166            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19167        } else {
19168            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19169            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19170                    outInfo, writeSettings, replacingPackage);
19171        }
19172
19173        // Take a note whether we deleted the package for all users
19174        if (outInfo != null) {
19175            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19176            if (outInfo.removedChildPackages != null) {
19177                synchronized (mPackages) {
19178                    final int childCount = outInfo.removedChildPackages.size();
19179                    for (int i = 0; i < childCount; i++) {
19180                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19181                        if (childInfo != null) {
19182                            childInfo.removedForAllUsers = mPackages.get(
19183                                    childInfo.removedPackage) == null;
19184                        }
19185                    }
19186                }
19187            }
19188            // If we uninstalled an update to a system app there may be some
19189            // child packages that appeared as they are declared in the system
19190            // app but were not declared in the update.
19191            if (isSystemApp(ps)) {
19192                synchronized (mPackages) {
19193                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19194                    final int childCount = (updatedPs.childPackageNames != null)
19195                            ? updatedPs.childPackageNames.size() : 0;
19196                    for (int i = 0; i < childCount; i++) {
19197                        String childPackageName = updatedPs.childPackageNames.get(i);
19198                        if (outInfo.removedChildPackages == null
19199                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19200                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19201                            if (childPs == null) {
19202                                continue;
19203                            }
19204                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19205                            installRes.name = childPackageName;
19206                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19207                            installRes.pkg = mPackages.get(childPackageName);
19208                            installRes.uid = childPs.pkg.applicationInfo.uid;
19209                            if (outInfo.appearedChildPackages == null) {
19210                                outInfo.appearedChildPackages = new ArrayMap<>();
19211                            }
19212                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19213                        }
19214                    }
19215                }
19216            }
19217        }
19218
19219        return ret;
19220    }
19221
19222    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19223        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19224                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19225        for (int nextUserId : userIds) {
19226            if (DEBUG_REMOVE) {
19227                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19228            }
19229            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19230                    false /*installed*/,
19231                    true /*stopped*/,
19232                    true /*notLaunched*/,
19233                    false /*hidden*/,
19234                    false /*suspended*/,
19235                    false /*instantApp*/,
19236                    null /*lastDisableAppCaller*/,
19237                    null /*enabledComponents*/,
19238                    null /*disabledComponents*/,
19239                    ps.readUserState(nextUserId).domainVerificationStatus,
19240                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19241        }
19242        mSettings.writeKernelMappingLPr(ps);
19243    }
19244
19245    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19246            PackageRemovedInfo outInfo) {
19247        final PackageParser.Package pkg;
19248        synchronized (mPackages) {
19249            pkg = mPackages.get(ps.name);
19250        }
19251
19252        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19253                : new int[] {userId};
19254        for (int nextUserId : userIds) {
19255            if (DEBUG_REMOVE) {
19256                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19257                        + nextUserId);
19258            }
19259
19260            destroyAppDataLIF(pkg, userId,
19261                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19262            destroyAppProfilesLIF(pkg, userId);
19263            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19264            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19265            schedulePackageCleaning(ps.name, nextUserId, false);
19266            synchronized (mPackages) {
19267                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19268                    scheduleWritePackageRestrictionsLocked(nextUserId);
19269                }
19270                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19271            }
19272        }
19273
19274        if (outInfo != null) {
19275            outInfo.removedPackage = ps.name;
19276            outInfo.installerPackageName = ps.installerPackageName;
19277            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19278            outInfo.removedAppId = ps.appId;
19279            outInfo.removedUsers = userIds;
19280            outInfo.broadcastUsers = userIds;
19281        }
19282
19283        return true;
19284    }
19285
19286    private final class ClearStorageConnection implements ServiceConnection {
19287        IMediaContainerService mContainerService;
19288
19289        @Override
19290        public void onServiceConnected(ComponentName name, IBinder service) {
19291            synchronized (this) {
19292                mContainerService = IMediaContainerService.Stub
19293                        .asInterface(Binder.allowBlocking(service));
19294                notifyAll();
19295            }
19296        }
19297
19298        @Override
19299        public void onServiceDisconnected(ComponentName name) {
19300        }
19301    }
19302
19303    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19304        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19305
19306        final boolean mounted;
19307        if (Environment.isExternalStorageEmulated()) {
19308            mounted = true;
19309        } else {
19310            final String status = Environment.getExternalStorageState();
19311
19312            mounted = status.equals(Environment.MEDIA_MOUNTED)
19313                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19314        }
19315
19316        if (!mounted) {
19317            return;
19318        }
19319
19320        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19321        int[] users;
19322        if (userId == UserHandle.USER_ALL) {
19323            users = sUserManager.getUserIds();
19324        } else {
19325            users = new int[] { userId };
19326        }
19327        final ClearStorageConnection conn = new ClearStorageConnection();
19328        if (mContext.bindServiceAsUser(
19329                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19330            try {
19331                for (int curUser : users) {
19332                    long timeout = SystemClock.uptimeMillis() + 5000;
19333                    synchronized (conn) {
19334                        long now;
19335                        while (conn.mContainerService == null &&
19336                                (now = SystemClock.uptimeMillis()) < timeout) {
19337                            try {
19338                                conn.wait(timeout - now);
19339                            } catch (InterruptedException e) {
19340                            }
19341                        }
19342                    }
19343                    if (conn.mContainerService == null) {
19344                        return;
19345                    }
19346
19347                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19348                    clearDirectory(conn.mContainerService,
19349                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19350                    if (allData) {
19351                        clearDirectory(conn.mContainerService,
19352                                userEnv.buildExternalStorageAppDataDirs(packageName));
19353                        clearDirectory(conn.mContainerService,
19354                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19355                    }
19356                }
19357            } finally {
19358                mContext.unbindService(conn);
19359            }
19360        }
19361    }
19362
19363    @Override
19364    public void clearApplicationProfileData(String packageName) {
19365        enforceSystemOrRoot("Only the system can clear all profile data");
19366
19367        final PackageParser.Package pkg;
19368        synchronized (mPackages) {
19369            pkg = mPackages.get(packageName);
19370        }
19371
19372        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19373            synchronized (mInstallLock) {
19374                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19375            }
19376        }
19377    }
19378
19379    @Override
19380    public void clearApplicationUserData(final String packageName,
19381            final IPackageDataObserver observer, final int userId) {
19382        mContext.enforceCallingOrSelfPermission(
19383                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19384
19385        enforceCrossUserPermission(Binder.getCallingUid(), userId,
19386                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19387
19388        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19389            throw new SecurityException("Cannot clear data for a protected package: "
19390                    + packageName);
19391        }
19392        // Queue up an async operation since the package deletion may take a little while.
19393        mHandler.post(new Runnable() {
19394            public void run() {
19395                mHandler.removeCallbacks(this);
19396                final boolean succeeded;
19397                try (PackageFreezer freezer = freezePackage(packageName,
19398                        "clearApplicationUserData")) {
19399                    synchronized (mInstallLock) {
19400                        succeeded = clearApplicationUserDataLIF(packageName, userId);
19401                    }
19402                    clearExternalStorageDataSync(packageName, userId, true);
19403                    synchronized (mPackages) {
19404                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19405                                packageName, userId);
19406                    }
19407                }
19408                if (succeeded) {
19409                    // invoke DeviceStorageMonitor's update method to clear any notifications
19410                    DeviceStorageMonitorInternal dsm = LocalServices
19411                            .getService(DeviceStorageMonitorInternal.class);
19412                    if (dsm != null) {
19413                        dsm.checkMemory();
19414                    }
19415                }
19416                if(observer != null) {
19417                    try {
19418                        observer.onRemoveCompleted(packageName, succeeded);
19419                    } catch (RemoteException e) {
19420                        Log.i(TAG, "Observer no longer exists.");
19421                    }
19422                } //end if observer
19423            } //end run
19424        });
19425    }
19426
19427    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19428        if (packageName == null) {
19429            Slog.w(TAG, "Attempt to delete null packageName.");
19430            return false;
19431        }
19432
19433        // Try finding details about the requested package
19434        PackageParser.Package pkg;
19435        synchronized (mPackages) {
19436            pkg = mPackages.get(packageName);
19437            if (pkg == null) {
19438                final PackageSetting ps = mSettings.mPackages.get(packageName);
19439                if (ps != null) {
19440                    pkg = ps.pkg;
19441                }
19442            }
19443
19444            if (pkg == null) {
19445                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19446                return false;
19447            }
19448
19449            PackageSetting ps = (PackageSetting) pkg.mExtras;
19450            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19451        }
19452
19453        clearAppDataLIF(pkg, userId,
19454                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19455
19456        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19457        removeKeystoreDataIfNeeded(userId, appId);
19458
19459        UserManagerInternal umInternal = getUserManagerInternal();
19460        final int flags;
19461        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19462            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19463        } else if (umInternal.isUserRunning(userId)) {
19464            flags = StorageManager.FLAG_STORAGE_DE;
19465        } else {
19466            flags = 0;
19467        }
19468        prepareAppDataContentsLIF(pkg, userId, flags);
19469
19470        return true;
19471    }
19472
19473    /**
19474     * Reverts user permission state changes (permissions and flags) in
19475     * all packages for a given user.
19476     *
19477     * @param userId The device user for which to do a reset.
19478     */
19479    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19480        final int packageCount = mPackages.size();
19481        for (int i = 0; i < packageCount; i++) {
19482            PackageParser.Package pkg = mPackages.valueAt(i);
19483            PackageSetting ps = (PackageSetting) pkg.mExtras;
19484            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19485        }
19486    }
19487
19488    private void resetNetworkPolicies(int userId) {
19489        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19490    }
19491
19492    /**
19493     * Reverts user permission state changes (permissions and flags).
19494     *
19495     * @param ps The package for which to reset.
19496     * @param userId The device user for which to do a reset.
19497     */
19498    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19499            final PackageSetting ps, final int userId) {
19500        if (ps.pkg == null) {
19501            return;
19502        }
19503
19504        // These are flags that can change base on user actions.
19505        final int userSettableMask = FLAG_PERMISSION_USER_SET
19506                | FLAG_PERMISSION_USER_FIXED
19507                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19508                | FLAG_PERMISSION_REVIEW_REQUIRED;
19509
19510        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19511                | FLAG_PERMISSION_POLICY_FIXED;
19512
19513        boolean writeInstallPermissions = false;
19514        boolean writeRuntimePermissions = false;
19515
19516        final int permissionCount = ps.pkg.requestedPermissions.size();
19517        for (int i = 0; i < permissionCount; i++) {
19518            String permission = ps.pkg.requestedPermissions.get(i);
19519
19520            BasePermission bp = mSettings.mPermissions.get(permission);
19521            if (bp == null) {
19522                continue;
19523            }
19524
19525            // If shared user we just reset the state to which only this app contributed.
19526            if (ps.sharedUser != null) {
19527                boolean used = false;
19528                final int packageCount = ps.sharedUser.packages.size();
19529                for (int j = 0; j < packageCount; j++) {
19530                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19531                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19532                            && pkg.pkg.requestedPermissions.contains(permission)) {
19533                        used = true;
19534                        break;
19535                    }
19536                }
19537                if (used) {
19538                    continue;
19539                }
19540            }
19541
19542            PermissionsState permissionsState = ps.getPermissionsState();
19543
19544            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
19545
19546            // Always clear the user settable flags.
19547            final boolean hasInstallState = permissionsState.getInstallPermissionState(
19548                    bp.name) != null;
19549            // If permission review is enabled and this is a legacy app, mark the
19550            // permission as requiring a review as this is the initial state.
19551            int flags = 0;
19552            if (mPermissionReviewRequired
19553                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19554                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19555            }
19556            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19557                if (hasInstallState) {
19558                    writeInstallPermissions = true;
19559                } else {
19560                    writeRuntimePermissions = true;
19561                }
19562            }
19563
19564            // Below is only runtime permission handling.
19565            if (!bp.isRuntime()) {
19566                continue;
19567            }
19568
19569            // Never clobber system or policy.
19570            if ((oldFlags & policyOrSystemFlags) != 0) {
19571                continue;
19572            }
19573
19574            // If this permission was granted by default, make sure it is.
19575            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19576                if (permissionsState.grantRuntimePermission(bp, userId)
19577                        != PERMISSION_OPERATION_FAILURE) {
19578                    writeRuntimePermissions = true;
19579                }
19580            // If permission review is enabled the permissions for a legacy apps
19581            // are represented as constantly granted runtime ones, so don't revoke.
19582            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19583                // Otherwise, reset the permission.
19584                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19585                switch (revokeResult) {
19586                    case PERMISSION_OPERATION_SUCCESS:
19587                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19588                        writeRuntimePermissions = true;
19589                        final int appId = ps.appId;
19590                        mHandler.post(new Runnable() {
19591                            @Override
19592                            public void run() {
19593                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19594                            }
19595                        });
19596                    } break;
19597                }
19598            }
19599        }
19600
19601        // Synchronously write as we are taking permissions away.
19602        if (writeRuntimePermissions) {
19603            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19604        }
19605
19606        // Synchronously write as we are taking permissions away.
19607        if (writeInstallPermissions) {
19608            mSettings.writeLPr();
19609        }
19610    }
19611
19612    /**
19613     * Remove entries from the keystore daemon. Will only remove it if the
19614     * {@code appId} is valid.
19615     */
19616    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19617        if (appId < 0) {
19618            return;
19619        }
19620
19621        final KeyStore keyStore = KeyStore.getInstance();
19622        if (keyStore != null) {
19623            if (userId == UserHandle.USER_ALL) {
19624                for (final int individual : sUserManager.getUserIds()) {
19625                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19626                }
19627            } else {
19628                keyStore.clearUid(UserHandle.getUid(userId, appId));
19629            }
19630        } else {
19631            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19632        }
19633    }
19634
19635    @Override
19636    public void deleteApplicationCacheFiles(final String packageName,
19637            final IPackageDataObserver observer) {
19638        final int userId = UserHandle.getCallingUserId();
19639        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19640    }
19641
19642    @Override
19643    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19644            final IPackageDataObserver observer) {
19645        mContext.enforceCallingOrSelfPermission(
19646                android.Manifest.permission.DELETE_CACHE_FILES, null);
19647        enforceCrossUserPermission(Binder.getCallingUid(), userId,
19648                /* requireFullPermission= */ true, /* checkShell= */ false,
19649                "delete application cache files");
19650
19651        final PackageParser.Package pkg;
19652        synchronized (mPackages) {
19653            pkg = mPackages.get(packageName);
19654        }
19655
19656        // Queue up an async operation since the package deletion may take a little while.
19657        mHandler.post(new Runnable() {
19658            public void run() {
19659                synchronized (mInstallLock) {
19660                    final int flags = StorageManager.FLAG_STORAGE_DE
19661                            | StorageManager.FLAG_STORAGE_CE;
19662                    // We're only clearing cache files, so we don't care if the
19663                    // app is unfrozen and still able to run
19664                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19665                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19666                }
19667                clearExternalStorageDataSync(packageName, userId, false);
19668                if (observer != null) {
19669                    try {
19670                        observer.onRemoveCompleted(packageName, true);
19671                    } catch (RemoteException e) {
19672                        Log.i(TAG, "Observer no longer exists.");
19673                    }
19674                }
19675            }
19676        });
19677    }
19678
19679    @Override
19680    public void getPackageSizeInfo(final String packageName, int userHandle,
19681            final IPackageStatsObserver observer) {
19682        throw new UnsupportedOperationException(
19683                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19684    }
19685
19686    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19687        final PackageSetting ps;
19688        synchronized (mPackages) {
19689            ps = mSettings.mPackages.get(packageName);
19690            if (ps == null) {
19691                Slog.w(TAG, "Failed to find settings for " + packageName);
19692                return false;
19693            }
19694        }
19695
19696        final String[] packageNames = { packageName };
19697        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19698        final String[] codePaths = { ps.codePathString };
19699
19700        try {
19701            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19702                    ps.appId, ceDataInodes, codePaths, stats);
19703
19704            // For now, ignore code size of packages on system partition
19705            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19706                stats.codeSize = 0;
19707            }
19708
19709            // External clients expect these to be tracked separately
19710            stats.dataSize -= stats.cacheSize;
19711
19712        } catch (InstallerException e) {
19713            Slog.w(TAG, String.valueOf(e));
19714            return false;
19715        }
19716
19717        return true;
19718    }
19719
19720    private int getUidTargetSdkVersionLockedLPr(int uid) {
19721        Object obj = mSettings.getUserIdLPr(uid);
19722        if (obj instanceof SharedUserSetting) {
19723            final SharedUserSetting sus = (SharedUserSetting) obj;
19724            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19725            final Iterator<PackageSetting> it = sus.packages.iterator();
19726            while (it.hasNext()) {
19727                final PackageSetting ps = it.next();
19728                if (ps.pkg != null) {
19729                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19730                    if (v < vers) vers = v;
19731                }
19732            }
19733            return vers;
19734        } else if (obj instanceof PackageSetting) {
19735            final PackageSetting ps = (PackageSetting) obj;
19736            if (ps.pkg != null) {
19737                return ps.pkg.applicationInfo.targetSdkVersion;
19738            }
19739        }
19740        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19741    }
19742
19743    @Override
19744    public void addPreferredActivity(IntentFilter filter, int match,
19745            ComponentName[] set, ComponentName activity, int userId) {
19746        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19747                "Adding preferred");
19748    }
19749
19750    private void addPreferredActivityInternal(IntentFilter filter, int match,
19751            ComponentName[] set, ComponentName activity, boolean always, int userId,
19752            String opname) {
19753        // writer
19754        int callingUid = Binder.getCallingUid();
19755        enforceCrossUserPermission(callingUid, userId,
19756                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19757        if (filter.countActions() == 0) {
19758            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19759            return;
19760        }
19761        synchronized (mPackages) {
19762            if (mContext.checkCallingOrSelfPermission(
19763                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19764                    != PackageManager.PERMISSION_GRANTED) {
19765                if (getUidTargetSdkVersionLockedLPr(callingUid)
19766                        < Build.VERSION_CODES.FROYO) {
19767                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19768                            + callingUid);
19769                    return;
19770                }
19771                mContext.enforceCallingOrSelfPermission(
19772                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19773            }
19774
19775            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19776            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19777                    + userId + ":");
19778            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19779            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19780            scheduleWritePackageRestrictionsLocked(userId);
19781            postPreferredActivityChangedBroadcast(userId);
19782        }
19783    }
19784
19785    private void postPreferredActivityChangedBroadcast(int userId) {
19786        mHandler.post(() -> {
19787            final IActivityManager am = ActivityManager.getService();
19788            if (am == null) {
19789                return;
19790            }
19791
19792            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19793            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19794            try {
19795                am.broadcastIntent(null, intent, null, null,
19796                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19797                        null, false, false, userId);
19798            } catch (RemoteException e) {
19799            }
19800        });
19801    }
19802
19803    @Override
19804    public void replacePreferredActivity(IntentFilter filter, int match,
19805            ComponentName[] set, ComponentName activity, int userId) {
19806        if (filter.countActions() != 1) {
19807            throw new IllegalArgumentException(
19808                    "replacePreferredActivity expects filter to have only 1 action.");
19809        }
19810        if (filter.countDataAuthorities() != 0
19811                || filter.countDataPaths() != 0
19812                || filter.countDataSchemes() > 1
19813                || filter.countDataTypes() != 0) {
19814            throw new IllegalArgumentException(
19815                    "replacePreferredActivity expects filter to have no data authorities, " +
19816                    "paths, or types; and at most one scheme.");
19817        }
19818
19819        final int callingUid = Binder.getCallingUid();
19820        enforceCrossUserPermission(callingUid, userId,
19821                true /* requireFullPermission */, false /* checkShell */,
19822                "replace preferred activity");
19823        synchronized (mPackages) {
19824            if (mContext.checkCallingOrSelfPermission(
19825                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19826                    != PackageManager.PERMISSION_GRANTED) {
19827                if (getUidTargetSdkVersionLockedLPr(callingUid)
19828                        < Build.VERSION_CODES.FROYO) {
19829                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19830                            + Binder.getCallingUid());
19831                    return;
19832                }
19833                mContext.enforceCallingOrSelfPermission(
19834                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19835            }
19836
19837            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19838            if (pir != null) {
19839                // Get all of the existing entries that exactly match this filter.
19840                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19841                if (existing != null && existing.size() == 1) {
19842                    PreferredActivity cur = existing.get(0);
19843                    if (DEBUG_PREFERRED) {
19844                        Slog.i(TAG, "Checking replace of preferred:");
19845                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19846                        if (!cur.mPref.mAlways) {
19847                            Slog.i(TAG, "  -- CUR; not mAlways!");
19848                        } else {
19849                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19850                            Slog.i(TAG, "  -- CUR: mSet="
19851                                    + Arrays.toString(cur.mPref.mSetComponents));
19852                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19853                            Slog.i(TAG, "  -- NEW: mMatch="
19854                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19855                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19856                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19857                        }
19858                    }
19859                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19860                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19861                            && cur.mPref.sameSet(set)) {
19862                        // Setting the preferred activity to what it happens to be already
19863                        if (DEBUG_PREFERRED) {
19864                            Slog.i(TAG, "Replacing with same preferred activity "
19865                                    + cur.mPref.mShortComponent + " for user "
19866                                    + userId + ":");
19867                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19868                        }
19869                        return;
19870                    }
19871                }
19872
19873                if (existing != null) {
19874                    if (DEBUG_PREFERRED) {
19875                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19876                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19877                    }
19878                    for (int i = 0; i < existing.size(); i++) {
19879                        PreferredActivity pa = existing.get(i);
19880                        if (DEBUG_PREFERRED) {
19881                            Slog.i(TAG, "Removing existing preferred activity "
19882                                    + pa.mPref.mComponent + ":");
19883                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19884                        }
19885                        pir.removeFilter(pa);
19886                    }
19887                }
19888            }
19889            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19890                    "Replacing preferred");
19891        }
19892    }
19893
19894    @Override
19895    public void clearPackagePreferredActivities(String packageName) {
19896        final int callingUid = Binder.getCallingUid();
19897        if (getInstantAppPackageName(callingUid) != null) {
19898            return;
19899        }
19900        // writer
19901        synchronized (mPackages) {
19902            PackageParser.Package pkg = mPackages.get(packageName);
19903            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19904                if (mContext.checkCallingOrSelfPermission(
19905                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19906                        != PackageManager.PERMISSION_GRANTED) {
19907                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19908                            < Build.VERSION_CODES.FROYO) {
19909                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19910                                + callingUid);
19911                        return;
19912                    }
19913                    mContext.enforceCallingOrSelfPermission(
19914                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19915                }
19916            }
19917
19918            int user = UserHandle.getCallingUserId();
19919            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19920                scheduleWritePackageRestrictionsLocked(user);
19921            }
19922        }
19923    }
19924
19925    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19926    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19927        ArrayList<PreferredActivity> removed = null;
19928        boolean changed = false;
19929        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19930            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19931            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19932            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19933                continue;
19934            }
19935            Iterator<PreferredActivity> it = pir.filterIterator();
19936            while (it.hasNext()) {
19937                PreferredActivity pa = it.next();
19938                // Mark entry for removal only if it matches the package name
19939                // and the entry is of type "always".
19940                if (packageName == null ||
19941                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19942                                && pa.mPref.mAlways)) {
19943                    if (removed == null) {
19944                        removed = new ArrayList<PreferredActivity>();
19945                    }
19946                    removed.add(pa);
19947                }
19948            }
19949            if (removed != null) {
19950                for (int j=0; j<removed.size(); j++) {
19951                    PreferredActivity pa = removed.get(j);
19952                    pir.removeFilter(pa);
19953                }
19954                changed = true;
19955            }
19956        }
19957        if (changed) {
19958            postPreferredActivityChangedBroadcast(userId);
19959        }
19960        return changed;
19961    }
19962
19963    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19964    private void clearIntentFilterVerificationsLPw(int userId) {
19965        final int packageCount = mPackages.size();
19966        for (int i = 0; i < packageCount; i++) {
19967            PackageParser.Package pkg = mPackages.valueAt(i);
19968            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19969        }
19970    }
19971
19972    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19973    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19974        if (userId == UserHandle.USER_ALL) {
19975            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19976                    sUserManager.getUserIds())) {
19977                for (int oneUserId : sUserManager.getUserIds()) {
19978                    scheduleWritePackageRestrictionsLocked(oneUserId);
19979                }
19980            }
19981        } else {
19982            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19983                scheduleWritePackageRestrictionsLocked(userId);
19984            }
19985        }
19986    }
19987
19988    /** Clears state for all users, and touches intent filter verification policy */
19989    void clearDefaultBrowserIfNeeded(String packageName) {
19990        for (int oneUserId : sUserManager.getUserIds()) {
19991            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19992        }
19993    }
19994
19995    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19996        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19997        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19998            if (packageName.equals(defaultBrowserPackageName)) {
19999                setDefaultBrowserPackageName(null, userId);
20000            }
20001        }
20002    }
20003
20004    @Override
20005    public void resetApplicationPreferences(int userId) {
20006        mContext.enforceCallingOrSelfPermission(
20007                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20008        final long identity = Binder.clearCallingIdentity();
20009        // writer
20010        try {
20011            synchronized (mPackages) {
20012                clearPackagePreferredActivitiesLPw(null, userId);
20013                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20014                // TODO: We have to reset the default SMS and Phone. This requires
20015                // significant refactoring to keep all default apps in the package
20016                // manager (cleaner but more work) or have the services provide
20017                // callbacks to the package manager to request a default app reset.
20018                applyFactoryDefaultBrowserLPw(userId);
20019                clearIntentFilterVerificationsLPw(userId);
20020                primeDomainVerificationsLPw(userId);
20021                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20022                scheduleWritePackageRestrictionsLocked(userId);
20023            }
20024            resetNetworkPolicies(userId);
20025        } finally {
20026            Binder.restoreCallingIdentity(identity);
20027        }
20028    }
20029
20030    @Override
20031    public int getPreferredActivities(List<IntentFilter> outFilters,
20032            List<ComponentName> outActivities, String packageName) {
20033        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20034            return 0;
20035        }
20036        int num = 0;
20037        final int userId = UserHandle.getCallingUserId();
20038        // reader
20039        synchronized (mPackages) {
20040            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20041            if (pir != null) {
20042                final Iterator<PreferredActivity> it = pir.filterIterator();
20043                while (it.hasNext()) {
20044                    final PreferredActivity pa = it.next();
20045                    if (packageName == null
20046                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20047                                    && pa.mPref.mAlways)) {
20048                        if (outFilters != null) {
20049                            outFilters.add(new IntentFilter(pa));
20050                        }
20051                        if (outActivities != null) {
20052                            outActivities.add(pa.mPref.mComponent);
20053                        }
20054                    }
20055                }
20056            }
20057        }
20058
20059        return num;
20060    }
20061
20062    @Override
20063    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20064            int userId) {
20065        int callingUid = Binder.getCallingUid();
20066        if (callingUid != Process.SYSTEM_UID) {
20067            throw new SecurityException(
20068                    "addPersistentPreferredActivity can only be run by the system");
20069        }
20070        if (filter.countActions() == 0) {
20071            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20072            return;
20073        }
20074        synchronized (mPackages) {
20075            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20076                    ":");
20077            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20078            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20079                    new PersistentPreferredActivity(filter, activity));
20080            scheduleWritePackageRestrictionsLocked(userId);
20081            postPreferredActivityChangedBroadcast(userId);
20082        }
20083    }
20084
20085    @Override
20086    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20087        int callingUid = Binder.getCallingUid();
20088        if (callingUid != Process.SYSTEM_UID) {
20089            throw new SecurityException(
20090                    "clearPackagePersistentPreferredActivities can only be run by the system");
20091        }
20092        ArrayList<PersistentPreferredActivity> removed = null;
20093        boolean changed = false;
20094        synchronized (mPackages) {
20095            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20096                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20097                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20098                        .valueAt(i);
20099                if (userId != thisUserId) {
20100                    continue;
20101                }
20102                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20103                while (it.hasNext()) {
20104                    PersistentPreferredActivity ppa = it.next();
20105                    // Mark entry for removal only if it matches the package name.
20106                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20107                        if (removed == null) {
20108                            removed = new ArrayList<PersistentPreferredActivity>();
20109                        }
20110                        removed.add(ppa);
20111                    }
20112                }
20113                if (removed != null) {
20114                    for (int j=0; j<removed.size(); j++) {
20115                        PersistentPreferredActivity ppa = removed.get(j);
20116                        ppir.removeFilter(ppa);
20117                    }
20118                    changed = true;
20119                }
20120            }
20121
20122            if (changed) {
20123                scheduleWritePackageRestrictionsLocked(userId);
20124                postPreferredActivityChangedBroadcast(userId);
20125            }
20126        }
20127    }
20128
20129    /**
20130     * Common machinery for picking apart a restored XML blob and passing
20131     * it to a caller-supplied functor to be applied to the running system.
20132     */
20133    private void restoreFromXml(XmlPullParser parser, int userId,
20134            String expectedStartTag, BlobXmlRestorer functor)
20135            throws IOException, XmlPullParserException {
20136        int type;
20137        while ((type = parser.next()) != XmlPullParser.START_TAG
20138                && type != XmlPullParser.END_DOCUMENT) {
20139        }
20140        if (type != XmlPullParser.START_TAG) {
20141            // oops didn't find a start tag?!
20142            if (DEBUG_BACKUP) {
20143                Slog.e(TAG, "Didn't find start tag during restore");
20144            }
20145            return;
20146        }
20147Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20148        // this is supposed to be TAG_PREFERRED_BACKUP
20149        if (!expectedStartTag.equals(parser.getName())) {
20150            if (DEBUG_BACKUP) {
20151                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20152            }
20153            return;
20154        }
20155
20156        // skip interfering stuff, then we're aligned with the backing implementation
20157        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20158Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20159        functor.apply(parser, userId);
20160    }
20161
20162    private interface BlobXmlRestorer {
20163        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20164    }
20165
20166    /**
20167     * Non-Binder method, support for the backup/restore mechanism: write the
20168     * full set of preferred activities in its canonical XML format.  Returns the
20169     * XML output as a byte array, or null if there is none.
20170     */
20171    @Override
20172    public byte[] getPreferredActivityBackup(int userId) {
20173        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20174            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20175        }
20176
20177        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20178        try {
20179            final XmlSerializer serializer = new FastXmlSerializer();
20180            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20181            serializer.startDocument(null, true);
20182            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20183
20184            synchronized (mPackages) {
20185                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20186            }
20187
20188            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20189            serializer.endDocument();
20190            serializer.flush();
20191        } catch (Exception e) {
20192            if (DEBUG_BACKUP) {
20193                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20194            }
20195            return null;
20196        }
20197
20198        return dataStream.toByteArray();
20199    }
20200
20201    @Override
20202    public void restorePreferredActivities(byte[] backup, int userId) {
20203        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20204            throw new SecurityException("Only the system may call restorePreferredActivities()");
20205        }
20206
20207        try {
20208            final XmlPullParser parser = Xml.newPullParser();
20209            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20210            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20211                    new BlobXmlRestorer() {
20212                        @Override
20213                        public void apply(XmlPullParser parser, int userId)
20214                                throws XmlPullParserException, IOException {
20215                            synchronized (mPackages) {
20216                                mSettings.readPreferredActivitiesLPw(parser, userId);
20217                            }
20218                        }
20219                    } );
20220        } catch (Exception e) {
20221            if (DEBUG_BACKUP) {
20222                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20223            }
20224        }
20225    }
20226
20227    /**
20228     * Non-Binder method, support for the backup/restore mechanism: write the
20229     * default browser (etc) settings in its canonical XML format.  Returns the default
20230     * browser XML representation as a byte array, or null if there is none.
20231     */
20232    @Override
20233    public byte[] getDefaultAppsBackup(int userId) {
20234        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20235            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20236        }
20237
20238        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20239        try {
20240            final XmlSerializer serializer = new FastXmlSerializer();
20241            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20242            serializer.startDocument(null, true);
20243            serializer.startTag(null, TAG_DEFAULT_APPS);
20244
20245            synchronized (mPackages) {
20246                mSettings.writeDefaultAppsLPr(serializer, userId);
20247            }
20248
20249            serializer.endTag(null, TAG_DEFAULT_APPS);
20250            serializer.endDocument();
20251            serializer.flush();
20252        } catch (Exception e) {
20253            if (DEBUG_BACKUP) {
20254                Slog.e(TAG, "Unable to write default apps for backup", e);
20255            }
20256            return null;
20257        }
20258
20259        return dataStream.toByteArray();
20260    }
20261
20262    @Override
20263    public void restoreDefaultApps(byte[] backup, int userId) {
20264        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20265            throw new SecurityException("Only the system may call restoreDefaultApps()");
20266        }
20267
20268        try {
20269            final XmlPullParser parser = Xml.newPullParser();
20270            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20271            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20272                    new BlobXmlRestorer() {
20273                        @Override
20274                        public void apply(XmlPullParser parser, int userId)
20275                                throws XmlPullParserException, IOException {
20276                            synchronized (mPackages) {
20277                                mSettings.readDefaultAppsLPw(parser, userId);
20278                            }
20279                        }
20280                    } );
20281        } catch (Exception e) {
20282            if (DEBUG_BACKUP) {
20283                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20284            }
20285        }
20286    }
20287
20288    @Override
20289    public byte[] getIntentFilterVerificationBackup(int userId) {
20290        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20291            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20292        }
20293
20294        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20295        try {
20296            final XmlSerializer serializer = new FastXmlSerializer();
20297            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20298            serializer.startDocument(null, true);
20299            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20300
20301            synchronized (mPackages) {
20302                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20303            }
20304
20305            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20306            serializer.endDocument();
20307            serializer.flush();
20308        } catch (Exception e) {
20309            if (DEBUG_BACKUP) {
20310                Slog.e(TAG, "Unable to write default apps for backup", e);
20311            }
20312            return null;
20313        }
20314
20315        return dataStream.toByteArray();
20316    }
20317
20318    @Override
20319    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20320        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20321            throw new SecurityException("Only the system may call restorePreferredActivities()");
20322        }
20323
20324        try {
20325            final XmlPullParser parser = Xml.newPullParser();
20326            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20327            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20328                    new BlobXmlRestorer() {
20329                        @Override
20330                        public void apply(XmlPullParser parser, int userId)
20331                                throws XmlPullParserException, IOException {
20332                            synchronized (mPackages) {
20333                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20334                                mSettings.writeLPr();
20335                            }
20336                        }
20337                    } );
20338        } catch (Exception e) {
20339            if (DEBUG_BACKUP) {
20340                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20341            }
20342        }
20343    }
20344
20345    @Override
20346    public byte[] getPermissionGrantBackup(int userId) {
20347        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20348            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20349        }
20350
20351        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20352        try {
20353            final XmlSerializer serializer = new FastXmlSerializer();
20354            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20355            serializer.startDocument(null, true);
20356            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20357
20358            synchronized (mPackages) {
20359                serializeRuntimePermissionGrantsLPr(serializer, userId);
20360            }
20361
20362            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20363            serializer.endDocument();
20364            serializer.flush();
20365        } catch (Exception e) {
20366            if (DEBUG_BACKUP) {
20367                Slog.e(TAG, "Unable to write default apps for backup", e);
20368            }
20369            return null;
20370        }
20371
20372        return dataStream.toByteArray();
20373    }
20374
20375    @Override
20376    public void restorePermissionGrants(byte[] backup, int userId) {
20377        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20378            throw new SecurityException("Only the system may call restorePermissionGrants()");
20379        }
20380
20381        try {
20382            final XmlPullParser parser = Xml.newPullParser();
20383            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20384            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20385                    new BlobXmlRestorer() {
20386                        @Override
20387                        public void apply(XmlPullParser parser, int userId)
20388                                throws XmlPullParserException, IOException {
20389                            synchronized (mPackages) {
20390                                processRestoredPermissionGrantsLPr(parser, userId);
20391                            }
20392                        }
20393                    } );
20394        } catch (Exception e) {
20395            if (DEBUG_BACKUP) {
20396                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20397            }
20398        }
20399    }
20400
20401    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20402            throws IOException {
20403        serializer.startTag(null, TAG_ALL_GRANTS);
20404
20405        final int N = mSettings.mPackages.size();
20406        for (int i = 0; i < N; i++) {
20407            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20408            boolean pkgGrantsKnown = false;
20409
20410            PermissionsState packagePerms = ps.getPermissionsState();
20411
20412            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20413                final int grantFlags = state.getFlags();
20414                // only look at grants that are not system/policy fixed
20415                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20416                    final boolean isGranted = state.isGranted();
20417                    // And only back up the user-twiddled state bits
20418                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20419                        final String packageName = mSettings.mPackages.keyAt(i);
20420                        if (!pkgGrantsKnown) {
20421                            serializer.startTag(null, TAG_GRANT);
20422                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20423                            pkgGrantsKnown = true;
20424                        }
20425
20426                        final boolean userSet =
20427                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20428                        final boolean userFixed =
20429                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20430                        final boolean revoke =
20431                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20432
20433                        serializer.startTag(null, TAG_PERMISSION);
20434                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20435                        if (isGranted) {
20436                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20437                        }
20438                        if (userSet) {
20439                            serializer.attribute(null, ATTR_USER_SET, "true");
20440                        }
20441                        if (userFixed) {
20442                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20443                        }
20444                        if (revoke) {
20445                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20446                        }
20447                        serializer.endTag(null, TAG_PERMISSION);
20448                    }
20449                }
20450            }
20451
20452            if (pkgGrantsKnown) {
20453                serializer.endTag(null, TAG_GRANT);
20454            }
20455        }
20456
20457        serializer.endTag(null, TAG_ALL_GRANTS);
20458    }
20459
20460    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20461            throws XmlPullParserException, IOException {
20462        String pkgName = null;
20463        int outerDepth = parser.getDepth();
20464        int type;
20465        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20466                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20467            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20468                continue;
20469            }
20470
20471            final String tagName = parser.getName();
20472            if (tagName.equals(TAG_GRANT)) {
20473                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20474                if (DEBUG_BACKUP) {
20475                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20476                }
20477            } else if (tagName.equals(TAG_PERMISSION)) {
20478
20479                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20480                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20481
20482                int newFlagSet = 0;
20483                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20484                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20485                }
20486                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20487                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20488                }
20489                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20490                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20491                }
20492                if (DEBUG_BACKUP) {
20493                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
20494                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20495                }
20496                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20497                if (ps != null) {
20498                    // Already installed so we apply the grant immediately
20499                    if (DEBUG_BACKUP) {
20500                        Slog.v(TAG, "        + already installed; applying");
20501                    }
20502                    PermissionsState perms = ps.getPermissionsState();
20503                    BasePermission bp = mSettings.mPermissions.get(permName);
20504                    if (bp != null) {
20505                        if (isGranted) {
20506                            perms.grantRuntimePermission(bp, userId);
20507                        }
20508                        if (newFlagSet != 0) {
20509                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20510                        }
20511                    }
20512                } else {
20513                    // Need to wait for post-restore install to apply the grant
20514                    if (DEBUG_BACKUP) {
20515                        Slog.v(TAG, "        - not yet installed; saving for later");
20516                    }
20517                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20518                            isGranted, newFlagSet, userId);
20519                }
20520            } else {
20521                PackageManagerService.reportSettingsProblem(Log.WARN,
20522                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20523                XmlUtils.skipCurrentTag(parser);
20524            }
20525        }
20526
20527        scheduleWriteSettingsLocked();
20528        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20529    }
20530
20531    @Override
20532    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20533            int sourceUserId, int targetUserId, int flags) {
20534        mContext.enforceCallingOrSelfPermission(
20535                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20536        int callingUid = Binder.getCallingUid();
20537        enforceOwnerRights(ownerPackage, callingUid);
20538        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20539        if (intentFilter.countActions() == 0) {
20540            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20541            return;
20542        }
20543        synchronized (mPackages) {
20544            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20545                    ownerPackage, targetUserId, flags);
20546            CrossProfileIntentResolver resolver =
20547                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20548            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20549            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20550            if (existing != null) {
20551                int size = existing.size();
20552                for (int i = 0; i < size; i++) {
20553                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20554                        return;
20555                    }
20556                }
20557            }
20558            resolver.addFilter(newFilter);
20559            scheduleWritePackageRestrictionsLocked(sourceUserId);
20560        }
20561    }
20562
20563    @Override
20564    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20565        mContext.enforceCallingOrSelfPermission(
20566                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20567        int callingUid = Binder.getCallingUid();
20568        enforceOwnerRights(ownerPackage, callingUid);
20569        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20570        synchronized (mPackages) {
20571            CrossProfileIntentResolver resolver =
20572                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20573            ArraySet<CrossProfileIntentFilter> set =
20574                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20575            for (CrossProfileIntentFilter filter : set) {
20576                if (filter.getOwnerPackage().equals(ownerPackage)) {
20577                    resolver.removeFilter(filter);
20578                }
20579            }
20580            scheduleWritePackageRestrictionsLocked(sourceUserId);
20581        }
20582    }
20583
20584    // Enforcing that callingUid is owning pkg on userId
20585    private void enforceOwnerRights(String pkg, int callingUid) {
20586        // The system owns everything.
20587        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20588            return;
20589        }
20590        int callingUserId = UserHandle.getUserId(callingUid);
20591        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20592        if (pi == null) {
20593            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20594                    + callingUserId);
20595        }
20596        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20597            throw new SecurityException("Calling uid " + callingUid
20598                    + " does not own package " + pkg);
20599        }
20600    }
20601
20602    @Override
20603    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20604        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20605            return null;
20606        }
20607        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20608    }
20609
20610    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20611        UserManagerService ums = UserManagerService.getInstance();
20612        if (ums != null) {
20613            final UserInfo parent = ums.getProfileParent(userId);
20614            final int launcherUid = (parent != null) ? parent.id : userId;
20615            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20616            if (launcherComponent != null) {
20617                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20618                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20619                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20620                        .setPackage(launcherComponent.getPackageName());
20621                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20622            }
20623        }
20624    }
20625
20626    /**
20627     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20628     * then reports the most likely home activity or null if there are more than one.
20629     */
20630    private ComponentName getDefaultHomeActivity(int userId) {
20631        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20632        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20633        if (cn != null) {
20634            return cn;
20635        }
20636
20637        // Find the launcher with the highest priority and return that component if there are no
20638        // other home activity with the same priority.
20639        int lastPriority = Integer.MIN_VALUE;
20640        ComponentName lastComponent = null;
20641        final int size = allHomeCandidates.size();
20642        for (int i = 0; i < size; i++) {
20643            final ResolveInfo ri = allHomeCandidates.get(i);
20644            if (ri.priority > lastPriority) {
20645                lastComponent = ri.activityInfo.getComponentName();
20646                lastPriority = ri.priority;
20647            } else if (ri.priority == lastPriority) {
20648                // Two components found with same priority.
20649                lastComponent = null;
20650            }
20651        }
20652        return lastComponent;
20653    }
20654
20655    private Intent getHomeIntent() {
20656        Intent intent = new Intent(Intent.ACTION_MAIN);
20657        intent.addCategory(Intent.CATEGORY_HOME);
20658        intent.addCategory(Intent.CATEGORY_DEFAULT);
20659        return intent;
20660    }
20661
20662    private IntentFilter getHomeFilter() {
20663        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20664        filter.addCategory(Intent.CATEGORY_HOME);
20665        filter.addCategory(Intent.CATEGORY_DEFAULT);
20666        return filter;
20667    }
20668
20669    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20670            int userId) {
20671        Intent intent  = getHomeIntent();
20672        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20673                PackageManager.GET_META_DATA, userId);
20674        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20675                true, false, false, userId);
20676
20677        allHomeCandidates.clear();
20678        if (list != null) {
20679            for (ResolveInfo ri : list) {
20680                allHomeCandidates.add(ri);
20681            }
20682        }
20683        return (preferred == null || preferred.activityInfo == null)
20684                ? null
20685                : new ComponentName(preferred.activityInfo.packageName,
20686                        preferred.activityInfo.name);
20687    }
20688
20689    @Override
20690    public void setHomeActivity(ComponentName comp, int userId) {
20691        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20692            return;
20693        }
20694        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20695        getHomeActivitiesAsUser(homeActivities, userId);
20696
20697        boolean found = false;
20698
20699        final int size = homeActivities.size();
20700        final ComponentName[] set = new ComponentName[size];
20701        for (int i = 0; i < size; i++) {
20702            final ResolveInfo candidate = homeActivities.get(i);
20703            final ActivityInfo info = candidate.activityInfo;
20704            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20705            set[i] = activityName;
20706            if (!found && activityName.equals(comp)) {
20707                found = true;
20708            }
20709        }
20710        if (!found) {
20711            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20712                    + userId);
20713        }
20714        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20715                set, comp, userId);
20716    }
20717
20718    private @Nullable String getSetupWizardPackageName() {
20719        final Intent intent = new Intent(Intent.ACTION_MAIN);
20720        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20721
20722        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20723                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20724                        | MATCH_DISABLED_COMPONENTS,
20725                UserHandle.myUserId());
20726        if (matches.size() == 1) {
20727            return matches.get(0).getComponentInfo().packageName;
20728        } else {
20729            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20730                    + ": matches=" + matches);
20731            return null;
20732        }
20733    }
20734
20735    private @Nullable String getStorageManagerPackageName() {
20736        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20737
20738        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20739                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20740                        | MATCH_DISABLED_COMPONENTS,
20741                UserHandle.myUserId());
20742        if (matches.size() == 1) {
20743            return matches.get(0).getComponentInfo().packageName;
20744        } else {
20745            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20746                    + matches.size() + ": matches=" + matches);
20747            return null;
20748        }
20749    }
20750
20751    @Override
20752    public void setApplicationEnabledSetting(String appPackageName,
20753            int newState, int flags, int userId, String callingPackage) {
20754        if (!sUserManager.exists(userId)) return;
20755        if (callingPackage == null) {
20756            callingPackage = Integer.toString(Binder.getCallingUid());
20757        }
20758        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20759    }
20760
20761    @Override
20762    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20763        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20764        synchronized (mPackages) {
20765            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20766            if (pkgSetting != null) {
20767                pkgSetting.setUpdateAvailable(updateAvailable);
20768            }
20769        }
20770    }
20771
20772    @Override
20773    public void setComponentEnabledSetting(ComponentName componentName,
20774            int newState, int flags, int userId) {
20775        if (!sUserManager.exists(userId)) return;
20776        setEnabledSetting(componentName.getPackageName(),
20777                componentName.getClassName(), newState, flags, userId, null);
20778    }
20779
20780    private void setEnabledSetting(final String packageName, String className, int newState,
20781            final int flags, int userId, String callingPackage) {
20782        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20783              || newState == COMPONENT_ENABLED_STATE_ENABLED
20784              || newState == COMPONENT_ENABLED_STATE_DISABLED
20785              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20786              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20787            throw new IllegalArgumentException("Invalid new component state: "
20788                    + newState);
20789        }
20790        PackageSetting pkgSetting;
20791        final int callingUid = Binder.getCallingUid();
20792        final int permission;
20793        if (callingUid == Process.SYSTEM_UID) {
20794            permission = PackageManager.PERMISSION_GRANTED;
20795        } else {
20796            permission = mContext.checkCallingOrSelfPermission(
20797                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20798        }
20799        enforceCrossUserPermission(callingUid, userId,
20800                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20801        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20802        boolean sendNow = false;
20803        boolean isApp = (className == null);
20804        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20805        String componentName = isApp ? packageName : className;
20806        int packageUid = -1;
20807        ArrayList<String> components;
20808
20809        // reader
20810        synchronized (mPackages) {
20811            pkgSetting = mSettings.mPackages.get(packageName);
20812            if (pkgSetting == null) {
20813                if (!isCallerInstantApp) {
20814                    if (className == null) {
20815                        throw new IllegalArgumentException("Unknown package: " + packageName);
20816                    }
20817                    throw new IllegalArgumentException(
20818                            "Unknown component: " + packageName + "/" + className);
20819                } else {
20820                    // throw SecurityException to prevent leaking package information
20821                    throw new SecurityException(
20822                            "Attempt to change component state; "
20823                            + "pid=" + Binder.getCallingPid()
20824                            + ", uid=" + callingUid
20825                            + (className == null
20826                                    ? ", package=" + packageName
20827                                    : ", component=" + packageName + "/" + className));
20828                }
20829            }
20830        }
20831
20832        // Limit who can change which apps
20833        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20834            // Don't allow apps that don't have permission to modify other apps
20835            if (!allowedByPermission) {
20836                throw new SecurityException(
20837                        "Attempt to change component state; "
20838                        + "pid=" + Binder.getCallingPid()
20839                        + ", uid=" + callingUid
20840                        + (className == null
20841                                ? ", package=" + packageName
20842                                : ", component=" + packageName + "/" + className));
20843            }
20844            // Don't allow changing protected packages.
20845            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20846                throw new SecurityException("Cannot disable a protected package: " + packageName);
20847            }
20848        }
20849
20850        synchronized (mPackages) {
20851            if (callingUid == Process.SHELL_UID
20852                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20853                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20854                // unless it is a test package.
20855                int oldState = pkgSetting.getEnabled(userId);
20856                if (className == null
20857                    &&
20858                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20859                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20860                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20861                    &&
20862                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20863                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
20864                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20865                    // ok
20866                } else {
20867                    throw new SecurityException(
20868                            "Shell cannot change component state for " + packageName + "/"
20869                            + className + " to " + newState);
20870                }
20871            }
20872            if (className == null) {
20873                // We're dealing with an application/package level state change
20874                if (pkgSetting.getEnabled(userId) == newState) {
20875                    // Nothing to do
20876                    return;
20877                }
20878                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20879                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20880                    // Don't care about who enables an app.
20881                    callingPackage = null;
20882                }
20883                pkgSetting.setEnabled(newState, userId, callingPackage);
20884                // pkgSetting.pkg.mSetEnabled = newState;
20885            } else {
20886                // We're dealing with a component level state change
20887                // First, verify that this is a valid class name.
20888                PackageParser.Package pkg = pkgSetting.pkg;
20889                if (pkg == null || !pkg.hasComponentClassName(className)) {
20890                    if (pkg != null &&
20891                            pkg.applicationInfo.targetSdkVersion >=
20892                                    Build.VERSION_CODES.JELLY_BEAN) {
20893                        throw new IllegalArgumentException("Component class " + className
20894                                + " does not exist in " + packageName);
20895                    } else {
20896                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20897                                + className + " does not exist in " + packageName);
20898                    }
20899                }
20900                switch (newState) {
20901                case COMPONENT_ENABLED_STATE_ENABLED:
20902                    if (!pkgSetting.enableComponentLPw(className, userId)) {
20903                        return;
20904                    }
20905                    break;
20906                case COMPONENT_ENABLED_STATE_DISABLED:
20907                    if (!pkgSetting.disableComponentLPw(className, userId)) {
20908                        return;
20909                    }
20910                    break;
20911                case COMPONENT_ENABLED_STATE_DEFAULT:
20912                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
20913                        return;
20914                    }
20915                    break;
20916                default:
20917                    Slog.e(TAG, "Invalid new component state: " + newState);
20918                    return;
20919                }
20920            }
20921            scheduleWritePackageRestrictionsLocked(userId);
20922            updateSequenceNumberLP(packageName, new int[] { userId });
20923            final long callingId = Binder.clearCallingIdentity();
20924            try {
20925                updateInstantAppInstallerLocked(packageName);
20926            } finally {
20927                Binder.restoreCallingIdentity(callingId);
20928            }
20929            components = mPendingBroadcasts.get(userId, packageName);
20930            final boolean newPackage = components == null;
20931            if (newPackage) {
20932                components = new ArrayList<String>();
20933            }
20934            if (!components.contains(componentName)) {
20935                components.add(componentName);
20936            }
20937            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20938                sendNow = true;
20939                // Purge entry from pending broadcast list if another one exists already
20940                // since we are sending one right away.
20941                mPendingBroadcasts.remove(userId, packageName);
20942            } else {
20943                if (newPackage) {
20944                    mPendingBroadcasts.put(userId, packageName, components);
20945                }
20946                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20947                    // Schedule a message
20948                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20949                }
20950            }
20951        }
20952
20953        long callingId = Binder.clearCallingIdentity();
20954        try {
20955            if (sendNow) {
20956                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20957                sendPackageChangedBroadcast(packageName,
20958                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20959            }
20960        } finally {
20961            Binder.restoreCallingIdentity(callingId);
20962        }
20963    }
20964
20965    @Override
20966    public void flushPackageRestrictionsAsUser(int userId) {
20967        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20968            return;
20969        }
20970        if (!sUserManager.exists(userId)) {
20971            return;
20972        }
20973        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20974                false /* checkShell */, "flushPackageRestrictions");
20975        synchronized (mPackages) {
20976            mSettings.writePackageRestrictionsLPr(userId);
20977            mDirtyUsers.remove(userId);
20978            if (mDirtyUsers.isEmpty()) {
20979                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20980            }
20981        }
20982    }
20983
20984    private void sendPackageChangedBroadcast(String packageName,
20985            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20986        if (DEBUG_INSTALL)
20987            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20988                    + componentNames);
20989        Bundle extras = new Bundle(4);
20990        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20991        String nameList[] = new String[componentNames.size()];
20992        componentNames.toArray(nameList);
20993        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20994        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20995        extras.putInt(Intent.EXTRA_UID, packageUid);
20996        // If this is not reporting a change of the overall package, then only send it
20997        // to registered receivers.  We don't want to launch a swath of apps for every
20998        // little component state change.
20999        final int flags = !componentNames.contains(packageName)
21000                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21001        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21002                new int[] {UserHandle.getUserId(packageUid)});
21003    }
21004
21005    @Override
21006    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21007        if (!sUserManager.exists(userId)) return;
21008        final int callingUid = Binder.getCallingUid();
21009        if (getInstantAppPackageName(callingUid) != null) {
21010            return;
21011        }
21012        final int permission = mContext.checkCallingOrSelfPermission(
21013                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21014        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21015        enforceCrossUserPermission(callingUid, userId,
21016                true /* requireFullPermission */, true /* checkShell */, "stop package");
21017        // writer
21018        synchronized (mPackages) {
21019            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21020                    allowedByPermission, callingUid, userId)) {
21021                scheduleWritePackageRestrictionsLocked(userId);
21022            }
21023        }
21024    }
21025
21026    @Override
21027    public String getInstallerPackageName(String packageName) {
21028        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21029            return null;
21030        }
21031        // reader
21032        synchronized (mPackages) {
21033            return mSettings.getInstallerPackageNameLPr(packageName);
21034        }
21035    }
21036
21037    public boolean isOrphaned(String packageName) {
21038        // reader
21039        synchronized (mPackages) {
21040            return mSettings.isOrphaned(packageName);
21041        }
21042    }
21043
21044    @Override
21045    public int getApplicationEnabledSetting(String packageName, int userId) {
21046        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21047        int callingUid = Binder.getCallingUid();
21048        enforceCrossUserPermission(callingUid, userId,
21049                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21050        // reader
21051        synchronized (mPackages) {
21052            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21053                return COMPONENT_ENABLED_STATE_DISABLED;
21054            }
21055            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21056        }
21057    }
21058
21059    @Override
21060    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
21061        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21062        int uid = Binder.getCallingUid();
21063        enforceCrossUserPermission(uid, userId,
21064                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
21065        // reader
21066        synchronized (mPackages) {
21067            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
21068        }
21069    }
21070
21071    @Override
21072    public void enterSafeMode() {
21073        enforceSystemOrRoot("Only the system can request entering safe mode");
21074
21075        if (!mSystemReady) {
21076            mSafeMode = true;
21077        }
21078    }
21079
21080    @Override
21081    public void systemReady() {
21082        enforceSystemOrRoot("Only the system can claim the system is ready");
21083
21084        mSystemReady = true;
21085        final ContentResolver resolver = mContext.getContentResolver();
21086        ContentObserver co = new ContentObserver(mHandler) {
21087            @Override
21088            public void onChange(boolean selfChange) {
21089                mEphemeralAppsDisabled =
21090                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21091                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21092            }
21093        };
21094        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21095                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21096                false, co, UserHandle.USER_SYSTEM);
21097        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21098                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21099        co.onChange(true);
21100
21101        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21102        // disabled after already being started.
21103        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21104                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21105
21106        // Read the compatibilty setting when the system is ready.
21107        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21108                mContext.getContentResolver(),
21109                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21110        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21111        if (DEBUG_SETTINGS) {
21112            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21113        }
21114
21115        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21116
21117        synchronized (mPackages) {
21118            // Verify that all of the preferred activity components actually
21119            // exist.  It is possible for applications to be updated and at
21120            // that point remove a previously declared activity component that
21121            // had been set as a preferred activity.  We try to clean this up
21122            // the next time we encounter that preferred activity, but it is
21123            // possible for the user flow to never be able to return to that
21124            // situation so here we do a sanity check to make sure we haven't
21125            // left any junk around.
21126            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21127            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21128                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21129                removed.clear();
21130                for (PreferredActivity pa : pir.filterSet()) {
21131                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21132                        removed.add(pa);
21133                    }
21134                }
21135                if (removed.size() > 0) {
21136                    for (int r=0; r<removed.size(); r++) {
21137                        PreferredActivity pa = removed.get(r);
21138                        Slog.w(TAG, "Removing dangling preferred activity: "
21139                                + pa.mPref.mComponent);
21140                        pir.removeFilter(pa);
21141                    }
21142                    mSettings.writePackageRestrictionsLPr(
21143                            mSettings.mPreferredActivities.keyAt(i));
21144                }
21145            }
21146
21147            for (int userId : UserManagerService.getInstance().getUserIds()) {
21148                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21149                    grantPermissionsUserIds = ArrayUtils.appendInt(
21150                            grantPermissionsUserIds, userId);
21151                }
21152            }
21153        }
21154        sUserManager.systemReady();
21155
21156        // If we upgraded grant all default permissions before kicking off.
21157        for (int userId : grantPermissionsUserIds) {
21158            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21159        }
21160
21161        // If we did not grant default permissions, we preload from this the
21162        // default permission exceptions lazily to ensure we don't hit the
21163        // disk on a new user creation.
21164        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21165            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21166        }
21167
21168        // Kick off any messages waiting for system ready
21169        if (mPostSystemReadyMessages != null) {
21170            for (Message msg : mPostSystemReadyMessages) {
21171                msg.sendToTarget();
21172            }
21173            mPostSystemReadyMessages = null;
21174        }
21175
21176        // Watch for external volumes that come and go over time
21177        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21178        storage.registerListener(mStorageListener);
21179
21180        mInstallerService.systemReady();
21181        mPackageDexOptimizer.systemReady();
21182
21183        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21184                StorageManagerInternal.class);
21185        StorageManagerInternal.addExternalStoragePolicy(
21186                new StorageManagerInternal.ExternalStorageMountPolicy() {
21187            @Override
21188            public int getMountMode(int uid, String packageName) {
21189                if (Process.isIsolated(uid)) {
21190                    return Zygote.MOUNT_EXTERNAL_NONE;
21191                }
21192                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21193                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21194                }
21195                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21196                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21197                }
21198                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21199                    return Zygote.MOUNT_EXTERNAL_READ;
21200                }
21201                return Zygote.MOUNT_EXTERNAL_WRITE;
21202            }
21203
21204            @Override
21205            public boolean hasExternalStorage(int uid, String packageName) {
21206                return true;
21207            }
21208        });
21209
21210        // Now that we're mostly running, clean up stale users and apps
21211        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21212        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21213
21214        if (mPrivappPermissionsViolations != null) {
21215            Slog.wtf(TAG,"Signature|privileged permissions not in "
21216                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21217            mPrivappPermissionsViolations = null;
21218        }
21219    }
21220
21221    public void waitForAppDataPrepared() {
21222        if (mPrepareAppDataFuture == null) {
21223            return;
21224        }
21225        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21226        mPrepareAppDataFuture = null;
21227    }
21228
21229    @Override
21230    public boolean isSafeMode() {
21231        // allow instant applications
21232        return mSafeMode;
21233    }
21234
21235    @Override
21236    public boolean hasSystemUidErrors() {
21237        // allow instant applications
21238        return mHasSystemUidErrors;
21239    }
21240
21241    static String arrayToString(int[] array) {
21242        StringBuffer buf = new StringBuffer(128);
21243        buf.append('[');
21244        if (array != null) {
21245            for (int i=0; i<array.length; i++) {
21246                if (i > 0) buf.append(", ");
21247                buf.append(array[i]);
21248            }
21249        }
21250        buf.append(']');
21251        return buf.toString();
21252    }
21253
21254    static class DumpState {
21255        public static final int DUMP_LIBS = 1 << 0;
21256        public static final int DUMP_FEATURES = 1 << 1;
21257        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
21258        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
21259        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
21260        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
21261        public static final int DUMP_PERMISSIONS = 1 << 6;
21262        public static final int DUMP_PACKAGES = 1 << 7;
21263        public static final int DUMP_SHARED_USERS = 1 << 8;
21264        public static final int DUMP_MESSAGES = 1 << 9;
21265        public static final int DUMP_PROVIDERS = 1 << 10;
21266        public static final int DUMP_VERIFIERS = 1 << 11;
21267        public static final int DUMP_PREFERRED = 1 << 12;
21268        public static final int DUMP_PREFERRED_XML = 1 << 13;
21269        public static final int DUMP_KEYSETS = 1 << 14;
21270        public static final int DUMP_VERSION = 1 << 15;
21271        public static final int DUMP_INSTALLS = 1 << 16;
21272        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
21273        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
21274        public static final int DUMP_FROZEN = 1 << 19;
21275        public static final int DUMP_DEXOPT = 1 << 20;
21276        public static final int DUMP_COMPILER_STATS = 1 << 21;
21277        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
21278        public static final int DUMP_CHANGES = 1 << 23;
21279
21280        public static final int OPTION_SHOW_FILTERS = 1 << 0;
21281
21282        private int mTypes;
21283
21284        private int mOptions;
21285
21286        private boolean mTitlePrinted;
21287
21288        private SharedUserSetting mSharedUser;
21289
21290        public boolean isDumping(int type) {
21291            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
21292                return true;
21293            }
21294
21295            return (mTypes & type) != 0;
21296        }
21297
21298        public void setDump(int type) {
21299            mTypes |= type;
21300        }
21301
21302        public boolean isOptionEnabled(int option) {
21303            return (mOptions & option) != 0;
21304        }
21305
21306        public void setOptionEnabled(int option) {
21307            mOptions |= option;
21308        }
21309
21310        public boolean onTitlePrinted() {
21311            final boolean printed = mTitlePrinted;
21312            mTitlePrinted = true;
21313            return printed;
21314        }
21315
21316        public boolean getTitlePrinted() {
21317            return mTitlePrinted;
21318        }
21319
21320        public void setTitlePrinted(boolean enabled) {
21321            mTitlePrinted = enabled;
21322        }
21323
21324        public SharedUserSetting getSharedUser() {
21325            return mSharedUser;
21326        }
21327
21328        public void setSharedUser(SharedUserSetting user) {
21329            mSharedUser = user;
21330        }
21331    }
21332
21333    @Override
21334    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21335            FileDescriptor err, String[] args, ShellCallback callback,
21336            ResultReceiver resultReceiver) {
21337        (new PackageManagerShellCommand(this)).exec(
21338                this, in, out, err, args, callback, resultReceiver);
21339    }
21340
21341    @Override
21342    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21343        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21344
21345        DumpState dumpState = new DumpState();
21346        boolean fullPreferred = false;
21347        boolean checkin = false;
21348
21349        String packageName = null;
21350        ArraySet<String> permissionNames = null;
21351
21352        int opti = 0;
21353        while (opti < args.length) {
21354            String opt = args[opti];
21355            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21356                break;
21357            }
21358            opti++;
21359
21360            if ("-a".equals(opt)) {
21361                // Right now we only know how to print all.
21362            } else if ("-h".equals(opt)) {
21363                pw.println("Package manager dump options:");
21364                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21365                pw.println("    --checkin: dump for a checkin");
21366                pw.println("    -f: print details of intent filters");
21367                pw.println("    -h: print this help");
21368                pw.println("  cmd may be one of:");
21369                pw.println("    l[ibraries]: list known shared libraries");
21370                pw.println("    f[eatures]: list device features");
21371                pw.println("    k[eysets]: print known keysets");
21372                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21373                pw.println("    perm[issions]: dump permissions");
21374                pw.println("    permission [name ...]: dump declaration and use of given permission");
21375                pw.println("    pref[erred]: print preferred package settings");
21376                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21377                pw.println("    prov[iders]: dump content providers");
21378                pw.println("    p[ackages]: dump installed packages");
21379                pw.println("    s[hared-users]: dump shared user IDs");
21380                pw.println("    m[essages]: print collected runtime messages");
21381                pw.println("    v[erifiers]: print package verifier info");
21382                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21383                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21384                pw.println("    version: print database version info");
21385                pw.println("    write: write current settings now");
21386                pw.println("    installs: details about install sessions");
21387                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21388                pw.println("    dexopt: dump dexopt state");
21389                pw.println("    compiler-stats: dump compiler statistics");
21390                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21391                pw.println("    <package.name>: info about given package");
21392                return;
21393            } else if ("--checkin".equals(opt)) {
21394                checkin = true;
21395            } else if ("-f".equals(opt)) {
21396                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21397            } else if ("--proto".equals(opt)) {
21398                dumpProto(fd);
21399                return;
21400            } else {
21401                pw.println("Unknown argument: " + opt + "; use -h for help");
21402            }
21403        }
21404
21405        // Is the caller requesting to dump a particular piece of data?
21406        if (opti < args.length) {
21407            String cmd = args[opti];
21408            opti++;
21409            // Is this a package name?
21410            if ("android".equals(cmd) || cmd.contains(".")) {
21411                packageName = cmd;
21412                // When dumping a single package, we always dump all of its
21413                // filter information since the amount of data will be reasonable.
21414                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21415            } else if ("check-permission".equals(cmd)) {
21416                if (opti >= args.length) {
21417                    pw.println("Error: check-permission missing permission argument");
21418                    return;
21419                }
21420                String perm = args[opti];
21421                opti++;
21422                if (opti >= args.length) {
21423                    pw.println("Error: check-permission missing package argument");
21424                    return;
21425                }
21426
21427                String pkg = args[opti];
21428                opti++;
21429                int user = UserHandle.getUserId(Binder.getCallingUid());
21430                if (opti < args.length) {
21431                    try {
21432                        user = Integer.parseInt(args[opti]);
21433                    } catch (NumberFormatException e) {
21434                        pw.println("Error: check-permission user argument is not a number: "
21435                                + args[opti]);
21436                        return;
21437                    }
21438                }
21439
21440                // Normalize package name to handle renamed packages and static libs
21441                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21442
21443                pw.println(checkPermission(perm, pkg, user));
21444                return;
21445            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21446                dumpState.setDump(DumpState.DUMP_LIBS);
21447            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21448                dumpState.setDump(DumpState.DUMP_FEATURES);
21449            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21450                if (opti >= args.length) {
21451                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21452                            | DumpState.DUMP_SERVICE_RESOLVERS
21453                            | DumpState.DUMP_RECEIVER_RESOLVERS
21454                            | DumpState.DUMP_CONTENT_RESOLVERS);
21455                } else {
21456                    while (opti < args.length) {
21457                        String name = args[opti];
21458                        if ("a".equals(name) || "activity".equals(name)) {
21459                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21460                        } else if ("s".equals(name) || "service".equals(name)) {
21461                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21462                        } else if ("r".equals(name) || "receiver".equals(name)) {
21463                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21464                        } else if ("c".equals(name) || "content".equals(name)) {
21465                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21466                        } else {
21467                            pw.println("Error: unknown resolver table type: " + name);
21468                            return;
21469                        }
21470                        opti++;
21471                    }
21472                }
21473            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21474                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21475            } else if ("permission".equals(cmd)) {
21476                if (opti >= args.length) {
21477                    pw.println("Error: permission requires permission name");
21478                    return;
21479                }
21480                permissionNames = new ArraySet<>();
21481                while (opti < args.length) {
21482                    permissionNames.add(args[opti]);
21483                    opti++;
21484                }
21485                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21486                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21487            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21488                dumpState.setDump(DumpState.DUMP_PREFERRED);
21489            } else if ("preferred-xml".equals(cmd)) {
21490                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21491                if (opti < args.length && "--full".equals(args[opti])) {
21492                    fullPreferred = true;
21493                    opti++;
21494                }
21495            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21496                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21497            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21498                dumpState.setDump(DumpState.DUMP_PACKAGES);
21499            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21500                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21501            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21502                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21503            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21504                dumpState.setDump(DumpState.DUMP_MESSAGES);
21505            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21506                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21507            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21508                    || "intent-filter-verifiers".equals(cmd)) {
21509                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21510            } else if ("version".equals(cmd)) {
21511                dumpState.setDump(DumpState.DUMP_VERSION);
21512            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21513                dumpState.setDump(DumpState.DUMP_KEYSETS);
21514            } else if ("installs".equals(cmd)) {
21515                dumpState.setDump(DumpState.DUMP_INSTALLS);
21516            } else if ("frozen".equals(cmd)) {
21517                dumpState.setDump(DumpState.DUMP_FROZEN);
21518            } else if ("dexopt".equals(cmd)) {
21519                dumpState.setDump(DumpState.DUMP_DEXOPT);
21520            } else if ("compiler-stats".equals(cmd)) {
21521                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21522            } else if ("enabled-overlays".equals(cmd)) {
21523                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
21524            } else if ("changes".equals(cmd)) {
21525                dumpState.setDump(DumpState.DUMP_CHANGES);
21526            } else if ("write".equals(cmd)) {
21527                synchronized (mPackages) {
21528                    mSettings.writeLPr();
21529                    pw.println("Settings written.");
21530                    return;
21531                }
21532            }
21533        }
21534
21535        if (checkin) {
21536            pw.println("vers,1");
21537        }
21538
21539        // reader
21540        synchronized (mPackages) {
21541            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21542                if (!checkin) {
21543                    if (dumpState.onTitlePrinted())
21544                        pw.println();
21545                    pw.println("Database versions:");
21546                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21547                }
21548            }
21549
21550            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21551                if (!checkin) {
21552                    if (dumpState.onTitlePrinted())
21553                        pw.println();
21554                    pw.println("Verifiers:");
21555                    pw.print("  Required: ");
21556                    pw.print(mRequiredVerifierPackage);
21557                    pw.print(" (uid=");
21558                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21559                            UserHandle.USER_SYSTEM));
21560                    pw.println(")");
21561                } else if (mRequiredVerifierPackage != null) {
21562                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21563                    pw.print(",");
21564                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21565                            UserHandle.USER_SYSTEM));
21566                }
21567            }
21568
21569            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21570                    packageName == null) {
21571                if (mIntentFilterVerifierComponent != null) {
21572                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21573                    if (!checkin) {
21574                        if (dumpState.onTitlePrinted())
21575                            pw.println();
21576                        pw.println("Intent Filter Verifier:");
21577                        pw.print("  Using: ");
21578                        pw.print(verifierPackageName);
21579                        pw.print(" (uid=");
21580                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21581                                UserHandle.USER_SYSTEM));
21582                        pw.println(")");
21583                    } else if (verifierPackageName != null) {
21584                        pw.print("ifv,"); pw.print(verifierPackageName);
21585                        pw.print(",");
21586                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21587                                UserHandle.USER_SYSTEM));
21588                    }
21589                } else {
21590                    pw.println();
21591                    pw.println("No Intent Filter Verifier available!");
21592                }
21593            }
21594
21595            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21596                boolean printedHeader = false;
21597                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21598                while (it.hasNext()) {
21599                    String libName = it.next();
21600                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21601                    if (versionedLib == null) {
21602                        continue;
21603                    }
21604                    final int versionCount = versionedLib.size();
21605                    for (int i = 0; i < versionCount; i++) {
21606                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21607                        if (!checkin) {
21608                            if (!printedHeader) {
21609                                if (dumpState.onTitlePrinted())
21610                                    pw.println();
21611                                pw.println("Libraries:");
21612                                printedHeader = true;
21613                            }
21614                            pw.print("  ");
21615                        } else {
21616                            pw.print("lib,");
21617                        }
21618                        pw.print(libEntry.info.getName());
21619                        if (libEntry.info.isStatic()) {
21620                            pw.print(" version=" + libEntry.info.getVersion());
21621                        }
21622                        if (!checkin) {
21623                            pw.print(" -> ");
21624                        }
21625                        if (libEntry.path != null) {
21626                            pw.print(" (jar) ");
21627                            pw.print(libEntry.path);
21628                        } else {
21629                            pw.print(" (apk) ");
21630                            pw.print(libEntry.apk);
21631                        }
21632                        pw.println();
21633                    }
21634                }
21635            }
21636
21637            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21638                if (dumpState.onTitlePrinted())
21639                    pw.println();
21640                if (!checkin) {
21641                    pw.println("Features:");
21642                }
21643
21644                synchronized (mAvailableFeatures) {
21645                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21646                        if (checkin) {
21647                            pw.print("feat,");
21648                            pw.print(feat.name);
21649                            pw.print(",");
21650                            pw.println(feat.version);
21651                        } else {
21652                            pw.print("  ");
21653                            pw.print(feat.name);
21654                            if (feat.version > 0) {
21655                                pw.print(" version=");
21656                                pw.print(feat.version);
21657                            }
21658                            pw.println();
21659                        }
21660                    }
21661                }
21662            }
21663
21664            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21665                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21666                        : "Activity Resolver Table:", "  ", packageName,
21667                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21668                    dumpState.setTitlePrinted(true);
21669                }
21670            }
21671            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21672                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21673                        : "Receiver Resolver Table:", "  ", packageName,
21674                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21675                    dumpState.setTitlePrinted(true);
21676                }
21677            }
21678            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21679                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21680                        : "Service Resolver Table:", "  ", packageName,
21681                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21682                    dumpState.setTitlePrinted(true);
21683                }
21684            }
21685            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21686                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21687                        : "Provider Resolver Table:", "  ", packageName,
21688                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21689                    dumpState.setTitlePrinted(true);
21690                }
21691            }
21692
21693            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21694                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21695                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21696                    int user = mSettings.mPreferredActivities.keyAt(i);
21697                    if (pir.dump(pw,
21698                            dumpState.getTitlePrinted()
21699                                ? "\nPreferred Activities User " + user + ":"
21700                                : "Preferred Activities User " + user + ":", "  ",
21701                            packageName, true, false)) {
21702                        dumpState.setTitlePrinted(true);
21703                    }
21704                }
21705            }
21706
21707            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21708                pw.flush();
21709                FileOutputStream fout = new FileOutputStream(fd);
21710                BufferedOutputStream str = new BufferedOutputStream(fout);
21711                XmlSerializer serializer = new FastXmlSerializer();
21712                try {
21713                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21714                    serializer.startDocument(null, true);
21715                    serializer.setFeature(
21716                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21717                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21718                    serializer.endDocument();
21719                    serializer.flush();
21720                } catch (IllegalArgumentException e) {
21721                    pw.println("Failed writing: " + e);
21722                } catch (IllegalStateException e) {
21723                    pw.println("Failed writing: " + e);
21724                } catch (IOException e) {
21725                    pw.println("Failed writing: " + e);
21726                }
21727            }
21728
21729            if (!checkin
21730                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21731                    && packageName == null) {
21732                pw.println();
21733                int count = mSettings.mPackages.size();
21734                if (count == 0) {
21735                    pw.println("No applications!");
21736                    pw.println();
21737                } else {
21738                    final String prefix = "  ";
21739                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21740                    if (allPackageSettings.size() == 0) {
21741                        pw.println("No domain preferred apps!");
21742                        pw.println();
21743                    } else {
21744                        pw.println("App verification status:");
21745                        pw.println();
21746                        count = 0;
21747                        for (PackageSetting ps : allPackageSettings) {
21748                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21749                            if (ivi == null || ivi.getPackageName() == null) continue;
21750                            pw.println(prefix + "Package: " + ivi.getPackageName());
21751                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21752                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21753                            pw.println();
21754                            count++;
21755                        }
21756                        if (count == 0) {
21757                            pw.println(prefix + "No app verification established.");
21758                            pw.println();
21759                        }
21760                        for (int userId : sUserManager.getUserIds()) {
21761                            pw.println("App linkages for user " + userId + ":");
21762                            pw.println();
21763                            count = 0;
21764                            for (PackageSetting ps : allPackageSettings) {
21765                                final long status = ps.getDomainVerificationStatusForUser(userId);
21766                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21767                                        && !DEBUG_DOMAIN_VERIFICATION) {
21768                                    continue;
21769                                }
21770                                pw.println(prefix + "Package: " + ps.name);
21771                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21772                                String statusStr = IntentFilterVerificationInfo.
21773                                        getStatusStringFromValue(status);
21774                                pw.println(prefix + "Status:  " + statusStr);
21775                                pw.println();
21776                                count++;
21777                            }
21778                            if (count == 0) {
21779                                pw.println(prefix + "No configured app linkages.");
21780                                pw.println();
21781                            }
21782                        }
21783                    }
21784                }
21785            }
21786
21787            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21788                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21789                if (packageName == null && permissionNames == null) {
21790                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
21791                        if (iperm == 0) {
21792                            if (dumpState.onTitlePrinted())
21793                                pw.println();
21794                            pw.println("AppOp Permissions:");
21795                        }
21796                        pw.print("  AppOp Permission ");
21797                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
21798                        pw.println(":");
21799                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
21800                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
21801                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
21802                        }
21803                    }
21804                }
21805            }
21806
21807            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21808                boolean printedSomething = false;
21809                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21810                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21811                        continue;
21812                    }
21813                    if (!printedSomething) {
21814                        if (dumpState.onTitlePrinted())
21815                            pw.println();
21816                        pw.println("Registered ContentProviders:");
21817                        printedSomething = true;
21818                    }
21819                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21820                    pw.print("    "); pw.println(p.toString());
21821                }
21822                printedSomething = false;
21823                for (Map.Entry<String, PackageParser.Provider> entry :
21824                        mProvidersByAuthority.entrySet()) {
21825                    PackageParser.Provider p = entry.getValue();
21826                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21827                        continue;
21828                    }
21829                    if (!printedSomething) {
21830                        if (dumpState.onTitlePrinted())
21831                            pw.println();
21832                        pw.println("ContentProvider Authorities:");
21833                        printedSomething = true;
21834                    }
21835                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21836                    pw.print("    "); pw.println(p.toString());
21837                    if (p.info != null && p.info.applicationInfo != null) {
21838                        final String appInfo = p.info.applicationInfo.toString();
21839                        pw.print("      applicationInfo="); pw.println(appInfo);
21840                    }
21841                }
21842            }
21843
21844            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21845                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21846            }
21847
21848            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21849                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21850            }
21851
21852            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21853                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21854            }
21855
21856            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21857                if (dumpState.onTitlePrinted()) pw.println();
21858                pw.println("Package Changes:");
21859                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21860                final int K = mChangedPackages.size();
21861                for (int i = 0; i < K; i++) {
21862                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21863                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21864                    final int N = changes.size();
21865                    if (N == 0) {
21866                        pw.print("    "); pw.println("No packages changed");
21867                    } else {
21868                        for (int j = 0; j < N; j++) {
21869                            final String pkgName = changes.valueAt(j);
21870                            final int sequenceNumber = changes.keyAt(j);
21871                            pw.print("    ");
21872                            pw.print("seq=");
21873                            pw.print(sequenceNumber);
21874                            pw.print(", package=");
21875                            pw.println(pkgName);
21876                        }
21877                    }
21878                }
21879            }
21880
21881            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21882                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21883            }
21884
21885            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21886                // XXX should handle packageName != null by dumping only install data that
21887                // the given package is involved with.
21888                if (dumpState.onTitlePrinted()) pw.println();
21889
21890                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21891                ipw.println();
21892                ipw.println("Frozen packages:");
21893                ipw.increaseIndent();
21894                if (mFrozenPackages.size() == 0) {
21895                    ipw.println("(none)");
21896                } else {
21897                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21898                        ipw.println(mFrozenPackages.valueAt(i));
21899                    }
21900                }
21901                ipw.decreaseIndent();
21902            }
21903
21904            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21905                if (dumpState.onTitlePrinted()) pw.println();
21906                dumpDexoptStateLPr(pw, packageName);
21907            }
21908
21909            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21910                if (dumpState.onTitlePrinted()) pw.println();
21911                dumpCompilerStatsLPr(pw, packageName);
21912            }
21913
21914            if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) {
21915                if (dumpState.onTitlePrinted()) pw.println();
21916                dumpEnabledOverlaysLPr(pw);
21917            }
21918
21919            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21920                if (dumpState.onTitlePrinted()) pw.println();
21921                mSettings.dumpReadMessagesLPr(pw, dumpState);
21922
21923                pw.println();
21924                pw.println("Package warning messages:");
21925                BufferedReader in = null;
21926                String line = null;
21927                try {
21928                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21929                    while ((line = in.readLine()) != null) {
21930                        if (line.contains("ignored: updated version")) continue;
21931                        pw.println(line);
21932                    }
21933                } catch (IOException ignored) {
21934                } finally {
21935                    IoUtils.closeQuietly(in);
21936                }
21937            }
21938
21939            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21940                BufferedReader in = null;
21941                String line = null;
21942                try {
21943                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21944                    while ((line = in.readLine()) != null) {
21945                        if (line.contains("ignored: updated version")) continue;
21946                        pw.print("msg,");
21947                        pw.println(line);
21948                    }
21949                } catch (IOException ignored) {
21950                } finally {
21951                    IoUtils.closeQuietly(in);
21952                }
21953            }
21954        }
21955
21956        // PackageInstaller should be called outside of mPackages lock
21957        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21958            // XXX should handle packageName != null by dumping only install data that
21959            // the given package is involved with.
21960            if (dumpState.onTitlePrinted()) pw.println();
21961            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21962        }
21963    }
21964
21965    private void dumpProto(FileDescriptor fd) {
21966        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21967
21968        synchronized (mPackages) {
21969            final long requiredVerifierPackageToken =
21970                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21971            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21972            proto.write(
21973                    PackageServiceDumpProto.PackageShortProto.UID,
21974                    getPackageUid(
21975                            mRequiredVerifierPackage,
21976                            MATCH_DEBUG_TRIAGED_MISSING,
21977                            UserHandle.USER_SYSTEM));
21978            proto.end(requiredVerifierPackageToken);
21979
21980            if (mIntentFilterVerifierComponent != null) {
21981                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21982                final long verifierPackageToken =
21983                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21984                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21985                proto.write(
21986                        PackageServiceDumpProto.PackageShortProto.UID,
21987                        getPackageUid(
21988                                verifierPackageName,
21989                                MATCH_DEBUG_TRIAGED_MISSING,
21990                                UserHandle.USER_SYSTEM));
21991                proto.end(verifierPackageToken);
21992            }
21993
21994            dumpSharedLibrariesProto(proto);
21995            dumpFeaturesProto(proto);
21996            mSettings.dumpPackagesProto(proto);
21997            mSettings.dumpSharedUsersProto(proto);
21998            dumpMessagesProto(proto);
21999        }
22000        proto.flush();
22001    }
22002
22003    private void dumpMessagesProto(ProtoOutputStream proto) {
22004        BufferedReader in = null;
22005        String line = null;
22006        try {
22007            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22008            while ((line = in.readLine()) != null) {
22009                if (line.contains("ignored: updated version")) continue;
22010                proto.write(PackageServiceDumpProto.MESSAGES, line);
22011            }
22012        } catch (IOException ignored) {
22013        } finally {
22014            IoUtils.closeQuietly(in);
22015        }
22016    }
22017
22018    private void dumpFeaturesProto(ProtoOutputStream proto) {
22019        synchronized (mAvailableFeatures) {
22020            final int count = mAvailableFeatures.size();
22021            for (int i = 0; i < count; i++) {
22022                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22023                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22024                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22025                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22026                proto.end(featureToken);
22027            }
22028        }
22029    }
22030
22031    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22032        final int count = mSharedLibraries.size();
22033        for (int i = 0; i < count; i++) {
22034            final String libName = mSharedLibraries.keyAt(i);
22035            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22036            if (versionedLib == null) {
22037                continue;
22038            }
22039            final int versionCount = versionedLib.size();
22040            for (int j = 0; j < versionCount; j++) {
22041                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22042                final long sharedLibraryToken =
22043                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22044                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22045                final boolean isJar = (libEntry.path != null);
22046                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22047                if (isJar) {
22048                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22049                } else {
22050                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22051                }
22052                proto.end(sharedLibraryToken);
22053            }
22054        }
22055    }
22056
22057    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22058        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22059        ipw.println();
22060        ipw.println("Dexopt state:");
22061        ipw.increaseIndent();
22062        Collection<PackageParser.Package> packages = null;
22063        if (packageName != null) {
22064            PackageParser.Package targetPackage = mPackages.get(packageName);
22065            if (targetPackage != null) {
22066                packages = Collections.singletonList(targetPackage);
22067            } else {
22068                ipw.println("Unable to find package: " + packageName);
22069                return;
22070            }
22071        } else {
22072            packages = mPackages.values();
22073        }
22074
22075        for (PackageParser.Package pkg : packages) {
22076            ipw.println("[" + pkg.packageName + "]");
22077            ipw.increaseIndent();
22078            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
22079            ipw.decreaseIndent();
22080        }
22081    }
22082
22083    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22084        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22085        ipw.println();
22086        ipw.println("Compiler stats:");
22087        ipw.increaseIndent();
22088        Collection<PackageParser.Package> packages = null;
22089        if (packageName != null) {
22090            PackageParser.Package targetPackage = mPackages.get(packageName);
22091            if (targetPackage != null) {
22092                packages = Collections.singletonList(targetPackage);
22093            } else {
22094                ipw.println("Unable to find package: " + packageName);
22095                return;
22096            }
22097        } else {
22098            packages = mPackages.values();
22099        }
22100
22101        for (PackageParser.Package pkg : packages) {
22102            ipw.println("[" + pkg.packageName + "]");
22103            ipw.increaseIndent();
22104
22105            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22106            if (stats == null) {
22107                ipw.println("(No recorded stats)");
22108            } else {
22109                stats.dump(ipw);
22110            }
22111            ipw.decreaseIndent();
22112        }
22113    }
22114
22115    private void dumpEnabledOverlaysLPr(PrintWriter pw) {
22116        pw.println("Enabled overlay paths:");
22117        final int N = mEnabledOverlayPaths.size();
22118        for (int i = 0; i < N; i++) {
22119            final int userId = mEnabledOverlayPaths.keyAt(i);
22120            pw.println(String.format("    User %d:", userId));
22121            final ArrayMap<String, ArrayList<String>> userSpecificOverlays =
22122                mEnabledOverlayPaths.valueAt(i);
22123            final int M = userSpecificOverlays.size();
22124            for (int j = 0; j < M; j++) {
22125                final String targetPackageName = userSpecificOverlays.keyAt(j);
22126                final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j);
22127                pw.println(String.format("        %s: %s", targetPackageName, overlayPackagePaths));
22128            }
22129        }
22130    }
22131
22132    private String dumpDomainString(String packageName) {
22133        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22134                .getList();
22135        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22136
22137        ArraySet<String> result = new ArraySet<>();
22138        if (iviList.size() > 0) {
22139            for (IntentFilterVerificationInfo ivi : iviList) {
22140                for (String host : ivi.getDomains()) {
22141                    result.add(host);
22142                }
22143            }
22144        }
22145        if (filters != null && filters.size() > 0) {
22146            for (IntentFilter filter : filters) {
22147                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22148                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22149                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22150                    result.addAll(filter.getHostsList());
22151                }
22152            }
22153        }
22154
22155        StringBuilder sb = new StringBuilder(result.size() * 16);
22156        for (String domain : result) {
22157            if (sb.length() > 0) sb.append(" ");
22158            sb.append(domain);
22159        }
22160        return sb.toString();
22161    }
22162
22163    // ------- apps on sdcard specific code -------
22164    static final boolean DEBUG_SD_INSTALL = false;
22165
22166    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22167
22168    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22169
22170    private boolean mMediaMounted = false;
22171
22172    static String getEncryptKey() {
22173        try {
22174            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22175                    SD_ENCRYPTION_KEYSTORE_NAME);
22176            if (sdEncKey == null) {
22177                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22178                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22179                if (sdEncKey == null) {
22180                    Slog.e(TAG, "Failed to create encryption keys");
22181                    return null;
22182                }
22183            }
22184            return sdEncKey;
22185        } catch (NoSuchAlgorithmException nsae) {
22186            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22187            return null;
22188        } catch (IOException ioe) {
22189            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22190            return null;
22191        }
22192    }
22193
22194    /*
22195     * Update media status on PackageManager.
22196     */
22197    @Override
22198    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22199        enforceSystemOrRoot("Media status can only be updated by the system");
22200        // reader; this apparently protects mMediaMounted, but should probably
22201        // be a different lock in that case.
22202        synchronized (mPackages) {
22203            Log.i(TAG, "Updating external media status from "
22204                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
22205                    + (mediaStatus ? "mounted" : "unmounted"));
22206            if (DEBUG_SD_INSTALL)
22207                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22208                        + ", mMediaMounted=" + mMediaMounted);
22209            if (mediaStatus == mMediaMounted) {
22210                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22211                        : 0, -1);
22212                mHandler.sendMessage(msg);
22213                return;
22214            }
22215            mMediaMounted = mediaStatus;
22216        }
22217        // Queue up an async operation since the package installation may take a
22218        // little while.
22219        mHandler.post(new Runnable() {
22220            public void run() {
22221                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22222            }
22223        });
22224    }
22225
22226    /**
22227     * Called by StorageManagerService when the initial ASECs to scan are available.
22228     * Should block until all the ASEC containers are finished being scanned.
22229     */
22230    public void scanAvailableAsecs() {
22231        updateExternalMediaStatusInner(true, false, false);
22232    }
22233
22234    /*
22235     * Collect information of applications on external media, map them against
22236     * existing containers and update information based on current mount status.
22237     * Please note that we always have to report status if reportStatus has been
22238     * set to true especially when unloading packages.
22239     */
22240    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
22241            boolean externalStorage) {
22242        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
22243        int[] uidArr = EmptyArray.INT;
22244
22245        final String[] list = PackageHelper.getSecureContainerList();
22246        if (ArrayUtils.isEmpty(list)) {
22247            Log.i(TAG, "No secure containers found");
22248        } else {
22249            // Process list of secure containers and categorize them
22250            // as active or stale based on their package internal state.
22251
22252            // reader
22253            synchronized (mPackages) {
22254                for (String cid : list) {
22255                    // Leave stages untouched for now; installer service owns them
22256                    if (PackageInstallerService.isStageName(cid)) continue;
22257
22258                    if (DEBUG_SD_INSTALL)
22259                        Log.i(TAG, "Processing container " + cid);
22260                    String pkgName = getAsecPackageName(cid);
22261                    if (pkgName == null) {
22262                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
22263                        continue;
22264                    }
22265                    if (DEBUG_SD_INSTALL)
22266                        Log.i(TAG, "Looking for pkg : " + pkgName);
22267
22268                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
22269                    if (ps == null) {
22270                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
22271                        continue;
22272                    }
22273
22274                    /*
22275                     * Skip packages that are not external if we're unmounting
22276                     * external storage.
22277                     */
22278                    if (externalStorage && !isMounted && !isExternal(ps)) {
22279                        continue;
22280                    }
22281
22282                    final AsecInstallArgs args = new AsecInstallArgs(cid,
22283                            getAppDexInstructionSets(ps), ps.isForwardLocked());
22284                    // The package status is changed only if the code path
22285                    // matches between settings and the container id.
22286                    if (ps.codePathString != null
22287                            && ps.codePathString.startsWith(args.getCodePath())) {
22288                        if (DEBUG_SD_INSTALL) {
22289                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
22290                                    + " at code path: " + ps.codePathString);
22291                        }
22292
22293                        // We do have a valid package installed on sdcard
22294                        processCids.put(args, ps.codePathString);
22295                        final int uid = ps.appId;
22296                        if (uid != -1) {
22297                            uidArr = ArrayUtils.appendInt(uidArr, uid);
22298                        }
22299                    } else {
22300                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
22301                                + ps.codePathString);
22302                    }
22303                }
22304            }
22305
22306            Arrays.sort(uidArr);
22307        }
22308
22309        // Process packages with valid entries.
22310        if (isMounted) {
22311            if (DEBUG_SD_INSTALL)
22312                Log.i(TAG, "Loading packages");
22313            loadMediaPackages(processCids, uidArr, externalStorage);
22314            startCleaningPackages();
22315            mInstallerService.onSecureContainersAvailable();
22316        } else {
22317            if (DEBUG_SD_INSTALL)
22318                Log.i(TAG, "Unloading packages");
22319            unloadMediaPackages(processCids, uidArr, reportStatus);
22320        }
22321    }
22322
22323    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22324            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22325        final int size = infos.size();
22326        final String[] packageNames = new String[size];
22327        final int[] packageUids = new int[size];
22328        for (int i = 0; i < size; i++) {
22329            final ApplicationInfo info = infos.get(i);
22330            packageNames[i] = info.packageName;
22331            packageUids[i] = info.uid;
22332        }
22333        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22334                finishedReceiver);
22335    }
22336
22337    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22338            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22339        sendResourcesChangedBroadcast(mediaStatus, replacing,
22340                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22341    }
22342
22343    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22344            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22345        int size = pkgList.length;
22346        if (size > 0) {
22347            // Send broadcasts here
22348            Bundle extras = new Bundle();
22349            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22350            if (uidArr != null) {
22351                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22352            }
22353            if (replacing) {
22354                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22355            }
22356            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22357                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22358            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22359        }
22360    }
22361
22362   /*
22363     * Look at potentially valid container ids from processCids If package
22364     * information doesn't match the one on record or package scanning fails,
22365     * the cid is added to list of removeCids. We currently don't delete stale
22366     * containers.
22367     */
22368    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
22369            boolean externalStorage) {
22370        ArrayList<String> pkgList = new ArrayList<String>();
22371        Set<AsecInstallArgs> keys = processCids.keySet();
22372
22373        for (AsecInstallArgs args : keys) {
22374            String codePath = processCids.get(args);
22375            if (DEBUG_SD_INSTALL)
22376                Log.i(TAG, "Loading container : " + args.cid);
22377            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
22378            try {
22379                // Make sure there are no container errors first.
22380                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
22381                    Slog.e(TAG, "Failed to mount cid : " + args.cid
22382                            + " when installing from sdcard");
22383                    continue;
22384                }
22385                // Check code path here.
22386                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
22387                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
22388                            + " does not match one in settings " + codePath);
22389                    continue;
22390                }
22391                // Parse package
22392                int parseFlags = mDefParseFlags;
22393                if (args.isExternalAsec()) {
22394                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
22395                }
22396                if (args.isFwdLocked()) {
22397                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
22398                }
22399
22400                synchronized (mInstallLock) {
22401                    PackageParser.Package pkg = null;
22402                    try {
22403                        // Sadly we don't know the package name yet to freeze it
22404                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
22405                                SCAN_IGNORE_FROZEN, 0, null);
22406                    } catch (PackageManagerException e) {
22407                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
22408                    }
22409                    // Scan the package
22410                    if (pkg != null) {
22411                        /*
22412                         * TODO why is the lock being held? doPostInstall is
22413                         * called in other places without the lock. This needs
22414                         * to be straightened out.
22415                         */
22416                        // writer
22417                        synchronized (mPackages) {
22418                            retCode = PackageManager.INSTALL_SUCCEEDED;
22419                            pkgList.add(pkg.packageName);
22420                            // Post process args
22421                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
22422                                    pkg.applicationInfo.uid);
22423                        }
22424                    } else {
22425                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
22426                    }
22427                }
22428
22429            } finally {
22430                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
22431                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
22432                }
22433            }
22434        }
22435        // writer
22436        synchronized (mPackages) {
22437            // If the platform SDK has changed since the last time we booted,
22438            // we need to re-grant app permission to catch any new ones that
22439            // appear. This is really a hack, and means that apps can in some
22440            // cases get permissions that the user didn't initially explicitly
22441            // allow... it would be nice to have some better way to handle
22442            // this situation.
22443            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
22444                    : mSettings.getInternalVersion();
22445            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
22446                    : StorageManager.UUID_PRIVATE_INTERNAL;
22447
22448            int updateFlags = UPDATE_PERMISSIONS_ALL;
22449            if (ver.sdkVersion != mSdkVersion) {
22450                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22451                        + mSdkVersion + "; regranting permissions for external");
22452                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22453            }
22454            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22455
22456            // Yay, everything is now upgraded
22457            ver.forceCurrent();
22458
22459            // can downgrade to reader
22460            // Persist settings
22461            mSettings.writeLPr();
22462        }
22463        // Send a broadcast to let everyone know we are done processing
22464        if (pkgList.size() > 0) {
22465            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
22466        }
22467    }
22468
22469   /*
22470     * Utility method to unload a list of specified containers
22471     */
22472    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
22473        // Just unmount all valid containers.
22474        for (AsecInstallArgs arg : cidArgs) {
22475            synchronized (mInstallLock) {
22476                arg.doPostDeleteLI(false);
22477           }
22478       }
22479   }
22480
22481    /*
22482     * Unload packages mounted on external media. This involves deleting package
22483     * data from internal structures, sending broadcasts about disabled packages,
22484     * gc'ing to free up references, unmounting all secure containers
22485     * corresponding to packages on external media, and posting a
22486     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
22487     * that we always have to post this message if status has been requested no
22488     * matter what.
22489     */
22490    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
22491            final boolean reportStatus) {
22492        if (DEBUG_SD_INSTALL)
22493            Log.i(TAG, "unloading media packages");
22494        ArrayList<String> pkgList = new ArrayList<String>();
22495        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
22496        final Set<AsecInstallArgs> keys = processCids.keySet();
22497        for (AsecInstallArgs args : keys) {
22498            String pkgName = args.getPackageName();
22499            if (DEBUG_SD_INSTALL)
22500                Log.i(TAG, "Trying to unload pkg : " + pkgName);
22501            // Delete package internally
22502            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22503            synchronized (mInstallLock) {
22504                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22505                final boolean res;
22506                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
22507                        "unloadMediaPackages")) {
22508                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
22509                            null);
22510                }
22511                if (res) {
22512                    pkgList.add(pkgName);
22513                } else {
22514                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
22515                    failedList.add(args);
22516                }
22517            }
22518        }
22519
22520        // reader
22521        synchronized (mPackages) {
22522            // We didn't update the settings after removing each package;
22523            // write them now for all packages.
22524            mSettings.writeLPr();
22525        }
22526
22527        // We have to absolutely send UPDATED_MEDIA_STATUS only
22528        // after confirming that all the receivers processed the ordered
22529        // broadcast when packages get disabled, force a gc to clean things up.
22530        // and unload all the containers.
22531        if (pkgList.size() > 0) {
22532            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
22533                    new IIntentReceiver.Stub() {
22534                public void performReceive(Intent intent, int resultCode, String data,
22535                        Bundle extras, boolean ordered, boolean sticky,
22536                        int sendingUser) throws RemoteException {
22537                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
22538                            reportStatus ? 1 : 0, 1, keys);
22539                    mHandler.sendMessage(msg);
22540                }
22541            });
22542        } else {
22543            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
22544                    keys);
22545            mHandler.sendMessage(msg);
22546        }
22547    }
22548
22549    private void loadPrivatePackages(final VolumeInfo vol) {
22550        mHandler.post(new Runnable() {
22551            @Override
22552            public void run() {
22553                loadPrivatePackagesInner(vol);
22554            }
22555        });
22556    }
22557
22558    private void loadPrivatePackagesInner(VolumeInfo vol) {
22559        final String volumeUuid = vol.fsUuid;
22560        if (TextUtils.isEmpty(volumeUuid)) {
22561            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22562            return;
22563        }
22564
22565        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22566        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22567        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22568
22569        final VersionInfo ver;
22570        final List<PackageSetting> packages;
22571        synchronized (mPackages) {
22572            ver = mSettings.findOrCreateVersion(volumeUuid);
22573            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22574        }
22575
22576        for (PackageSetting ps : packages) {
22577            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22578            synchronized (mInstallLock) {
22579                final PackageParser.Package pkg;
22580                try {
22581                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22582                    loaded.add(pkg.applicationInfo);
22583
22584                } catch (PackageManagerException e) {
22585                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22586                }
22587
22588                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22589                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22590                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22591                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22592                }
22593            }
22594        }
22595
22596        // Reconcile app data for all started/unlocked users
22597        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22598        final UserManager um = mContext.getSystemService(UserManager.class);
22599        UserManagerInternal umInternal = getUserManagerInternal();
22600        for (UserInfo user : um.getUsers()) {
22601            final int flags;
22602            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22603                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22604            } else if (umInternal.isUserRunning(user.id)) {
22605                flags = StorageManager.FLAG_STORAGE_DE;
22606            } else {
22607                continue;
22608            }
22609
22610            try {
22611                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22612                synchronized (mInstallLock) {
22613                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22614                }
22615            } catch (IllegalStateException e) {
22616                // Device was probably ejected, and we'll process that event momentarily
22617                Slog.w(TAG, "Failed to prepare storage: " + e);
22618            }
22619        }
22620
22621        synchronized (mPackages) {
22622            int updateFlags = UPDATE_PERMISSIONS_ALL;
22623            if (ver.sdkVersion != mSdkVersion) {
22624                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22625                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22626                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22627            }
22628            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22629
22630            // Yay, everything is now upgraded
22631            ver.forceCurrent();
22632
22633            mSettings.writeLPr();
22634        }
22635
22636        for (PackageFreezer freezer : freezers) {
22637            freezer.close();
22638        }
22639
22640        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22641        sendResourcesChangedBroadcast(true, false, loaded, null);
22642    }
22643
22644    private void unloadPrivatePackages(final VolumeInfo vol) {
22645        mHandler.post(new Runnable() {
22646            @Override
22647            public void run() {
22648                unloadPrivatePackagesInner(vol);
22649            }
22650        });
22651    }
22652
22653    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22654        final String volumeUuid = vol.fsUuid;
22655        if (TextUtils.isEmpty(volumeUuid)) {
22656            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22657            return;
22658        }
22659
22660        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22661        synchronized (mInstallLock) {
22662        synchronized (mPackages) {
22663            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22664            for (PackageSetting ps : packages) {
22665                if (ps.pkg == null) continue;
22666
22667                final ApplicationInfo info = ps.pkg.applicationInfo;
22668                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22669                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22670
22671                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22672                        "unloadPrivatePackagesInner")) {
22673                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22674                            false, null)) {
22675                        unloaded.add(info);
22676                    } else {
22677                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22678                    }
22679                }
22680
22681                // Try very hard to release any references to this package
22682                // so we don't risk the system server being killed due to
22683                // open FDs
22684                AttributeCache.instance().removePackage(ps.name);
22685            }
22686
22687            mSettings.writeLPr();
22688        }
22689        }
22690
22691        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22692        sendResourcesChangedBroadcast(false, false, unloaded, null);
22693
22694        // Try very hard to release any references to this path so we don't risk
22695        // the system server being killed due to open FDs
22696        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22697
22698        for (int i = 0; i < 3; i++) {
22699            System.gc();
22700            System.runFinalization();
22701        }
22702    }
22703
22704    private void assertPackageKnown(String volumeUuid, String packageName)
22705            throws PackageManagerException {
22706        synchronized (mPackages) {
22707            // Normalize package name to handle renamed packages
22708            packageName = normalizePackageNameLPr(packageName);
22709
22710            final PackageSetting ps = mSettings.mPackages.get(packageName);
22711            if (ps == null) {
22712                throw new PackageManagerException("Package " + packageName + " is unknown");
22713            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22714                throw new PackageManagerException(
22715                        "Package " + packageName + " found on unknown volume " + volumeUuid
22716                                + "; expected volume " + ps.volumeUuid);
22717            }
22718        }
22719    }
22720
22721    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22722            throws PackageManagerException {
22723        synchronized (mPackages) {
22724            // Normalize package name to handle renamed packages
22725            packageName = normalizePackageNameLPr(packageName);
22726
22727            final PackageSetting ps = mSettings.mPackages.get(packageName);
22728            if (ps == null) {
22729                throw new PackageManagerException("Package " + packageName + " is unknown");
22730            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22731                throw new PackageManagerException(
22732                        "Package " + packageName + " found on unknown volume " + volumeUuid
22733                                + "; expected volume " + ps.volumeUuid);
22734            } else if (!ps.getInstalled(userId)) {
22735                throw new PackageManagerException(
22736                        "Package " + packageName + " not installed for user " + userId);
22737            }
22738        }
22739    }
22740
22741    private List<String> collectAbsoluteCodePaths() {
22742        synchronized (mPackages) {
22743            List<String> codePaths = new ArrayList<>();
22744            final int packageCount = mSettings.mPackages.size();
22745            for (int i = 0; i < packageCount; i++) {
22746                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22747                codePaths.add(ps.codePath.getAbsolutePath());
22748            }
22749            return codePaths;
22750        }
22751    }
22752
22753    /**
22754     * Examine all apps present on given mounted volume, and destroy apps that
22755     * aren't expected, either due to uninstallation or reinstallation on
22756     * another volume.
22757     */
22758    private void reconcileApps(String volumeUuid) {
22759        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22760        List<File> filesToDelete = null;
22761
22762        final File[] files = FileUtils.listFilesOrEmpty(
22763                Environment.getDataAppDirectory(volumeUuid));
22764        for (File file : files) {
22765            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22766                    && !PackageInstallerService.isStageName(file.getName());
22767            if (!isPackage) {
22768                // Ignore entries which are not packages
22769                continue;
22770            }
22771
22772            String absolutePath = file.getAbsolutePath();
22773
22774            boolean pathValid = false;
22775            final int absoluteCodePathCount = absoluteCodePaths.size();
22776            for (int i = 0; i < absoluteCodePathCount; i++) {
22777                String absoluteCodePath = absoluteCodePaths.get(i);
22778                if (absolutePath.startsWith(absoluteCodePath)) {
22779                    pathValid = true;
22780                    break;
22781                }
22782            }
22783
22784            if (!pathValid) {
22785                if (filesToDelete == null) {
22786                    filesToDelete = new ArrayList<>();
22787                }
22788                filesToDelete.add(file);
22789            }
22790        }
22791
22792        if (filesToDelete != null) {
22793            final int fileToDeleteCount = filesToDelete.size();
22794            for (int i = 0; i < fileToDeleteCount; i++) {
22795                File fileToDelete = filesToDelete.get(i);
22796                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22797                synchronized (mInstallLock) {
22798                    removeCodePathLI(fileToDelete);
22799                }
22800            }
22801        }
22802    }
22803
22804    /**
22805     * Reconcile all app data for the given user.
22806     * <p>
22807     * Verifies that directories exist and that ownership and labeling is
22808     * correct for all installed apps on all mounted volumes.
22809     */
22810    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22811        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22812        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22813            final String volumeUuid = vol.getFsUuid();
22814            synchronized (mInstallLock) {
22815                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22816            }
22817        }
22818    }
22819
22820    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22821            boolean migrateAppData) {
22822        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22823    }
22824
22825    /**
22826     * Reconcile all app data on given mounted volume.
22827     * <p>
22828     * Destroys app data that isn't expected, either due to uninstallation or
22829     * reinstallation on another volume.
22830     * <p>
22831     * Verifies that directories exist and that ownership and labeling is
22832     * correct for all installed apps.
22833     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22834     */
22835    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22836            boolean migrateAppData, boolean onlyCoreApps) {
22837        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22838                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22839        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22840
22841        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22842        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22843
22844        // First look for stale data that doesn't belong, and check if things
22845        // have changed since we did our last restorecon
22846        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22847            if (StorageManager.isFileEncryptedNativeOrEmulated()
22848                    && !StorageManager.isUserKeyUnlocked(userId)) {
22849                throw new RuntimeException(
22850                        "Yikes, someone asked us to reconcile CE storage while " + userId
22851                                + " was still locked; this would have caused massive data loss!");
22852            }
22853
22854            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22855            for (File file : files) {
22856                final String packageName = file.getName();
22857                try {
22858                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22859                } catch (PackageManagerException e) {
22860                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22861                    try {
22862                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22863                                StorageManager.FLAG_STORAGE_CE, 0);
22864                    } catch (InstallerException e2) {
22865                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22866                    }
22867                }
22868            }
22869        }
22870        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22871            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22872            for (File file : files) {
22873                final String packageName = file.getName();
22874                try {
22875                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22876                } catch (PackageManagerException e) {
22877                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22878                    try {
22879                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22880                                StorageManager.FLAG_STORAGE_DE, 0);
22881                    } catch (InstallerException e2) {
22882                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22883                    }
22884                }
22885            }
22886        }
22887
22888        // Ensure that data directories are ready to roll for all packages
22889        // installed for this volume and user
22890        final List<PackageSetting> packages;
22891        synchronized (mPackages) {
22892            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22893        }
22894        int preparedCount = 0;
22895        for (PackageSetting ps : packages) {
22896            final String packageName = ps.name;
22897            if (ps.pkg == null) {
22898                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22899                // TODO: might be due to legacy ASEC apps; we should circle back
22900                // and reconcile again once they're scanned
22901                continue;
22902            }
22903            // Skip non-core apps if requested
22904            if (onlyCoreApps && !ps.pkg.coreApp) {
22905                result.add(packageName);
22906                continue;
22907            }
22908
22909            if (ps.getInstalled(userId)) {
22910                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22911                preparedCount++;
22912            }
22913        }
22914
22915        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22916        return result;
22917    }
22918
22919    /**
22920     * Prepare app data for the given app just after it was installed or
22921     * upgraded. This method carefully only touches users that it's installed
22922     * for, and it forces a restorecon to handle any seinfo changes.
22923     * <p>
22924     * Verifies that directories exist and that ownership and labeling is
22925     * correct for all installed apps. If there is an ownership mismatch, it
22926     * will try recovering system apps by wiping data; third-party app data is
22927     * left intact.
22928     * <p>
22929     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22930     */
22931    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22932        final PackageSetting ps;
22933        synchronized (mPackages) {
22934            ps = mSettings.mPackages.get(pkg.packageName);
22935            mSettings.writeKernelMappingLPr(ps);
22936        }
22937
22938        final UserManager um = mContext.getSystemService(UserManager.class);
22939        UserManagerInternal umInternal = getUserManagerInternal();
22940        for (UserInfo user : um.getUsers()) {
22941            final int flags;
22942            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22943                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22944            } else if (umInternal.isUserRunning(user.id)) {
22945                flags = StorageManager.FLAG_STORAGE_DE;
22946            } else {
22947                continue;
22948            }
22949
22950            if (ps.getInstalled(user.id)) {
22951                // TODO: when user data is locked, mark that we're still dirty
22952                prepareAppDataLIF(pkg, user.id, flags);
22953            }
22954        }
22955    }
22956
22957    /**
22958     * Prepare app data for the given app.
22959     * <p>
22960     * Verifies that directories exist and that ownership and labeling is
22961     * correct for all installed apps. If there is an ownership mismatch, this
22962     * will try recovering system apps by wiping data; third-party app data is
22963     * left intact.
22964     */
22965    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22966        if (pkg == null) {
22967            Slog.wtf(TAG, "Package was null!", new Throwable());
22968            return;
22969        }
22970        prepareAppDataLeafLIF(pkg, userId, flags);
22971        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22972        for (int i = 0; i < childCount; i++) {
22973            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22974        }
22975    }
22976
22977    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22978            boolean maybeMigrateAppData) {
22979        prepareAppDataLIF(pkg, userId, flags);
22980
22981        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22982            // We may have just shuffled around app data directories, so
22983            // prepare them one more time
22984            prepareAppDataLIF(pkg, userId, flags);
22985        }
22986    }
22987
22988    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22989        if (DEBUG_APP_DATA) {
22990            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22991                    + Integer.toHexString(flags));
22992        }
22993
22994        final String volumeUuid = pkg.volumeUuid;
22995        final String packageName = pkg.packageName;
22996        final ApplicationInfo app = pkg.applicationInfo;
22997        final int appId = UserHandle.getAppId(app.uid);
22998
22999        Preconditions.checkNotNull(app.seInfo);
23000
23001        long ceDataInode = -1;
23002        try {
23003            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23004                    appId, app.seInfo, app.targetSdkVersion);
23005        } catch (InstallerException e) {
23006            if (app.isSystemApp()) {
23007                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23008                        + ", but trying to recover: " + e);
23009                destroyAppDataLeafLIF(pkg, userId, flags);
23010                try {
23011                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23012                            appId, app.seInfo, app.targetSdkVersion);
23013                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23014                } catch (InstallerException e2) {
23015                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23016                }
23017            } else {
23018                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23019            }
23020        }
23021
23022        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23023            // TODO: mark this structure as dirty so we persist it!
23024            synchronized (mPackages) {
23025                final PackageSetting ps = mSettings.mPackages.get(packageName);
23026                if (ps != null) {
23027                    ps.setCeDataInode(ceDataInode, userId);
23028                }
23029            }
23030        }
23031
23032        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23033    }
23034
23035    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23036        if (pkg == null) {
23037            Slog.wtf(TAG, "Package was null!", new Throwable());
23038            return;
23039        }
23040        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23041        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23042        for (int i = 0; i < childCount; i++) {
23043            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23044        }
23045    }
23046
23047    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23048        final String volumeUuid = pkg.volumeUuid;
23049        final String packageName = pkg.packageName;
23050        final ApplicationInfo app = pkg.applicationInfo;
23051
23052        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23053            // Create a native library symlink only if we have native libraries
23054            // and if the native libraries are 32 bit libraries. We do not provide
23055            // this symlink for 64 bit libraries.
23056            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23057                final String nativeLibPath = app.nativeLibraryDir;
23058                try {
23059                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23060                            nativeLibPath, userId);
23061                } catch (InstallerException e) {
23062                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23063                }
23064            }
23065        }
23066    }
23067
23068    /**
23069     * For system apps on non-FBE devices, this method migrates any existing
23070     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23071     * requested by the app.
23072     */
23073    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23074        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23075                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23076            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23077                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23078            try {
23079                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23080                        storageTarget);
23081            } catch (InstallerException e) {
23082                logCriticalInfo(Log.WARN,
23083                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23084            }
23085            return true;
23086        } else {
23087            return false;
23088        }
23089    }
23090
23091    public PackageFreezer freezePackage(String packageName, String killReason) {
23092        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23093    }
23094
23095    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23096        return new PackageFreezer(packageName, userId, killReason);
23097    }
23098
23099    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23100            String killReason) {
23101        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23102    }
23103
23104    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23105            String killReason) {
23106        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23107            return new PackageFreezer();
23108        } else {
23109            return freezePackage(packageName, userId, killReason);
23110        }
23111    }
23112
23113    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23114            String killReason) {
23115        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23116    }
23117
23118    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23119            String killReason) {
23120        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23121            return new PackageFreezer();
23122        } else {
23123            return freezePackage(packageName, userId, killReason);
23124        }
23125    }
23126
23127    /**
23128     * Class that freezes and kills the given package upon creation, and
23129     * unfreezes it upon closing. This is typically used when doing surgery on
23130     * app code/data to prevent the app from running while you're working.
23131     */
23132    private class PackageFreezer implements AutoCloseable {
23133        private final String mPackageName;
23134        private final PackageFreezer[] mChildren;
23135
23136        private final boolean mWeFroze;
23137
23138        private final AtomicBoolean mClosed = new AtomicBoolean();
23139        private final CloseGuard mCloseGuard = CloseGuard.get();
23140
23141        /**
23142         * Create and return a stub freezer that doesn't actually do anything,
23143         * typically used when someone requested
23144         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23145         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23146         */
23147        public PackageFreezer() {
23148            mPackageName = null;
23149            mChildren = null;
23150            mWeFroze = false;
23151            mCloseGuard.open("close");
23152        }
23153
23154        public PackageFreezer(String packageName, int userId, String killReason) {
23155            synchronized (mPackages) {
23156                mPackageName = packageName;
23157                mWeFroze = mFrozenPackages.add(mPackageName);
23158
23159                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23160                if (ps != null) {
23161                    killApplication(ps.name, ps.appId, userId, killReason);
23162                }
23163
23164                final PackageParser.Package p = mPackages.get(packageName);
23165                if (p != null && p.childPackages != null) {
23166                    final int N = p.childPackages.size();
23167                    mChildren = new PackageFreezer[N];
23168                    for (int i = 0; i < N; i++) {
23169                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23170                                userId, killReason);
23171                    }
23172                } else {
23173                    mChildren = null;
23174                }
23175            }
23176            mCloseGuard.open("close");
23177        }
23178
23179        @Override
23180        protected void finalize() throws Throwable {
23181            try {
23182                if (mCloseGuard != null) {
23183                    mCloseGuard.warnIfOpen();
23184                }
23185
23186                close();
23187            } finally {
23188                super.finalize();
23189            }
23190        }
23191
23192        @Override
23193        public void close() {
23194            mCloseGuard.close();
23195            if (mClosed.compareAndSet(false, true)) {
23196                synchronized (mPackages) {
23197                    if (mWeFroze) {
23198                        mFrozenPackages.remove(mPackageName);
23199                    }
23200
23201                    if (mChildren != null) {
23202                        for (PackageFreezer freezer : mChildren) {
23203                            freezer.close();
23204                        }
23205                    }
23206                }
23207            }
23208        }
23209    }
23210
23211    /**
23212     * Verify that given package is currently frozen.
23213     */
23214    private void checkPackageFrozen(String packageName) {
23215        synchronized (mPackages) {
23216            if (!mFrozenPackages.contains(packageName)) {
23217                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23218            }
23219        }
23220    }
23221
23222    @Override
23223    public int movePackage(final String packageName, final String volumeUuid) {
23224        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23225
23226        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
23227        final int moveId = mNextMoveId.getAndIncrement();
23228        mHandler.post(new Runnable() {
23229            @Override
23230            public void run() {
23231                try {
23232                    movePackageInternal(packageName, volumeUuid, moveId, user);
23233                } catch (PackageManagerException e) {
23234                    Slog.w(TAG, "Failed to move " + packageName, e);
23235                    mMoveCallbacks.notifyStatusChanged(moveId,
23236                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23237                }
23238            }
23239        });
23240        return moveId;
23241    }
23242
23243    private void movePackageInternal(final String packageName, final String volumeUuid,
23244            final int moveId, UserHandle user) throws PackageManagerException {
23245        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23246        final PackageManager pm = mContext.getPackageManager();
23247
23248        final boolean currentAsec;
23249        final String currentVolumeUuid;
23250        final File codeFile;
23251        final String installerPackageName;
23252        final String packageAbiOverride;
23253        final int appId;
23254        final String seinfo;
23255        final String label;
23256        final int targetSdkVersion;
23257        final PackageFreezer freezer;
23258        final int[] installedUserIds;
23259
23260        // reader
23261        synchronized (mPackages) {
23262            final PackageParser.Package pkg = mPackages.get(packageName);
23263            final PackageSetting ps = mSettings.mPackages.get(packageName);
23264            if (pkg == null || ps == null) {
23265                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23266            }
23267
23268            if (pkg.applicationInfo.isSystemApp()) {
23269                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23270                        "Cannot move system application");
23271            }
23272
23273            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23274            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23275                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23276            if (isInternalStorage && !allow3rdPartyOnInternal) {
23277                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23278                        "3rd party apps are not allowed on internal storage");
23279            }
23280
23281            if (pkg.applicationInfo.isExternalAsec()) {
23282                currentAsec = true;
23283                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23284            } else if (pkg.applicationInfo.isForwardLocked()) {
23285                currentAsec = true;
23286                currentVolumeUuid = "forward_locked";
23287            } else {
23288                currentAsec = false;
23289                currentVolumeUuid = ps.volumeUuid;
23290
23291                final File probe = new File(pkg.codePath);
23292                final File probeOat = new File(probe, "oat");
23293                if (!probe.isDirectory() || !probeOat.isDirectory()) {
23294                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23295                            "Move only supported for modern cluster style installs");
23296                }
23297            }
23298
23299            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23300                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23301                        "Package already moved to " + volumeUuid);
23302            }
23303            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23304                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23305                        "Device admin cannot be moved");
23306            }
23307
23308            if (mFrozenPackages.contains(packageName)) {
23309                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23310                        "Failed to move already frozen package");
23311            }
23312
23313            codeFile = new File(pkg.codePath);
23314            installerPackageName = ps.installerPackageName;
23315            packageAbiOverride = ps.cpuAbiOverrideString;
23316            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23317            seinfo = pkg.applicationInfo.seInfo;
23318            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23319            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23320            freezer = freezePackage(packageName, "movePackageInternal");
23321            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23322        }
23323
23324        final Bundle extras = new Bundle();
23325        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23326        extras.putString(Intent.EXTRA_TITLE, label);
23327        mMoveCallbacks.notifyCreated(moveId, extras);
23328
23329        int installFlags;
23330        final boolean moveCompleteApp;
23331        final File measurePath;
23332
23333        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23334            installFlags = INSTALL_INTERNAL;
23335            moveCompleteApp = !currentAsec;
23336            measurePath = Environment.getDataAppDirectory(volumeUuid);
23337        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23338            installFlags = INSTALL_EXTERNAL;
23339            moveCompleteApp = false;
23340            measurePath = storage.getPrimaryPhysicalVolume().getPath();
23341        } else {
23342            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23343            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23344                    || !volume.isMountedWritable()) {
23345                freezer.close();
23346                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23347                        "Move location not mounted private volume");
23348            }
23349
23350            Preconditions.checkState(!currentAsec);
23351
23352            installFlags = INSTALL_INTERNAL;
23353            moveCompleteApp = true;
23354            measurePath = Environment.getDataAppDirectory(volumeUuid);
23355        }
23356
23357        final PackageStats stats = new PackageStats(null, -1);
23358        synchronized (mInstaller) {
23359            for (int userId : installedUserIds) {
23360                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23361                    freezer.close();
23362                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23363                            "Failed to measure package size");
23364                }
23365            }
23366        }
23367
23368        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23369                + stats.dataSize);
23370
23371        final long startFreeBytes = measurePath.getUsableSpace();
23372        final long sizeBytes;
23373        if (moveCompleteApp) {
23374            sizeBytes = stats.codeSize + stats.dataSize;
23375        } else {
23376            sizeBytes = stats.codeSize;
23377        }
23378
23379        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23380            freezer.close();
23381            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23382                    "Not enough free space to move");
23383        }
23384
23385        mMoveCallbacks.notifyStatusChanged(moveId, 10);
23386
23387        final CountDownLatch installedLatch = new CountDownLatch(1);
23388        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23389            @Override
23390            public void onUserActionRequired(Intent intent) throws RemoteException {
23391                throw new IllegalStateException();
23392            }
23393
23394            @Override
23395            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23396                    Bundle extras) throws RemoteException {
23397                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23398                        + PackageManager.installStatusToString(returnCode, msg));
23399
23400                installedLatch.countDown();
23401                freezer.close();
23402
23403                final int status = PackageManager.installStatusToPublicStatus(returnCode);
23404                switch (status) {
23405                    case PackageInstaller.STATUS_SUCCESS:
23406                        mMoveCallbacks.notifyStatusChanged(moveId,
23407                                PackageManager.MOVE_SUCCEEDED);
23408                        break;
23409                    case PackageInstaller.STATUS_FAILURE_STORAGE:
23410                        mMoveCallbacks.notifyStatusChanged(moveId,
23411                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23412                        break;
23413                    default:
23414                        mMoveCallbacks.notifyStatusChanged(moveId,
23415                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23416                        break;
23417                }
23418            }
23419        };
23420
23421        final MoveInfo move;
23422        if (moveCompleteApp) {
23423            // Kick off a thread to report progress estimates
23424            new Thread() {
23425                @Override
23426                public void run() {
23427                    while (true) {
23428                        try {
23429                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
23430                                break;
23431                            }
23432                        } catch (InterruptedException ignored) {
23433                        }
23434
23435                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23436                        final int progress = 10 + (int) MathUtils.constrain(
23437                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23438                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23439                    }
23440                }
23441            }.start();
23442
23443            final String dataAppName = codeFile.getName();
23444            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23445                    dataAppName, appId, seinfo, targetSdkVersion);
23446        } else {
23447            move = null;
23448        }
23449
23450        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23451
23452        final Message msg = mHandler.obtainMessage(INIT_COPY);
23453        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23454        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23455                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23456                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23457                PackageManager.INSTALL_REASON_UNKNOWN);
23458        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23459        msg.obj = params;
23460
23461        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23462                System.identityHashCode(msg.obj));
23463        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23464                System.identityHashCode(msg.obj));
23465
23466        mHandler.sendMessage(msg);
23467    }
23468
23469    @Override
23470    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23471        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23472
23473        final int realMoveId = mNextMoveId.getAndIncrement();
23474        final Bundle extras = new Bundle();
23475        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23476        mMoveCallbacks.notifyCreated(realMoveId, extras);
23477
23478        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23479            @Override
23480            public void onCreated(int moveId, Bundle extras) {
23481                // Ignored
23482            }
23483
23484            @Override
23485            public void onStatusChanged(int moveId, int status, long estMillis) {
23486                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23487            }
23488        };
23489
23490        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23491        storage.setPrimaryStorageUuid(volumeUuid, callback);
23492        return realMoveId;
23493    }
23494
23495    @Override
23496    public int getMoveStatus(int moveId) {
23497        mContext.enforceCallingOrSelfPermission(
23498                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23499        return mMoveCallbacks.mLastStatus.get(moveId);
23500    }
23501
23502    @Override
23503    public void registerMoveCallback(IPackageMoveObserver callback) {
23504        mContext.enforceCallingOrSelfPermission(
23505                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23506        mMoveCallbacks.register(callback);
23507    }
23508
23509    @Override
23510    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23511        mContext.enforceCallingOrSelfPermission(
23512                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23513        mMoveCallbacks.unregister(callback);
23514    }
23515
23516    @Override
23517    public boolean setInstallLocation(int loc) {
23518        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23519                null);
23520        if (getInstallLocation() == loc) {
23521            return true;
23522        }
23523        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23524                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23525            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23526                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23527            return true;
23528        }
23529        return false;
23530   }
23531
23532    @Override
23533    public int getInstallLocation() {
23534        // allow instant app access
23535        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23536                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23537                PackageHelper.APP_INSTALL_AUTO);
23538    }
23539
23540    /** Called by UserManagerService */
23541    void cleanUpUser(UserManagerService userManager, int userHandle) {
23542        synchronized (mPackages) {
23543            mDirtyUsers.remove(userHandle);
23544            mUserNeedsBadging.delete(userHandle);
23545            mSettings.removeUserLPw(userHandle);
23546            mPendingBroadcasts.remove(userHandle);
23547            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23548            removeUnusedPackagesLPw(userManager, userHandle);
23549        }
23550    }
23551
23552    /**
23553     * We're removing userHandle and would like to remove any downloaded packages
23554     * that are no longer in use by any other user.
23555     * @param userHandle the user being removed
23556     */
23557    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23558        final boolean DEBUG_CLEAN_APKS = false;
23559        int [] users = userManager.getUserIds();
23560        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23561        while (psit.hasNext()) {
23562            PackageSetting ps = psit.next();
23563            if (ps.pkg == null) {
23564                continue;
23565            }
23566            final String packageName = ps.pkg.packageName;
23567            // Skip over if system app
23568            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23569                continue;
23570            }
23571            if (DEBUG_CLEAN_APKS) {
23572                Slog.i(TAG, "Checking package " + packageName);
23573            }
23574            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23575            if (keep) {
23576                if (DEBUG_CLEAN_APKS) {
23577                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23578                }
23579            } else {
23580                for (int i = 0; i < users.length; i++) {
23581                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23582                        keep = true;
23583                        if (DEBUG_CLEAN_APKS) {
23584                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23585                                    + users[i]);
23586                        }
23587                        break;
23588                    }
23589                }
23590            }
23591            if (!keep) {
23592                if (DEBUG_CLEAN_APKS) {
23593                    Slog.i(TAG, "  Removing package " + packageName);
23594                }
23595                mHandler.post(new Runnable() {
23596                    public void run() {
23597                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23598                                userHandle, 0);
23599                    } //end run
23600                });
23601            }
23602        }
23603    }
23604
23605    /** Called by UserManagerService */
23606    void createNewUser(int userId, String[] disallowedPackages) {
23607        synchronized (mInstallLock) {
23608            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23609        }
23610        synchronized (mPackages) {
23611            scheduleWritePackageRestrictionsLocked(userId);
23612            scheduleWritePackageListLocked(userId);
23613            applyFactoryDefaultBrowserLPw(userId);
23614            primeDomainVerificationsLPw(userId);
23615        }
23616    }
23617
23618    void onNewUserCreated(final int userId) {
23619        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23620        // If permission review for legacy apps is required, we represent
23621        // dagerous permissions for such apps as always granted runtime
23622        // permissions to keep per user flag state whether review is needed.
23623        // Hence, if a new user is added we have to propagate dangerous
23624        // permission grants for these legacy apps.
23625        if (mPermissionReviewRequired) {
23626            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
23627                    | UPDATE_PERMISSIONS_REPLACE_ALL);
23628        }
23629    }
23630
23631    @Override
23632    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23633        mContext.enforceCallingOrSelfPermission(
23634                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23635                "Only package verification agents can read the verifier device identity");
23636
23637        synchronized (mPackages) {
23638            return mSettings.getVerifierDeviceIdentityLPw();
23639        }
23640    }
23641
23642    @Override
23643    public void setPermissionEnforced(String permission, boolean enforced) {
23644        // TODO: Now that we no longer change GID for storage, this should to away.
23645        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23646                "setPermissionEnforced");
23647        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23648            synchronized (mPackages) {
23649                if (mSettings.mReadExternalStorageEnforced == null
23650                        || mSettings.mReadExternalStorageEnforced != enforced) {
23651                    mSettings.mReadExternalStorageEnforced = enforced;
23652                    mSettings.writeLPr();
23653                }
23654            }
23655            // kill any non-foreground processes so we restart them and
23656            // grant/revoke the GID.
23657            final IActivityManager am = ActivityManager.getService();
23658            if (am != null) {
23659                final long token = Binder.clearCallingIdentity();
23660                try {
23661                    am.killProcessesBelowForeground("setPermissionEnforcement");
23662                } catch (RemoteException e) {
23663                } finally {
23664                    Binder.restoreCallingIdentity(token);
23665                }
23666            }
23667        } else {
23668            throw new IllegalArgumentException("No selective enforcement for " + permission);
23669        }
23670    }
23671
23672    @Override
23673    @Deprecated
23674    public boolean isPermissionEnforced(String permission) {
23675        // allow instant applications
23676        return true;
23677    }
23678
23679    @Override
23680    public boolean isStorageLow() {
23681        // allow instant applications
23682        final long token = Binder.clearCallingIdentity();
23683        try {
23684            final DeviceStorageMonitorInternal
23685                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23686            if (dsm != null) {
23687                return dsm.isMemoryLow();
23688            } else {
23689                return false;
23690            }
23691        } finally {
23692            Binder.restoreCallingIdentity(token);
23693        }
23694    }
23695
23696    @Override
23697    public IPackageInstaller getPackageInstaller() {
23698        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23699            return null;
23700        }
23701        return mInstallerService;
23702    }
23703
23704    private boolean userNeedsBadging(int userId) {
23705        int index = mUserNeedsBadging.indexOfKey(userId);
23706        if (index < 0) {
23707            final UserInfo userInfo;
23708            final long token = Binder.clearCallingIdentity();
23709            try {
23710                userInfo = sUserManager.getUserInfo(userId);
23711            } finally {
23712                Binder.restoreCallingIdentity(token);
23713            }
23714            final boolean b;
23715            if (userInfo != null && userInfo.isManagedProfile()) {
23716                b = true;
23717            } else {
23718                b = false;
23719            }
23720            mUserNeedsBadging.put(userId, b);
23721            return b;
23722        }
23723        return mUserNeedsBadging.valueAt(index);
23724    }
23725
23726    @Override
23727    public KeySet getKeySetByAlias(String packageName, String alias) {
23728        if (packageName == null || alias == null) {
23729            return null;
23730        }
23731        synchronized(mPackages) {
23732            final PackageParser.Package pkg = mPackages.get(packageName);
23733            if (pkg == null) {
23734                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23735                throw new IllegalArgumentException("Unknown package: " + packageName);
23736            }
23737            KeySetManagerService ksms = mSettings.mKeySetManagerService;
23738            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23739        }
23740    }
23741
23742    @Override
23743    public KeySet getSigningKeySet(String packageName) {
23744        if (packageName == null) {
23745            return null;
23746        }
23747        synchronized(mPackages) {
23748            final int callingUid = Binder.getCallingUid();
23749            final int callingUserId = UserHandle.getUserId(callingUid);
23750            final PackageParser.Package pkg = mPackages.get(packageName);
23751            if (pkg == null) {
23752                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23753                throw new IllegalArgumentException("Unknown package: " + packageName);
23754            }
23755            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23756            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23757                // filter and pretend the package doesn't exist
23758                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23759                        + ", uid:" + callingUid);
23760                throw new IllegalArgumentException("Unknown package: " + packageName);
23761            }
23762            if (pkg.applicationInfo.uid != callingUid
23763                    && Process.SYSTEM_UID != callingUid) {
23764                throw new SecurityException("May not access signing KeySet of other apps.");
23765            }
23766            KeySetManagerService ksms = mSettings.mKeySetManagerService;
23767            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23768        }
23769    }
23770
23771    @Override
23772    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23773        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23774            return false;
23775        }
23776        if (packageName == null || ks == null) {
23777            return false;
23778        }
23779        synchronized(mPackages) {
23780            final PackageParser.Package pkg = mPackages.get(packageName);
23781            if (pkg == null) {
23782                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23783                throw new IllegalArgumentException("Unknown package: " + packageName);
23784            }
23785            IBinder ksh = ks.getToken();
23786            if (ksh instanceof KeySetHandle) {
23787                KeySetManagerService ksms = mSettings.mKeySetManagerService;
23788                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23789            }
23790            return false;
23791        }
23792    }
23793
23794    @Override
23795    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23796        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23797            return false;
23798        }
23799        if (packageName == null || ks == null) {
23800            return false;
23801        }
23802        synchronized(mPackages) {
23803            final PackageParser.Package pkg = mPackages.get(packageName);
23804            if (pkg == null) {
23805                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23806                throw new IllegalArgumentException("Unknown package: " + packageName);
23807            }
23808            IBinder ksh = ks.getToken();
23809            if (ksh instanceof KeySetHandle) {
23810                KeySetManagerService ksms = mSettings.mKeySetManagerService;
23811                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23812            }
23813            return false;
23814        }
23815    }
23816
23817    private void deletePackageIfUnusedLPr(final String packageName) {
23818        PackageSetting ps = mSettings.mPackages.get(packageName);
23819        if (ps == null) {
23820            return;
23821        }
23822        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23823            // TODO Implement atomic delete if package is unused
23824            // It is currently possible that the package will be deleted even if it is installed
23825            // after this method returns.
23826            mHandler.post(new Runnable() {
23827                public void run() {
23828                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23829                            0, PackageManager.DELETE_ALL_USERS);
23830                }
23831            });
23832        }
23833    }
23834
23835    /**
23836     * Check and throw if the given before/after packages would be considered a
23837     * downgrade.
23838     */
23839    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23840            throws PackageManagerException {
23841        if (after.versionCode < before.mVersionCode) {
23842            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23843                    "Update version code " + after.versionCode + " is older than current "
23844                    + before.mVersionCode);
23845        } else if (after.versionCode == before.mVersionCode) {
23846            if (after.baseRevisionCode < before.baseRevisionCode) {
23847                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23848                        "Update base revision code " + after.baseRevisionCode
23849                        + " is older than current " + before.baseRevisionCode);
23850            }
23851
23852            if (!ArrayUtils.isEmpty(after.splitNames)) {
23853                for (int i = 0; i < after.splitNames.length; i++) {
23854                    final String splitName = after.splitNames[i];
23855                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23856                    if (j != -1) {
23857                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23858                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23859                                    "Update split " + splitName + " revision code "
23860                                    + after.splitRevisionCodes[i] + " is older than current "
23861                                    + before.splitRevisionCodes[j]);
23862                        }
23863                    }
23864                }
23865            }
23866        }
23867    }
23868
23869    private static class MoveCallbacks extends Handler {
23870        private static final int MSG_CREATED = 1;
23871        private static final int MSG_STATUS_CHANGED = 2;
23872
23873        private final RemoteCallbackList<IPackageMoveObserver>
23874                mCallbacks = new RemoteCallbackList<>();
23875
23876        private final SparseIntArray mLastStatus = new SparseIntArray();
23877
23878        public MoveCallbacks(Looper looper) {
23879            super(looper);
23880        }
23881
23882        public void register(IPackageMoveObserver callback) {
23883            mCallbacks.register(callback);
23884        }
23885
23886        public void unregister(IPackageMoveObserver callback) {
23887            mCallbacks.unregister(callback);
23888        }
23889
23890        @Override
23891        public void handleMessage(Message msg) {
23892            final SomeArgs args = (SomeArgs) msg.obj;
23893            final int n = mCallbacks.beginBroadcast();
23894            for (int i = 0; i < n; i++) {
23895                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23896                try {
23897                    invokeCallback(callback, msg.what, args);
23898                } catch (RemoteException ignored) {
23899                }
23900            }
23901            mCallbacks.finishBroadcast();
23902            args.recycle();
23903        }
23904
23905        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23906                throws RemoteException {
23907            switch (what) {
23908                case MSG_CREATED: {
23909                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23910                    break;
23911                }
23912                case MSG_STATUS_CHANGED: {
23913                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23914                    break;
23915                }
23916            }
23917        }
23918
23919        private void notifyCreated(int moveId, Bundle extras) {
23920            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23921
23922            final SomeArgs args = SomeArgs.obtain();
23923            args.argi1 = moveId;
23924            args.arg2 = extras;
23925            obtainMessage(MSG_CREATED, args).sendToTarget();
23926        }
23927
23928        private void notifyStatusChanged(int moveId, int status) {
23929            notifyStatusChanged(moveId, status, -1);
23930        }
23931
23932        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23933            Slog.v(TAG, "Move " + moveId + " status " + status);
23934
23935            final SomeArgs args = SomeArgs.obtain();
23936            args.argi1 = moveId;
23937            args.argi2 = status;
23938            args.arg3 = estMillis;
23939            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23940
23941            synchronized (mLastStatus) {
23942                mLastStatus.put(moveId, status);
23943            }
23944        }
23945    }
23946
23947    private final static class OnPermissionChangeListeners extends Handler {
23948        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23949
23950        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23951                new RemoteCallbackList<>();
23952
23953        public OnPermissionChangeListeners(Looper looper) {
23954            super(looper);
23955        }
23956
23957        @Override
23958        public void handleMessage(Message msg) {
23959            switch (msg.what) {
23960                case MSG_ON_PERMISSIONS_CHANGED: {
23961                    final int uid = msg.arg1;
23962                    handleOnPermissionsChanged(uid);
23963                } break;
23964            }
23965        }
23966
23967        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23968            mPermissionListeners.register(listener);
23969
23970        }
23971
23972        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23973            mPermissionListeners.unregister(listener);
23974        }
23975
23976        public void onPermissionsChanged(int uid) {
23977            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23978                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23979            }
23980        }
23981
23982        private void handleOnPermissionsChanged(int uid) {
23983            final int count = mPermissionListeners.beginBroadcast();
23984            try {
23985                for (int i = 0; i < count; i++) {
23986                    IOnPermissionsChangeListener callback = mPermissionListeners
23987                            .getBroadcastItem(i);
23988                    try {
23989                        callback.onPermissionsChanged(uid);
23990                    } catch (RemoteException e) {
23991                        Log.e(TAG, "Permission listener is dead", e);
23992                    }
23993                }
23994            } finally {
23995                mPermissionListeners.finishBroadcast();
23996            }
23997        }
23998    }
23999
24000    private class PackageManagerInternalImpl extends PackageManagerInternal {
24001        @Override
24002        public void setLocationPackagesProvider(PackagesProvider provider) {
24003            synchronized (mPackages) {
24004                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24005            }
24006        }
24007
24008        @Override
24009        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24010            synchronized (mPackages) {
24011                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24012            }
24013        }
24014
24015        @Override
24016        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24017            synchronized (mPackages) {
24018                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24019            }
24020        }
24021
24022        @Override
24023        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24024            synchronized (mPackages) {
24025                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24026            }
24027        }
24028
24029        @Override
24030        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24031            synchronized (mPackages) {
24032                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24033            }
24034        }
24035
24036        @Override
24037        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24038            synchronized (mPackages) {
24039                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24040            }
24041        }
24042
24043        @Override
24044        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24045            synchronized (mPackages) {
24046                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24047                        packageName, userId);
24048            }
24049        }
24050
24051        @Override
24052        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24053            synchronized (mPackages) {
24054                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24055                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24056                        packageName, userId);
24057            }
24058        }
24059
24060        @Override
24061        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24062            synchronized (mPackages) {
24063                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24064                        packageName, userId);
24065            }
24066        }
24067
24068        @Override
24069        public void setKeepUninstalledPackages(final List<String> packageList) {
24070            Preconditions.checkNotNull(packageList);
24071            List<String> removedFromList = null;
24072            synchronized (mPackages) {
24073                if (mKeepUninstalledPackages != null) {
24074                    final int packagesCount = mKeepUninstalledPackages.size();
24075                    for (int i = 0; i < packagesCount; i++) {
24076                        String oldPackage = mKeepUninstalledPackages.get(i);
24077                        if (packageList != null && packageList.contains(oldPackage)) {
24078                            continue;
24079                        }
24080                        if (removedFromList == null) {
24081                            removedFromList = new ArrayList<>();
24082                        }
24083                        removedFromList.add(oldPackage);
24084                    }
24085                }
24086                mKeepUninstalledPackages = new ArrayList<>(packageList);
24087                if (removedFromList != null) {
24088                    final int removedCount = removedFromList.size();
24089                    for (int i = 0; i < removedCount; i++) {
24090                        deletePackageIfUnusedLPr(removedFromList.get(i));
24091                    }
24092                }
24093            }
24094        }
24095
24096        @Override
24097        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24098            synchronized (mPackages) {
24099                // If we do not support permission review, done.
24100                if (!mPermissionReviewRequired) {
24101                    return false;
24102                }
24103
24104                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24105                if (packageSetting == null) {
24106                    return false;
24107                }
24108
24109                // Permission review applies only to apps not supporting the new permission model.
24110                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24111                    return false;
24112                }
24113
24114                // Legacy apps have the permission and get user consent on launch.
24115                PermissionsState permissionsState = packageSetting.getPermissionsState();
24116                return permissionsState.isPermissionReviewRequired(userId);
24117            }
24118        }
24119
24120        @Override
24121        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
24122            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
24123        }
24124
24125        @Override
24126        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24127                int userId) {
24128            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24129        }
24130
24131        @Override
24132        public void setDeviceAndProfileOwnerPackages(
24133                int deviceOwnerUserId, String deviceOwnerPackage,
24134                SparseArray<String> profileOwnerPackages) {
24135            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24136                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24137        }
24138
24139        @Override
24140        public boolean isPackageDataProtected(int userId, String packageName) {
24141            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24142        }
24143
24144        @Override
24145        public boolean isPackageEphemeral(int userId, String packageName) {
24146            synchronized (mPackages) {
24147                final PackageSetting ps = mSettings.mPackages.get(packageName);
24148                return ps != null ? ps.getInstantApp(userId) : false;
24149            }
24150        }
24151
24152        @Override
24153        public boolean wasPackageEverLaunched(String packageName, int userId) {
24154            synchronized (mPackages) {
24155                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24156            }
24157        }
24158
24159        @Override
24160        public void grantRuntimePermission(String packageName, String name, int userId,
24161                boolean overridePolicy) {
24162            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24163                    overridePolicy);
24164        }
24165
24166        @Override
24167        public void revokeRuntimePermission(String packageName, String name, int userId,
24168                boolean overridePolicy) {
24169            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24170                    overridePolicy);
24171        }
24172
24173        @Override
24174        public String getNameForUid(int uid) {
24175            return PackageManagerService.this.getNameForUid(uid);
24176        }
24177
24178        @Override
24179        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24180                Intent origIntent, String resolvedType, String callingPackage,
24181                Bundle verificationBundle, int userId) {
24182            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24183                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24184                    userId);
24185        }
24186
24187        @Override
24188        public void grantEphemeralAccess(int userId, Intent intent,
24189                int targetAppId, int ephemeralAppId) {
24190            synchronized (mPackages) {
24191                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24192                        targetAppId, ephemeralAppId);
24193            }
24194        }
24195
24196        @Override
24197        public boolean isInstantAppInstallerComponent(ComponentName component) {
24198            synchronized (mPackages) {
24199                return mInstantAppInstallerActivity != null
24200                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24201            }
24202        }
24203
24204        @Override
24205        public void pruneInstantApps() {
24206            synchronized (mPackages) {
24207                mInstantAppRegistry.pruneInstantAppsLPw();
24208            }
24209        }
24210
24211        @Override
24212        public String getSetupWizardPackageName() {
24213            return mSetupWizardPackage;
24214        }
24215
24216        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24217            if (policy != null) {
24218                mExternalSourcesPolicy = policy;
24219            }
24220        }
24221
24222        @Override
24223        public boolean isPackagePersistent(String packageName) {
24224            synchronized (mPackages) {
24225                PackageParser.Package pkg = mPackages.get(packageName);
24226                return pkg != null
24227                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24228                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24229                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24230                        : false;
24231            }
24232        }
24233
24234        @Override
24235        public List<PackageInfo> getOverlayPackages(int userId) {
24236            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24237            synchronized (mPackages) {
24238                for (PackageParser.Package p : mPackages.values()) {
24239                    if (p.mOverlayTarget != null) {
24240                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24241                        if (pkg != null) {
24242                            overlayPackages.add(pkg);
24243                        }
24244                    }
24245                }
24246            }
24247            return overlayPackages;
24248        }
24249
24250        @Override
24251        public List<String> getTargetPackageNames(int userId) {
24252            List<String> targetPackages = new ArrayList<>();
24253            synchronized (mPackages) {
24254                for (PackageParser.Package p : mPackages.values()) {
24255                    if (p.mOverlayTarget == null) {
24256                        targetPackages.add(p.packageName);
24257                    }
24258                }
24259            }
24260            return targetPackages;
24261        }
24262
24263        @Override
24264        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24265                @Nullable List<String> overlayPackageNames) {
24266            synchronized (mPackages) {
24267                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24268                    Slog.e(TAG, "failed to find package " + targetPackageName);
24269                    return false;
24270                }
24271
24272                ArrayList<String> paths = null;
24273                if (overlayPackageNames != null) {
24274                    final int N = overlayPackageNames.size();
24275                    paths = new ArrayList<>(N);
24276                    for (int i = 0; i < N; i++) {
24277                        final String packageName = overlayPackageNames.get(i);
24278                        final PackageParser.Package pkg = mPackages.get(packageName);
24279                        if (pkg == null) {
24280                            Slog.e(TAG, "failed to find package " + packageName);
24281                            return false;
24282                        }
24283                        paths.add(pkg.baseCodePath);
24284                    }
24285                }
24286
24287                ArrayMap<String, ArrayList<String>> userSpecificOverlays =
24288                    mEnabledOverlayPaths.get(userId);
24289                if (userSpecificOverlays == null) {
24290                    userSpecificOverlays = new ArrayMap<>();
24291                    mEnabledOverlayPaths.put(userId, userSpecificOverlays);
24292                }
24293
24294                if (paths != null && paths.size() > 0) {
24295                    userSpecificOverlays.put(targetPackageName, paths);
24296                } else {
24297                    userSpecificOverlays.remove(targetPackageName);
24298                }
24299                return true;
24300            }
24301        }
24302
24303        @Override
24304        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24305                int flags, int userId) {
24306            return resolveIntentInternal(
24307                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
24308        }
24309
24310        @Override
24311        public ResolveInfo resolveService(Intent intent, String resolvedType,
24312                int flags, int userId, int callingUid) {
24313            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24314        }
24315
24316        @Override
24317        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24318            synchronized (mPackages) {
24319                mIsolatedOwners.put(isolatedUid, ownerUid);
24320            }
24321        }
24322
24323        @Override
24324        public void removeIsolatedUid(int isolatedUid) {
24325            synchronized (mPackages) {
24326                mIsolatedOwners.delete(isolatedUid);
24327            }
24328        }
24329
24330        @Override
24331        public int getUidTargetSdkVersion(int uid) {
24332            synchronized (mPackages) {
24333                return getUidTargetSdkVersionLockedLPr(uid);
24334            }
24335        }
24336
24337        @Override
24338        public boolean canAccessInstantApps(int callingUid) {
24339            return PackageManagerService.this.canAccessInstantApps(callingUid);
24340        }
24341    }
24342
24343    @Override
24344    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24345        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24346        synchronized (mPackages) {
24347            final long identity = Binder.clearCallingIdentity();
24348            try {
24349                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
24350                        packageNames, userId);
24351            } finally {
24352                Binder.restoreCallingIdentity(identity);
24353            }
24354        }
24355    }
24356
24357    @Override
24358    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24359        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24360        synchronized (mPackages) {
24361            final long identity = Binder.clearCallingIdentity();
24362            try {
24363                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
24364                        packageNames, userId);
24365            } finally {
24366                Binder.restoreCallingIdentity(identity);
24367            }
24368        }
24369    }
24370
24371    private static void enforceSystemOrPhoneCaller(String tag) {
24372        int callingUid = Binder.getCallingUid();
24373        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24374            throw new SecurityException(
24375                    "Cannot call " + tag + " from UID " + callingUid);
24376        }
24377    }
24378
24379    boolean isHistoricalPackageUsageAvailable() {
24380        return mPackageUsage.isHistoricalPackageUsageAvailable();
24381    }
24382
24383    /**
24384     * Return a <b>copy</b> of the collection of packages known to the package manager.
24385     * @return A copy of the values of mPackages.
24386     */
24387    Collection<PackageParser.Package> getPackages() {
24388        synchronized (mPackages) {
24389            return new ArrayList<>(mPackages.values());
24390        }
24391    }
24392
24393    /**
24394     * Logs process start information (including base APK hash) to the security log.
24395     * @hide
24396     */
24397    @Override
24398    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24399            String apkFile, int pid) {
24400        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24401            return;
24402        }
24403        if (!SecurityLog.isLoggingEnabled()) {
24404            return;
24405        }
24406        Bundle data = new Bundle();
24407        data.putLong("startTimestamp", System.currentTimeMillis());
24408        data.putString("processName", processName);
24409        data.putInt("uid", uid);
24410        data.putString("seinfo", seinfo);
24411        data.putString("apkFile", apkFile);
24412        data.putInt("pid", pid);
24413        Message msg = mProcessLoggingHandler.obtainMessage(
24414                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24415        msg.setData(data);
24416        mProcessLoggingHandler.sendMessage(msg);
24417    }
24418
24419    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24420        return mCompilerStats.getPackageStats(pkgName);
24421    }
24422
24423    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24424        return getOrCreateCompilerPackageStats(pkg.packageName);
24425    }
24426
24427    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24428        return mCompilerStats.getOrCreatePackageStats(pkgName);
24429    }
24430
24431    public void deleteCompilerPackageStats(String pkgName) {
24432        mCompilerStats.deletePackageStats(pkgName);
24433    }
24434
24435    @Override
24436    public int getInstallReason(String packageName, int userId) {
24437        final int callingUid = Binder.getCallingUid();
24438        enforceCrossUserPermission(callingUid, userId,
24439                true /* requireFullPermission */, false /* checkShell */,
24440                "get install reason");
24441        synchronized (mPackages) {
24442            final PackageSetting ps = mSettings.mPackages.get(packageName);
24443            if (filterAppAccessLPr(ps, callingUid, userId)) {
24444                return PackageManager.INSTALL_REASON_UNKNOWN;
24445            }
24446            if (ps != null) {
24447                return ps.getInstallReason(userId);
24448            }
24449        }
24450        return PackageManager.INSTALL_REASON_UNKNOWN;
24451    }
24452
24453    @Override
24454    public boolean canRequestPackageInstalls(String packageName, int userId) {
24455        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24456            return false;
24457        }
24458        return canRequestPackageInstallsInternal(packageName, 0, userId,
24459                true /* throwIfPermNotDeclared*/);
24460    }
24461
24462    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24463            boolean throwIfPermNotDeclared) {
24464        int callingUid = Binder.getCallingUid();
24465        int uid = getPackageUid(packageName, 0, userId);
24466        if (callingUid != uid && callingUid != Process.ROOT_UID
24467                && callingUid != Process.SYSTEM_UID) {
24468            throw new SecurityException(
24469                    "Caller uid " + callingUid + " does not own package " + packageName);
24470        }
24471        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24472        if (info == null) {
24473            return false;
24474        }
24475        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24476            return false;
24477        }
24478        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24479        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24480        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24481            if (throwIfPermNotDeclared) {
24482                throw new SecurityException("Need to declare " + appOpPermission
24483                        + " to call this api");
24484            } else {
24485                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24486                return false;
24487            }
24488        }
24489        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24490            return false;
24491        }
24492        if (mExternalSourcesPolicy != null) {
24493            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24494            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24495                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24496            }
24497        }
24498        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24499    }
24500
24501    @Override
24502    public ComponentName getInstantAppResolverSettingsComponent() {
24503        return mInstantAppResolverSettingsComponent;
24504    }
24505
24506    @Override
24507    public ComponentName getInstantAppInstallerComponent() {
24508        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24509            return null;
24510        }
24511        return mInstantAppInstallerActivity == null
24512                ? null : mInstantAppInstallerActivity.getComponentName();
24513    }
24514
24515    @Override
24516    public String getInstantAppAndroidId(String packageName, int userId) {
24517        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24518                "getInstantAppAndroidId");
24519        enforceCrossUserPermission(Binder.getCallingUid(), userId,
24520                true /* requireFullPermission */, false /* checkShell */,
24521                "getInstantAppAndroidId");
24522        // Make sure the target is an Instant App.
24523        if (!isInstantApp(packageName, userId)) {
24524            return null;
24525        }
24526        synchronized (mPackages) {
24527            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24528        }
24529    }
24530}
24531
24532interface PackageSender {
24533    void sendPackageBroadcast(final String action, final String pkg,
24534        final Bundle extras, final int flags, final String targetPkg,
24535        final IIntentReceiver finishedReceiver, final int[] userIds);
24536    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
24537        int appId, int... userIds);
24538}
24539