PackageManagerService.java revision 7dd99e3d463eb2354e5ddb0cbeed1333ec590235
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.READ_EXTERNAL_STORAGE;
22import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
23import static android.Manifest.permission.REQUEST_INSTALL_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.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
101import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
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.ChangedPackages;
129import android.content.pm.ComponentInfo;
130import android.content.pm.InstantAppRequest;
131import android.content.pm.AuxiliaryResolveInfo;
132import android.content.pm.FallbackCategoryProvider;
133import android.content.pm.FeatureInfo;
134import android.content.pm.IOnPermissionsChangeListener;
135import android.content.pm.IPackageDataObserver;
136import android.content.pm.IPackageDeleteObserver;
137import android.content.pm.IPackageDeleteObserver2;
138import android.content.pm.IPackageInstallObserver2;
139import android.content.pm.IPackageInstaller;
140import android.content.pm.IPackageManager;
141import android.content.pm.IPackageMoveObserver;
142import android.content.pm.IPackageStatsObserver;
143import android.content.pm.InstantAppInfo;
144import android.content.pm.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
385    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
386    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
387    // user, but by default initialize to this.
388    public static final boolean DEBUG_DEXOPT = false;
389
390    private static final boolean DEBUG_ABI_SELECTION = false;
391    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
392    private static final boolean DEBUG_TRIAGED_MISSING = false;
393    private static final boolean DEBUG_APP_DATA = false;
394
395    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
396    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
397
398    private static final boolean HIDE_EPHEMERAL_APIS = false;
399
400    private static final boolean ENABLE_FREE_CACHE_V2 =
401            SystemProperties.getBoolean("fw.free_cache_v2", true);
402
403    private static final int RADIO_UID = Process.PHONE_UID;
404    private static final int LOG_UID = Process.LOG_UID;
405    private static final int NFC_UID = Process.NFC_UID;
406    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
407    private static final int SHELL_UID = Process.SHELL_UID;
408
409    // Cap the size of permission trees that 3rd party apps can define
410    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
411
412    // Suffix used during package installation when copying/moving
413    // package apks to install directory.
414    private static final String INSTALL_PACKAGE_SUFFIX = "-";
415
416    static final int SCAN_NO_DEX = 1<<1;
417    static final int SCAN_FORCE_DEX = 1<<2;
418    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
419    static final int SCAN_NEW_INSTALL = 1<<4;
420    static final int SCAN_UPDATE_TIME = 1<<5;
421    static final int SCAN_BOOTING = 1<<6;
422    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
423    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
424    static final int SCAN_REPLACING = 1<<9;
425    static final int SCAN_REQUIRE_KNOWN = 1<<10;
426    static final int SCAN_MOVE = 1<<11;
427    static final int SCAN_INITIAL = 1<<12;
428    static final int SCAN_CHECK_ONLY = 1<<13;
429    static final int SCAN_DONT_KILL_APP = 1<<14;
430    static final int SCAN_IGNORE_FROZEN = 1<<15;
431    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
432    static final int SCAN_AS_INSTANT_APP = 1<<17;
433    static final int SCAN_AS_FULL_APP = 1<<18;
434    /** Should not be with the scan flags */
435    static final int FLAGS_REMOVE_CHATTY = 1<<31;
436
437    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
438
439    private static final int[] EMPTY_INT_ARRAY = new int[0];
440
441    /**
442     * Timeout (in milliseconds) after which the watchdog should declare that
443     * our handler thread is wedged.  The usual default for such things is one
444     * minute but we sometimes do very lengthy I/O operations on this thread,
445     * such as installing multi-gigabyte applications, so ours needs to be longer.
446     */
447    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
448
449    /**
450     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
451     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
452     * settings entry if available, otherwise we use the hardcoded default.  If it's been
453     * more than this long since the last fstrim, we force one during the boot sequence.
454     *
455     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
456     * one gets run at the next available charging+idle time.  This final mandatory
457     * no-fstrim check kicks in only of the other scheduling criteria is never met.
458     */
459    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
460
461    /**
462     * Whether verification is enabled by default.
463     */
464    private static final boolean DEFAULT_VERIFY_ENABLE = true;
465
466    /**
467     * The default maximum time to wait for the verification agent to return in
468     * milliseconds.
469     */
470    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
471
472    /**
473     * The default response for package verification timeout.
474     *
475     * This can be either PackageManager.VERIFICATION_ALLOW or
476     * PackageManager.VERIFICATION_REJECT.
477     */
478    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
479
480    static final String PLATFORM_PACKAGE_NAME = "android";
481
482    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
483
484    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
485            DEFAULT_CONTAINER_PACKAGE,
486            "com.android.defcontainer.DefaultContainerService");
487
488    private static final String KILL_APP_REASON_GIDS_CHANGED =
489            "permission grant or revoke changed gids";
490
491    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
492            "permissions revoked";
493
494    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
495
496    private static final String PACKAGE_SCHEME = "package";
497
498    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
499
500    /** Permission grant: not grant the permission. */
501    private static final int GRANT_DENIED = 1;
502
503    /** Permission grant: grant the permission as an install permission. */
504    private static final int GRANT_INSTALL = 2;
505
506    /** Permission grant: grant the permission as a runtime one. */
507    private static final int GRANT_RUNTIME = 3;
508
509    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
510    private static final int GRANT_UPGRADE = 4;
511
512    /** Canonical intent used to identify what counts as a "web browser" app */
513    private static final Intent sBrowserIntent;
514    static {
515        sBrowserIntent = new Intent();
516        sBrowserIntent.setAction(Intent.ACTION_VIEW);
517        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
518        sBrowserIntent.setData(Uri.parse("http:"));
519    }
520
521    /**
522     * The set of all protected actions [i.e. those actions for which a high priority
523     * intent filter is disallowed].
524     */
525    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
526    static {
527        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
528        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
529        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
530        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
531    }
532
533    // Compilation reasons.
534    public static final int REASON_FIRST_BOOT = 0;
535    public static final int REASON_BOOT = 1;
536    public static final int REASON_INSTALL = 2;
537    public static final int REASON_BACKGROUND_DEXOPT = 3;
538    public static final int REASON_AB_OTA = 4;
539
540    public static final int REASON_LAST = REASON_AB_OTA;
541
542    /** All dangerous permission names in the same order as the events in MetricsEvent */
543    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
544            Manifest.permission.READ_CALENDAR,
545            Manifest.permission.WRITE_CALENDAR,
546            Manifest.permission.CAMERA,
547            Manifest.permission.READ_CONTACTS,
548            Manifest.permission.WRITE_CONTACTS,
549            Manifest.permission.GET_ACCOUNTS,
550            Manifest.permission.ACCESS_FINE_LOCATION,
551            Manifest.permission.ACCESS_COARSE_LOCATION,
552            Manifest.permission.RECORD_AUDIO,
553            Manifest.permission.READ_PHONE_STATE,
554            Manifest.permission.CALL_PHONE,
555            Manifest.permission.READ_CALL_LOG,
556            Manifest.permission.WRITE_CALL_LOG,
557            Manifest.permission.ADD_VOICEMAIL,
558            Manifest.permission.USE_SIP,
559            Manifest.permission.PROCESS_OUTGOING_CALLS,
560            Manifest.permission.READ_CELL_BROADCASTS,
561            Manifest.permission.BODY_SENSORS,
562            Manifest.permission.SEND_SMS,
563            Manifest.permission.RECEIVE_SMS,
564            Manifest.permission.READ_SMS,
565            Manifest.permission.RECEIVE_WAP_PUSH,
566            Manifest.permission.RECEIVE_MMS,
567            Manifest.permission.READ_EXTERNAL_STORAGE,
568            Manifest.permission.WRITE_EXTERNAL_STORAGE,
569            Manifest.permission.READ_PHONE_NUMBERS,
570            Manifest.permission.ANSWER_PHONE_CALLS);
571
572
573    /**
574     * Version number for the package parser cache. Increment this whenever the format or
575     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
576     */
577    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
578
579    /**
580     * Whether the package parser cache is enabled.
581     */
582    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
583
584    final ServiceThread mHandlerThread;
585
586    final PackageHandler mHandler;
587
588    private final ProcessLoggingHandler mProcessLoggingHandler;
589
590    /**
591     * Messages for {@link #mHandler} that need to wait for system ready before
592     * being dispatched.
593     */
594    private ArrayList<Message> mPostSystemReadyMessages;
595
596    final int mSdkVersion = Build.VERSION.SDK_INT;
597
598    final Context mContext;
599    final boolean mFactoryTest;
600    final boolean mOnlyCore;
601    final DisplayMetrics mMetrics;
602    final int mDefParseFlags;
603    final String[] mSeparateProcesses;
604    final boolean mIsUpgrade;
605    final boolean mIsPreNUpgrade;
606    final boolean mIsPreNMR1Upgrade;
607
608    // Have we told the Activity Manager to whitelist the default container service by uid yet?
609    @GuardedBy("mPackages")
610    boolean mDefaultContainerWhitelisted = false;
611
612    @GuardedBy("mPackages")
613    private boolean mDexOptDialogShown;
614
615    /** The location for ASEC container files on internal storage. */
616    final String mAsecInternalPath;
617
618    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
619    // LOCK HELD.  Can be called with mInstallLock held.
620    @GuardedBy("mInstallLock")
621    final Installer mInstaller;
622
623    /** Directory where installed third-party apps stored */
624    final File mAppInstallDir;
625
626    /**
627     * Directory to which applications installed internally have their
628     * 32 bit native libraries copied.
629     */
630    private File mAppLib32InstallDir;
631
632    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
633    // apps.
634    final File mDrmAppPrivateInstallDir;
635
636    // ----------------------------------------------------------------
637
638    // Lock for state used when installing and doing other long running
639    // operations.  Methods that must be called with this lock held have
640    // the suffix "LI".
641    final Object mInstallLock = new Object();
642
643    // ----------------------------------------------------------------
644
645    // Keys are String (package name), values are Package.  This also serves
646    // as the lock for the global state.  Methods that must be called with
647    // this lock held have the prefix "LP".
648    @GuardedBy("mPackages")
649    final ArrayMap<String, PackageParser.Package> mPackages =
650            new ArrayMap<String, PackageParser.Package>();
651
652    final ArrayMap<String, Set<String>> mKnownCodebase =
653            new ArrayMap<String, Set<String>>();
654
655    // Keys are isolated uids and values are the uid of the application
656    // that created the isolated proccess.
657    @GuardedBy("mPackages")
658    final SparseIntArray mIsolatedOwners = new SparseIntArray();
659
660    // List of APK paths to load for each user and package. This data is never
661    // persisted by the package manager. Instead, the overlay manager will
662    // ensure the data is up-to-date in runtime.
663    @GuardedBy("mPackages")
664    final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths =
665        new SparseArray<ArrayMap<String, ArrayList<String>>>();
666
667    /**
668     * Tracks new system packages [received in an OTA] that we expect to
669     * find updated user-installed versions. Keys are package name, values
670     * are package location.
671     */
672    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
673    /**
674     * Tracks high priority intent filters for protected actions. During boot, certain
675     * filter actions are protected and should never be allowed to have a high priority
676     * intent filter for them. However, there is one, and only one exception -- the
677     * setup wizard. It must be able to define a high priority intent filter for these
678     * actions to ensure there are no escapes from the wizard. We need to delay processing
679     * of these during boot as we need to look at all of the system packages in order
680     * to know which component is the setup wizard.
681     */
682    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
683    /**
684     * Whether or not processing protected filters should be deferred.
685     */
686    private boolean mDeferProtectedFilters = true;
687
688    /**
689     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
690     */
691    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
692    /**
693     * Whether or not system app permissions should be promoted from install to runtime.
694     */
695    boolean mPromoteSystemApps;
696
697    @GuardedBy("mPackages")
698    final Settings mSettings;
699
700    /**
701     * Set of package names that are currently "frozen", which means active
702     * surgery is being done on the code/data for that package. The platform
703     * will refuse to launch frozen packages to avoid race conditions.
704     *
705     * @see PackageFreezer
706     */
707    @GuardedBy("mPackages")
708    final ArraySet<String> mFrozenPackages = new ArraySet<>();
709
710    final ProtectedPackages mProtectedPackages;
711
712    boolean mFirstBoot;
713
714    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
715
716    // System configuration read by SystemConfig.
717    final int[] mGlobalGids;
718    final SparseArray<ArraySet<String>> mSystemPermissions;
719    @GuardedBy("mAvailableFeatures")
720    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
721
722    // If mac_permissions.xml was found for seinfo labeling.
723    boolean mFoundPolicyFile;
724
725    private final InstantAppRegistry mInstantAppRegistry;
726
727    @GuardedBy("mPackages")
728    int mChangedPackagesSequenceNumber;
729    /**
730     * List of changed [installed, removed or updated] packages.
731     * mapping from user id -> sequence number -> package name
732     */
733    @GuardedBy("mPackages")
734    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
735    /**
736     * The sequence number of the last change to a package.
737     * mapping from user id -> package name -> sequence number
738     */
739    @GuardedBy("mPackages")
740    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
741
742    class PackageParserCallback implements PackageParser.Callback {
743        @Override public final boolean hasFeature(String feature) {
744            return PackageManagerService.this.hasSystemFeature(feature, 0);
745        }
746
747        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
748                Collection<PackageParser.Package> allPackages, String targetPackageName) {
749            List<PackageParser.Package> overlayPackages = null;
750            for (PackageParser.Package p : allPackages) {
751                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
752                    if (overlayPackages == null) {
753                        overlayPackages = new ArrayList<PackageParser.Package>();
754                    }
755                    overlayPackages.add(p);
756                }
757            }
758            if (overlayPackages != null) {
759                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
760                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
761                        return p1.mOverlayPriority - p2.mOverlayPriority;
762                    }
763                };
764                Collections.sort(overlayPackages, cmp);
765            }
766            return overlayPackages;
767        }
768
769        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
770                String targetPackageName, String targetPath) {
771            if ("android".equals(targetPackageName)) {
772                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
773                // native AssetManager.
774                return null;
775            }
776            List<PackageParser.Package> overlayPackages =
777                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
778            if (overlayPackages == null || overlayPackages.isEmpty()) {
779                return null;
780            }
781            List<String> overlayPathList = null;
782            for (PackageParser.Package overlayPackage : overlayPackages) {
783                if (targetPath == null) {
784                    if (overlayPathList == null) {
785                        overlayPathList = new ArrayList<String>();
786                    }
787                    overlayPathList.add(overlayPackage.baseCodePath);
788                    continue;
789                }
790
791                try {
792                    // Creates idmaps for system to parse correctly the Android manifest of the
793                    // target package.
794                    //
795                    // OverlayManagerService will update each of them with a correct gid from its
796                    // target package app id.
797                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
798                            UserHandle.getSharedAppGid(
799                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
800                    if (overlayPathList == null) {
801                        overlayPathList = new ArrayList<String>();
802                    }
803                    overlayPathList.add(overlayPackage.baseCodePath);
804                } catch (InstallerException e) {
805                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
806                            overlayPackage.baseCodePath);
807                }
808            }
809            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
810        }
811
812        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
813            synchronized (mPackages) {
814                return getStaticOverlayPathsLocked(
815                        mPackages.values(), targetPackageName, targetPath);
816            }
817        }
818
819        @Override public final String[] getOverlayApks(String targetPackageName) {
820            return getStaticOverlayPaths(targetPackageName, null);
821        }
822
823        @Override public final String[] getOverlayPaths(String targetPackageName,
824                String targetPath) {
825            return getStaticOverlayPaths(targetPackageName, targetPath);
826        }
827    };
828
829    class ParallelPackageParserCallback extends PackageParserCallback {
830        List<PackageParser.Package> mOverlayPackages = null;
831
832        void findStaticOverlayPackages() {
833            synchronized (mPackages) {
834                for (PackageParser.Package p : mPackages.values()) {
835                    if (p.mIsStaticOverlay) {
836                        if (mOverlayPackages == null) {
837                            mOverlayPackages = new ArrayList<PackageParser.Package>();
838                        }
839                        mOverlayPackages.add(p);
840                    }
841                }
842            }
843        }
844
845        @Override
846        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
847            // We can trust mOverlayPackages without holding mPackages because package uninstall
848            // can't happen while running parallel parsing.
849            // Moreover holding mPackages on each parsing thread causes dead-lock.
850            return mOverlayPackages == null ? null :
851                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
852        }
853    }
854
855    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
856    final ParallelPackageParserCallback mParallelPackageParserCallback =
857            new ParallelPackageParserCallback();
858
859    public static final class SharedLibraryEntry {
860        public final String path;
861        public final String apk;
862        public final SharedLibraryInfo info;
863
864        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
865                String declaringPackageName, int declaringPackageVersionCode) {
866            path = _path;
867            apk = _apk;
868            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
869                    declaringPackageName, declaringPackageVersionCode), null);
870        }
871    }
872
873    // Currently known shared libraries.
874    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
875    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
876            new ArrayMap<>();
877
878    // All available activities, for your resolving pleasure.
879    final ActivityIntentResolver mActivities =
880            new ActivityIntentResolver();
881
882    // All available receivers, for your resolving pleasure.
883    final ActivityIntentResolver mReceivers =
884            new ActivityIntentResolver();
885
886    // All available services, for your resolving pleasure.
887    final ServiceIntentResolver mServices = new ServiceIntentResolver();
888
889    // All available providers, for your resolving pleasure.
890    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
891
892    // Mapping from provider base names (first directory in content URI codePath)
893    // to the provider information.
894    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
895            new ArrayMap<String, PackageParser.Provider>();
896
897    // Mapping from instrumentation class names to info about them.
898    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
899            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
900
901    // Mapping from permission names to info about them.
902    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
903            new ArrayMap<String, PackageParser.PermissionGroup>();
904
905    // Packages whose data we have transfered into another package, thus
906    // should no longer exist.
907    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
908
909    // Broadcast actions that are only available to the system.
910    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
911
912    /** List of packages waiting for verification. */
913    final SparseArray<PackageVerificationState> mPendingVerification
914            = new SparseArray<PackageVerificationState>();
915
916    /** Set of packages associated with each app op permission. */
917    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
918
919    final PackageInstallerService mInstallerService;
920
921    private final PackageDexOptimizer mPackageDexOptimizer;
922    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
923    // is used by other apps).
924    private final DexManager mDexManager;
925
926    private AtomicInteger mNextMoveId = new AtomicInteger();
927    private final MoveCallbacks mMoveCallbacks;
928
929    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
930
931    // Cache of users who need badging.
932    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
933
934    /** Token for keys in mPendingVerification. */
935    private int mPendingVerificationToken = 0;
936
937    volatile boolean mSystemReady;
938    volatile boolean mSafeMode;
939    volatile boolean mHasSystemUidErrors;
940    private volatile boolean mEphemeralAppsDisabled;
941
942    ApplicationInfo mAndroidApplication;
943    final ActivityInfo mResolveActivity = new ActivityInfo();
944    final ResolveInfo mResolveInfo = new ResolveInfo();
945    ComponentName mResolveComponentName;
946    PackageParser.Package mPlatformPackage;
947    ComponentName mCustomResolverComponentName;
948
949    boolean mResolverReplaced = false;
950
951    private final @Nullable ComponentName mIntentFilterVerifierComponent;
952    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
953
954    private int mIntentFilterVerificationToken = 0;
955
956    /** The service connection to the ephemeral resolver */
957    final EphemeralResolverConnection mInstantAppResolverConnection;
958    /** Component used to show resolver settings for Instant Apps */
959    final ComponentName mInstantAppResolverSettingsComponent;
960
961    /** Activity used to install instant applications */
962    ActivityInfo mInstantAppInstallerActivity;
963    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
964
965    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
966            = new SparseArray<IntentFilterVerificationState>();
967
968    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
969
970    // List of packages names to keep cached, even if they are uninstalled for all users
971    private List<String> mKeepUninstalledPackages;
972
973    private UserManagerInternal mUserManagerInternal;
974
975    private DeviceIdleController.LocalService mDeviceIdleController;
976
977    private File mCacheDir;
978
979    private ArraySet<String> mPrivappPermissionsViolations;
980
981    private Future<?> mPrepareAppDataFuture;
982
983    private static class IFVerificationParams {
984        PackageParser.Package pkg;
985        boolean replacing;
986        int userId;
987        int verifierUid;
988
989        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
990                int _userId, int _verifierUid) {
991            pkg = _pkg;
992            replacing = _replacing;
993            userId = _userId;
994            replacing = _replacing;
995            verifierUid = _verifierUid;
996        }
997    }
998
999    private interface IntentFilterVerifier<T extends IntentFilter> {
1000        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1001                                               T filter, String packageName);
1002        void startVerifications(int userId);
1003        void receiveVerificationResponse(int verificationId);
1004    }
1005
1006    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1007        private Context mContext;
1008        private ComponentName mIntentFilterVerifierComponent;
1009        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1010
1011        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1012            mContext = context;
1013            mIntentFilterVerifierComponent = verifierComponent;
1014        }
1015
1016        private String getDefaultScheme() {
1017            return IntentFilter.SCHEME_HTTPS;
1018        }
1019
1020        @Override
1021        public void startVerifications(int userId) {
1022            // Launch verifications requests
1023            int count = mCurrentIntentFilterVerifications.size();
1024            for (int n=0; n<count; n++) {
1025                int verificationId = mCurrentIntentFilterVerifications.get(n);
1026                final IntentFilterVerificationState ivs =
1027                        mIntentFilterVerificationStates.get(verificationId);
1028
1029                String packageName = ivs.getPackageName();
1030
1031                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1032                final int filterCount = filters.size();
1033                ArraySet<String> domainsSet = new ArraySet<>();
1034                for (int m=0; m<filterCount; m++) {
1035                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1036                    domainsSet.addAll(filter.getHostsList());
1037                }
1038                synchronized (mPackages) {
1039                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1040                            packageName, domainsSet) != null) {
1041                        scheduleWriteSettingsLocked();
1042                    }
1043                }
1044                sendVerificationRequest(userId, verificationId, ivs);
1045            }
1046            mCurrentIntentFilterVerifications.clear();
1047        }
1048
1049        private void sendVerificationRequest(int userId, int verificationId,
1050                IntentFilterVerificationState ivs) {
1051
1052            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1053            verificationIntent.putExtra(
1054                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1055                    verificationId);
1056            verificationIntent.putExtra(
1057                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1058                    getDefaultScheme());
1059            verificationIntent.putExtra(
1060                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1061                    ivs.getHostsString());
1062            verificationIntent.putExtra(
1063                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1064                    ivs.getPackageName());
1065            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1066            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1067
1068            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1069            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1070                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1071                    userId, false, "intent filter verifier");
1072
1073            UserHandle user = new UserHandle(userId);
1074            mContext.sendBroadcastAsUser(verificationIntent, user);
1075            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1076                    "Sending IntentFilter verification broadcast");
1077        }
1078
1079        public void receiveVerificationResponse(int verificationId) {
1080            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1081
1082            final boolean verified = ivs.isVerified();
1083
1084            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1085            final int count = filters.size();
1086            if (DEBUG_DOMAIN_VERIFICATION) {
1087                Slog.i(TAG, "Received verification response " + verificationId
1088                        + " for " + count + " filters, verified=" + verified);
1089            }
1090            for (int n=0; n<count; n++) {
1091                PackageParser.ActivityIntentInfo filter = filters.get(n);
1092                filter.setVerified(verified);
1093
1094                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1095                        + " verified with result:" + verified + " and hosts:"
1096                        + ivs.getHostsString());
1097            }
1098
1099            mIntentFilterVerificationStates.remove(verificationId);
1100
1101            final String packageName = ivs.getPackageName();
1102            IntentFilterVerificationInfo ivi = null;
1103
1104            synchronized (mPackages) {
1105                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1106            }
1107            if (ivi == null) {
1108                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1109                        + verificationId + " packageName:" + packageName);
1110                return;
1111            }
1112            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1113                    "Updating IntentFilterVerificationInfo for package " + packageName
1114                            +" verificationId:" + verificationId);
1115
1116            synchronized (mPackages) {
1117                if (verified) {
1118                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1119                } else {
1120                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1121                }
1122                scheduleWriteSettingsLocked();
1123
1124                final int userId = ivs.getUserId();
1125                if (userId != UserHandle.USER_ALL) {
1126                    final int userStatus =
1127                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1128
1129                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1130                    boolean needUpdate = false;
1131
1132                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1133                    // already been set by the User thru the Disambiguation dialog
1134                    switch (userStatus) {
1135                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1136                            if (verified) {
1137                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1138                            } else {
1139                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1140                            }
1141                            needUpdate = true;
1142                            break;
1143
1144                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1145                            if (verified) {
1146                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1147                                needUpdate = true;
1148                            }
1149                            break;
1150
1151                        default:
1152                            // Nothing to do
1153                    }
1154
1155                    if (needUpdate) {
1156                        mSettings.updateIntentFilterVerificationStatusLPw(
1157                                packageName, updatedStatus, userId);
1158                        scheduleWritePackageRestrictionsLocked(userId);
1159                    }
1160                }
1161            }
1162        }
1163
1164        @Override
1165        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1166                    ActivityIntentInfo filter, String packageName) {
1167            if (!hasValidDomains(filter)) {
1168                return false;
1169            }
1170            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1171            if (ivs == null) {
1172                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1173                        packageName);
1174            }
1175            if (DEBUG_DOMAIN_VERIFICATION) {
1176                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1177            }
1178            ivs.addFilter(filter);
1179            return true;
1180        }
1181
1182        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1183                int userId, int verificationId, String packageName) {
1184            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1185                    verifierUid, userId, packageName);
1186            ivs.setPendingState();
1187            synchronized (mPackages) {
1188                mIntentFilterVerificationStates.append(verificationId, ivs);
1189                mCurrentIntentFilterVerifications.add(verificationId);
1190            }
1191            return ivs;
1192        }
1193    }
1194
1195    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1196        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1197                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1198                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1199    }
1200
1201    // Set of pending broadcasts for aggregating enable/disable of components.
1202    static class PendingPackageBroadcasts {
1203        // for each user id, a map of <package name -> components within that package>
1204        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1205
1206        public PendingPackageBroadcasts() {
1207            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1208        }
1209
1210        public ArrayList<String> get(int userId, String packageName) {
1211            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1212            return packages.get(packageName);
1213        }
1214
1215        public void put(int userId, String packageName, ArrayList<String> components) {
1216            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1217            packages.put(packageName, components);
1218        }
1219
1220        public void remove(int userId, String packageName) {
1221            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1222            if (packages != null) {
1223                packages.remove(packageName);
1224            }
1225        }
1226
1227        public void remove(int userId) {
1228            mUidMap.remove(userId);
1229        }
1230
1231        public int userIdCount() {
1232            return mUidMap.size();
1233        }
1234
1235        public int userIdAt(int n) {
1236            return mUidMap.keyAt(n);
1237        }
1238
1239        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1240            return mUidMap.get(userId);
1241        }
1242
1243        public int size() {
1244            // total number of pending broadcast entries across all userIds
1245            int num = 0;
1246            for (int i = 0; i< mUidMap.size(); i++) {
1247                num += mUidMap.valueAt(i).size();
1248            }
1249            return num;
1250        }
1251
1252        public void clear() {
1253            mUidMap.clear();
1254        }
1255
1256        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1257            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1258            if (map == null) {
1259                map = new ArrayMap<String, ArrayList<String>>();
1260                mUidMap.put(userId, map);
1261            }
1262            return map;
1263        }
1264    }
1265    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1266
1267    // Service Connection to remote media container service to copy
1268    // package uri's from external media onto secure containers
1269    // or internal storage.
1270    private IMediaContainerService mContainerService = null;
1271
1272    static final int SEND_PENDING_BROADCAST = 1;
1273    static final int MCS_BOUND = 3;
1274    static final int END_COPY = 4;
1275    static final int INIT_COPY = 5;
1276    static final int MCS_UNBIND = 6;
1277    static final int START_CLEANING_PACKAGE = 7;
1278    static final int FIND_INSTALL_LOC = 8;
1279    static final int POST_INSTALL = 9;
1280    static final int MCS_RECONNECT = 10;
1281    static final int MCS_GIVE_UP = 11;
1282    static final int UPDATED_MEDIA_STATUS = 12;
1283    static final int WRITE_SETTINGS = 13;
1284    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1285    static final int PACKAGE_VERIFIED = 15;
1286    static final int CHECK_PENDING_VERIFICATION = 16;
1287    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1288    static final int INTENT_FILTER_VERIFIED = 18;
1289    static final int WRITE_PACKAGE_LIST = 19;
1290    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1291
1292    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1293
1294    // Delay time in millisecs
1295    static final int BROADCAST_DELAY = 10 * 1000;
1296
1297    static UserManagerService sUserManager;
1298
1299    // Stores a list of users whose package restrictions file needs to be updated
1300    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1301
1302    final private DefaultContainerConnection mDefContainerConn =
1303            new DefaultContainerConnection();
1304    class DefaultContainerConnection implements ServiceConnection {
1305        public void onServiceConnected(ComponentName name, IBinder service) {
1306            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1307            final IMediaContainerService imcs = IMediaContainerService.Stub
1308                    .asInterface(Binder.allowBlocking(service));
1309            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1310        }
1311
1312        public void onServiceDisconnected(ComponentName name) {
1313            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1314        }
1315    }
1316
1317    // Recordkeeping of restore-after-install operations that are currently in flight
1318    // between the Package Manager and the Backup Manager
1319    static class PostInstallData {
1320        public InstallArgs args;
1321        public PackageInstalledInfo res;
1322
1323        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1324            args = _a;
1325            res = _r;
1326        }
1327    }
1328
1329    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1330    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1331
1332    // XML tags for backup/restore of various bits of state
1333    private static final String TAG_PREFERRED_BACKUP = "pa";
1334    private static final String TAG_DEFAULT_APPS = "da";
1335    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1336
1337    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1338    private static final String TAG_ALL_GRANTS = "rt-grants";
1339    private static final String TAG_GRANT = "grant";
1340    private static final String ATTR_PACKAGE_NAME = "pkg";
1341
1342    private static final String TAG_PERMISSION = "perm";
1343    private static final String ATTR_PERMISSION_NAME = "name";
1344    private static final String ATTR_IS_GRANTED = "g";
1345    private static final String ATTR_USER_SET = "set";
1346    private static final String ATTR_USER_FIXED = "fixed";
1347    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1348
1349    // System/policy permission grants are not backed up
1350    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1351            FLAG_PERMISSION_POLICY_FIXED
1352            | FLAG_PERMISSION_SYSTEM_FIXED
1353            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1354
1355    // And we back up these user-adjusted states
1356    private static final int USER_RUNTIME_GRANT_MASK =
1357            FLAG_PERMISSION_USER_SET
1358            | FLAG_PERMISSION_USER_FIXED
1359            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1360
1361    final @Nullable String mRequiredVerifierPackage;
1362    final @NonNull String mRequiredInstallerPackage;
1363    final @NonNull String mRequiredUninstallerPackage;
1364    final @Nullable String mSetupWizardPackage;
1365    final @Nullable String mStorageManagerPackage;
1366    final @NonNull String mServicesSystemSharedLibraryPackageName;
1367    final @NonNull String mSharedSystemSharedLibraryPackageName;
1368
1369    final boolean mPermissionReviewRequired;
1370
1371    private final PackageUsage mPackageUsage = new PackageUsage();
1372    private final CompilerStats mCompilerStats = new CompilerStats();
1373
1374    class PackageHandler extends Handler {
1375        private boolean mBound = false;
1376        final ArrayList<HandlerParams> mPendingInstalls =
1377            new ArrayList<HandlerParams>();
1378
1379        private boolean connectToService() {
1380            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1381                    " DefaultContainerService");
1382            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1383            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1384            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1385                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1386                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1387                mBound = true;
1388                return true;
1389            }
1390            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1391            return false;
1392        }
1393
1394        private void disconnectService() {
1395            mContainerService = null;
1396            mBound = false;
1397            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1398            mContext.unbindService(mDefContainerConn);
1399            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1400        }
1401
1402        PackageHandler(Looper looper) {
1403            super(looper);
1404        }
1405
1406        public void handleMessage(Message msg) {
1407            try {
1408                doHandleMessage(msg);
1409            } finally {
1410                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1411            }
1412        }
1413
1414        void doHandleMessage(Message msg) {
1415            switch (msg.what) {
1416                case INIT_COPY: {
1417                    HandlerParams params = (HandlerParams) msg.obj;
1418                    int idx = mPendingInstalls.size();
1419                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1420                    // If a bind was already initiated we dont really
1421                    // need to do anything. The pending install
1422                    // will be processed later on.
1423                    if (!mBound) {
1424                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1425                                System.identityHashCode(mHandler));
1426                        // If this is the only one pending we might
1427                        // have to bind to the service again.
1428                        if (!connectToService()) {
1429                            Slog.e(TAG, "Failed to bind to media container service");
1430                            params.serviceError();
1431                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1432                                    System.identityHashCode(mHandler));
1433                            if (params.traceMethod != null) {
1434                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1435                                        params.traceCookie);
1436                            }
1437                            return;
1438                        } else {
1439                            // Once we bind to the service, the first
1440                            // pending request will be processed.
1441                            mPendingInstalls.add(idx, params);
1442                        }
1443                    } else {
1444                        mPendingInstalls.add(idx, params);
1445                        // Already bound to the service. Just make
1446                        // sure we trigger off processing the first request.
1447                        if (idx == 0) {
1448                            mHandler.sendEmptyMessage(MCS_BOUND);
1449                        }
1450                    }
1451                    break;
1452                }
1453                case MCS_BOUND: {
1454                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1455                    if (msg.obj != null) {
1456                        mContainerService = (IMediaContainerService) msg.obj;
1457                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1458                                System.identityHashCode(mHandler));
1459                    }
1460                    if (mContainerService == null) {
1461                        if (!mBound) {
1462                            // Something seriously wrong since we are not bound and we are not
1463                            // waiting for connection. Bail out.
1464                            Slog.e(TAG, "Cannot bind to media container service");
1465                            for (HandlerParams params : mPendingInstalls) {
1466                                // Indicate service bind error
1467                                params.serviceError();
1468                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1469                                        System.identityHashCode(params));
1470                                if (params.traceMethod != null) {
1471                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1472                                            params.traceMethod, params.traceCookie);
1473                                }
1474                                return;
1475                            }
1476                            mPendingInstalls.clear();
1477                        } else {
1478                            Slog.w(TAG, "Waiting to connect to media container service");
1479                        }
1480                    } else if (mPendingInstalls.size() > 0) {
1481                        HandlerParams params = mPendingInstalls.get(0);
1482                        if (params != null) {
1483                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1484                                    System.identityHashCode(params));
1485                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1486                            if (params.startCopy()) {
1487                                // We are done...  look for more work or to
1488                                // go idle.
1489                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1490                                        "Checking for more work or unbind...");
1491                                // Delete pending install
1492                                if (mPendingInstalls.size() > 0) {
1493                                    mPendingInstalls.remove(0);
1494                                }
1495                                if (mPendingInstalls.size() == 0) {
1496                                    if (mBound) {
1497                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1498                                                "Posting delayed MCS_UNBIND");
1499                                        removeMessages(MCS_UNBIND);
1500                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1501                                        // Unbind after a little delay, to avoid
1502                                        // continual thrashing.
1503                                        sendMessageDelayed(ubmsg, 10000);
1504                                    }
1505                                } else {
1506                                    // There are more pending requests in queue.
1507                                    // Just post MCS_BOUND message to trigger processing
1508                                    // of next pending install.
1509                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1510                                            "Posting MCS_BOUND for next work");
1511                                    mHandler.sendEmptyMessage(MCS_BOUND);
1512                                }
1513                            }
1514                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1515                        }
1516                    } else {
1517                        // Should never happen ideally.
1518                        Slog.w(TAG, "Empty queue");
1519                    }
1520                    break;
1521                }
1522                case MCS_RECONNECT: {
1523                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1524                    if (mPendingInstalls.size() > 0) {
1525                        if (mBound) {
1526                            disconnectService();
1527                        }
1528                        if (!connectToService()) {
1529                            Slog.e(TAG, "Failed to bind to media container service");
1530                            for (HandlerParams params : mPendingInstalls) {
1531                                // Indicate service bind error
1532                                params.serviceError();
1533                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1534                                        System.identityHashCode(params));
1535                            }
1536                            mPendingInstalls.clear();
1537                        }
1538                    }
1539                    break;
1540                }
1541                case MCS_UNBIND: {
1542                    // If there is no actual work left, then time to unbind.
1543                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1544
1545                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1546                        if (mBound) {
1547                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1548
1549                            disconnectService();
1550                        }
1551                    } else if (mPendingInstalls.size() > 0) {
1552                        // There are more pending requests in queue.
1553                        // Just post MCS_BOUND message to trigger processing
1554                        // of next pending install.
1555                        mHandler.sendEmptyMessage(MCS_BOUND);
1556                    }
1557
1558                    break;
1559                }
1560                case MCS_GIVE_UP: {
1561                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1562                    HandlerParams params = mPendingInstalls.remove(0);
1563                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1564                            System.identityHashCode(params));
1565                    break;
1566                }
1567                case SEND_PENDING_BROADCAST: {
1568                    String packages[];
1569                    ArrayList<String> components[];
1570                    int size = 0;
1571                    int uids[];
1572                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1573                    synchronized (mPackages) {
1574                        if (mPendingBroadcasts == null) {
1575                            return;
1576                        }
1577                        size = mPendingBroadcasts.size();
1578                        if (size <= 0) {
1579                            // Nothing to be done. Just return
1580                            return;
1581                        }
1582                        packages = new String[size];
1583                        components = new ArrayList[size];
1584                        uids = new int[size];
1585                        int i = 0;  // filling out the above arrays
1586
1587                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1588                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1589                            Iterator<Map.Entry<String, ArrayList<String>>> it
1590                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1591                                            .entrySet().iterator();
1592                            while (it.hasNext() && i < size) {
1593                                Map.Entry<String, ArrayList<String>> ent = it.next();
1594                                packages[i] = ent.getKey();
1595                                components[i] = ent.getValue();
1596                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1597                                uids[i] = (ps != null)
1598                                        ? UserHandle.getUid(packageUserId, ps.appId)
1599                                        : -1;
1600                                i++;
1601                            }
1602                        }
1603                        size = i;
1604                        mPendingBroadcasts.clear();
1605                    }
1606                    // Send broadcasts
1607                    for (int i = 0; i < size; i++) {
1608                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1609                    }
1610                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1611                    break;
1612                }
1613                case START_CLEANING_PACKAGE: {
1614                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1615                    final String packageName = (String)msg.obj;
1616                    final int userId = msg.arg1;
1617                    final boolean andCode = msg.arg2 != 0;
1618                    synchronized (mPackages) {
1619                        if (userId == UserHandle.USER_ALL) {
1620                            int[] users = sUserManager.getUserIds();
1621                            for (int user : users) {
1622                                mSettings.addPackageToCleanLPw(
1623                                        new PackageCleanItem(user, packageName, andCode));
1624                            }
1625                        } else {
1626                            mSettings.addPackageToCleanLPw(
1627                                    new PackageCleanItem(userId, packageName, andCode));
1628                        }
1629                    }
1630                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1631                    startCleaningPackages();
1632                } break;
1633                case POST_INSTALL: {
1634                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1635
1636                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1637                    final boolean didRestore = (msg.arg2 != 0);
1638                    mRunningInstalls.delete(msg.arg1);
1639
1640                    if (data != null) {
1641                        InstallArgs args = data.args;
1642                        PackageInstalledInfo parentRes = data.res;
1643
1644                        final boolean grantPermissions = (args.installFlags
1645                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1646                        final boolean killApp = (args.installFlags
1647                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1648                        final String[] grantedPermissions = args.installGrantPermissions;
1649
1650                        // Handle the parent package
1651                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1652                                grantedPermissions, didRestore, args.installerPackageName,
1653                                args.observer);
1654
1655                        // Handle the child packages
1656                        final int childCount = (parentRes.addedChildPackages != null)
1657                                ? parentRes.addedChildPackages.size() : 0;
1658                        for (int i = 0; i < childCount; i++) {
1659                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1660                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1661                                    grantedPermissions, false, args.installerPackageName,
1662                                    args.observer);
1663                        }
1664
1665                        // Log tracing if needed
1666                        if (args.traceMethod != null) {
1667                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1668                                    args.traceCookie);
1669                        }
1670                    } else {
1671                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1672                    }
1673
1674                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1675                } break;
1676                case UPDATED_MEDIA_STATUS: {
1677                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1678                    boolean reportStatus = msg.arg1 == 1;
1679                    boolean doGc = msg.arg2 == 1;
1680                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1681                    if (doGc) {
1682                        // Force a gc to clear up stale containers.
1683                        Runtime.getRuntime().gc();
1684                    }
1685                    if (msg.obj != null) {
1686                        @SuppressWarnings("unchecked")
1687                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1688                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1689                        // Unload containers
1690                        unloadAllContainers(args);
1691                    }
1692                    if (reportStatus) {
1693                        try {
1694                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1695                                    "Invoking StorageManagerService call back");
1696                            PackageHelper.getStorageManager().finishMediaUpdate();
1697                        } catch (RemoteException e) {
1698                            Log.e(TAG, "StorageManagerService not running?");
1699                        }
1700                    }
1701                } break;
1702                case WRITE_SETTINGS: {
1703                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1704                    synchronized (mPackages) {
1705                        removeMessages(WRITE_SETTINGS);
1706                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1707                        mSettings.writeLPr();
1708                        mDirtyUsers.clear();
1709                    }
1710                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1711                } break;
1712                case WRITE_PACKAGE_RESTRICTIONS: {
1713                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1714                    synchronized (mPackages) {
1715                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1716                        for (int userId : mDirtyUsers) {
1717                            mSettings.writePackageRestrictionsLPr(userId);
1718                        }
1719                        mDirtyUsers.clear();
1720                    }
1721                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1722                } break;
1723                case WRITE_PACKAGE_LIST: {
1724                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1725                    synchronized (mPackages) {
1726                        removeMessages(WRITE_PACKAGE_LIST);
1727                        mSettings.writePackageListLPr(msg.arg1);
1728                    }
1729                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1730                } break;
1731                case CHECK_PENDING_VERIFICATION: {
1732                    final int verificationId = msg.arg1;
1733                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1734
1735                    if ((state != null) && !state.timeoutExtended()) {
1736                        final InstallArgs args = state.getInstallArgs();
1737                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1738
1739                        Slog.i(TAG, "Verification timed out for " + originUri);
1740                        mPendingVerification.remove(verificationId);
1741
1742                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1743
1744                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1745                            Slog.i(TAG, "Continuing with installation of " + originUri);
1746                            state.setVerifierResponse(Binder.getCallingUid(),
1747                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1748                            broadcastPackageVerified(verificationId, originUri,
1749                                    PackageManager.VERIFICATION_ALLOW,
1750                                    state.getInstallArgs().getUser());
1751                            try {
1752                                ret = args.copyApk(mContainerService, true);
1753                            } catch (RemoteException e) {
1754                                Slog.e(TAG, "Could not contact the ContainerService");
1755                            }
1756                        } else {
1757                            broadcastPackageVerified(verificationId, originUri,
1758                                    PackageManager.VERIFICATION_REJECT,
1759                                    state.getInstallArgs().getUser());
1760                        }
1761
1762                        Trace.asyncTraceEnd(
1763                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1764
1765                        processPendingInstall(args, ret);
1766                        mHandler.sendEmptyMessage(MCS_UNBIND);
1767                    }
1768                    break;
1769                }
1770                case PACKAGE_VERIFIED: {
1771                    final int verificationId = msg.arg1;
1772
1773                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1774                    if (state == null) {
1775                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1776                        break;
1777                    }
1778
1779                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1780
1781                    state.setVerifierResponse(response.callerUid, response.code);
1782
1783                    if (state.isVerificationComplete()) {
1784                        mPendingVerification.remove(verificationId);
1785
1786                        final InstallArgs args = state.getInstallArgs();
1787                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1788
1789                        int ret;
1790                        if (state.isInstallAllowed()) {
1791                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1792                            broadcastPackageVerified(verificationId, originUri,
1793                                    response.code, state.getInstallArgs().getUser());
1794                            try {
1795                                ret = args.copyApk(mContainerService, true);
1796                            } catch (RemoteException e) {
1797                                Slog.e(TAG, "Could not contact the ContainerService");
1798                            }
1799                        } else {
1800                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1801                        }
1802
1803                        Trace.asyncTraceEnd(
1804                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1805
1806                        processPendingInstall(args, ret);
1807                        mHandler.sendEmptyMessage(MCS_UNBIND);
1808                    }
1809
1810                    break;
1811                }
1812                case START_INTENT_FILTER_VERIFICATIONS: {
1813                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1814                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1815                            params.replacing, params.pkg);
1816                    break;
1817                }
1818                case INTENT_FILTER_VERIFIED: {
1819                    final int verificationId = msg.arg1;
1820
1821                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1822                            verificationId);
1823                    if (state == null) {
1824                        Slog.w(TAG, "Invalid IntentFilter verification token "
1825                                + verificationId + " received");
1826                        break;
1827                    }
1828
1829                    final int userId = state.getUserId();
1830
1831                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1832                            "Processing IntentFilter verification with token:"
1833                            + verificationId + " and userId:" + userId);
1834
1835                    final IntentFilterVerificationResponse response =
1836                            (IntentFilterVerificationResponse) msg.obj;
1837
1838                    state.setVerifierResponse(response.callerUid, response.code);
1839
1840                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1841                            "IntentFilter verification with token:" + verificationId
1842                            + " and userId:" + userId
1843                            + " is settings verifier response with response code:"
1844                            + response.code);
1845
1846                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1847                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1848                                + response.getFailedDomainsString());
1849                    }
1850
1851                    if (state.isVerificationComplete()) {
1852                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1853                    } else {
1854                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1855                                "IntentFilter verification with token:" + verificationId
1856                                + " was not said to be complete");
1857                    }
1858
1859                    break;
1860                }
1861                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1862                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1863                            mInstantAppResolverConnection,
1864                            (InstantAppRequest) msg.obj,
1865                            mInstantAppInstallerActivity,
1866                            mHandler);
1867                }
1868            }
1869        }
1870    }
1871
1872    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1873            boolean killApp, String[] grantedPermissions,
1874            boolean launchedForRestore, String installerPackage,
1875            IPackageInstallObserver2 installObserver) {
1876        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1877            // Send the removed broadcasts
1878            if (res.removedInfo != null) {
1879                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1880            }
1881
1882            // Now that we successfully installed the package, grant runtime
1883            // permissions if requested before broadcasting the install. Also
1884            // for legacy apps in permission review mode we clear the permission
1885            // review flag which is used to emulate runtime permissions for
1886            // legacy apps.
1887            if (grantPermissions) {
1888                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1889            }
1890
1891            final boolean update = res.removedInfo != null
1892                    && res.removedInfo.removedPackage != null;
1893            final String origInstallerPackageName = res.removedInfo != null
1894                    ? res.removedInfo.installerPackageName : null;
1895
1896            // If this is the first time we have child packages for a disabled privileged
1897            // app that had no children, we grant requested runtime permissions to the new
1898            // children if the parent on the system image had them already granted.
1899            if (res.pkg.parentPackage != null) {
1900                synchronized (mPackages) {
1901                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1902                }
1903            }
1904
1905            synchronized (mPackages) {
1906                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1907            }
1908
1909            final String packageName = res.pkg.applicationInfo.packageName;
1910
1911            // Determine the set of users who are adding this package for
1912            // the first time vs. those who are seeing an update.
1913            int[] firstUsers = EMPTY_INT_ARRAY;
1914            int[] updateUsers = EMPTY_INT_ARRAY;
1915            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1916            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1917            for (int newUser : res.newUsers) {
1918                if (ps.getInstantApp(newUser)) {
1919                    continue;
1920                }
1921                if (allNewUsers) {
1922                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1923                    continue;
1924                }
1925                boolean isNew = true;
1926                for (int origUser : res.origUsers) {
1927                    if (origUser == newUser) {
1928                        isNew = false;
1929                        break;
1930                    }
1931                }
1932                if (isNew) {
1933                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1934                } else {
1935                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1936                }
1937            }
1938
1939            // Send installed broadcasts if the package is not a static shared lib.
1940            if (res.pkg.staticSharedLibName == null) {
1941                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1942
1943                // Send added for users that see the package for the first time
1944                // sendPackageAddedForNewUsers also deals with system apps
1945                int appId = UserHandle.getAppId(res.uid);
1946                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1947                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1948
1949                // Send added for users that don't see the package for the first time
1950                Bundle extras = new Bundle(1);
1951                extras.putInt(Intent.EXTRA_UID, res.uid);
1952                if (update) {
1953                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1954                }
1955                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1956                        extras, 0 /*flags*/,
1957                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1958                if (origInstallerPackageName != null) {
1959                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1960                            extras, 0 /*flags*/,
1961                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1962                }
1963
1964                // Send replaced for users that don't see the package for the first time
1965                if (update) {
1966                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1967                            packageName, extras, 0 /*flags*/,
1968                            null /*targetPackage*/, null /*finishedReceiver*/,
1969                            updateUsers);
1970                    if (origInstallerPackageName != null) {
1971                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1972                                extras, 0 /*flags*/,
1973                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1974                    }
1975                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1976                            null /*package*/, null /*extras*/, 0 /*flags*/,
1977                            packageName /*targetPackage*/,
1978                            null /*finishedReceiver*/, updateUsers);
1979                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1980                    // First-install and we did a restore, so we're responsible for the
1981                    // first-launch broadcast.
1982                    if (DEBUG_BACKUP) {
1983                        Slog.i(TAG, "Post-restore of " + packageName
1984                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1985                    }
1986                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1987                }
1988
1989                // Send broadcast package appeared if forward locked/external for all users
1990                // treat asec-hosted packages like removable media on upgrade
1991                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1992                    if (DEBUG_INSTALL) {
1993                        Slog.i(TAG, "upgrading pkg " + res.pkg
1994                                + " is ASEC-hosted -> AVAILABLE");
1995                    }
1996                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1997                    ArrayList<String> pkgList = new ArrayList<>(1);
1998                    pkgList.add(packageName);
1999                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2000                }
2001            }
2002
2003            // Work that needs to happen on first install within each user
2004            if (firstUsers != null && firstUsers.length > 0) {
2005                synchronized (mPackages) {
2006                    for (int userId : firstUsers) {
2007                        // If this app is a browser and it's newly-installed for some
2008                        // users, clear any default-browser state in those users. The
2009                        // app's nature doesn't depend on the user, so we can just check
2010                        // its browser nature in any user and generalize.
2011                        if (packageIsBrowser(packageName, userId)) {
2012                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2013                        }
2014
2015                        // We may also need to apply pending (restored) runtime
2016                        // permission grants within these users.
2017                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2018                    }
2019                }
2020            }
2021
2022            // Log current value of "unknown sources" setting
2023            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2024                    getUnknownSourcesSettings());
2025
2026            // Force a gc to clear up things
2027            Runtime.getRuntime().gc();
2028
2029            // Remove the replaced package's older resources safely now
2030            // We delete after a gc for applications  on sdcard.
2031            if (res.removedInfo != null && res.removedInfo.args != null) {
2032                synchronized (mInstallLock) {
2033                    res.removedInfo.args.doPostDeleteLI(true);
2034                }
2035            }
2036
2037            // Notify DexManager that the package was installed for new users.
2038            // The updated users should already be indexed and the package code paths
2039            // should not change.
2040            // Don't notify the manager for ephemeral apps as they are not expected to
2041            // survive long enough to benefit of background optimizations.
2042            for (int userId : firstUsers) {
2043                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2044                // There's a race currently where some install events may interleave with an uninstall.
2045                // This can lead to package info being null (b/36642664).
2046                if (info != null) {
2047                    mDexManager.notifyPackageInstalled(info, userId);
2048                }
2049            }
2050        }
2051
2052        // If someone is watching installs - notify them
2053        if (installObserver != null) {
2054            try {
2055                Bundle extras = extrasForInstallResult(res);
2056                installObserver.onPackageInstalled(res.name, res.returnCode,
2057                        res.returnMsg, extras);
2058            } catch (RemoteException e) {
2059                Slog.i(TAG, "Observer no longer exists.");
2060            }
2061        }
2062    }
2063
2064    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2065            PackageParser.Package pkg) {
2066        if (pkg.parentPackage == null) {
2067            return;
2068        }
2069        if (pkg.requestedPermissions == null) {
2070            return;
2071        }
2072        final PackageSetting disabledSysParentPs = mSettings
2073                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2074        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2075                || !disabledSysParentPs.isPrivileged()
2076                || (disabledSysParentPs.childPackageNames != null
2077                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2078            return;
2079        }
2080        final int[] allUserIds = sUserManager.getUserIds();
2081        final int permCount = pkg.requestedPermissions.size();
2082        for (int i = 0; i < permCount; i++) {
2083            String permission = pkg.requestedPermissions.get(i);
2084            BasePermission bp = mSettings.mPermissions.get(permission);
2085            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2086                continue;
2087            }
2088            for (int userId : allUserIds) {
2089                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2090                        permission, userId)) {
2091                    grantRuntimePermission(pkg.packageName, permission, userId);
2092                }
2093            }
2094        }
2095    }
2096
2097    private StorageEventListener mStorageListener = new StorageEventListener() {
2098        @Override
2099        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2100            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2101                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2102                    final String volumeUuid = vol.getFsUuid();
2103
2104                    // Clean up any users or apps that were removed or recreated
2105                    // while this volume was missing
2106                    sUserManager.reconcileUsers(volumeUuid);
2107                    reconcileApps(volumeUuid);
2108
2109                    // Clean up any install sessions that expired or were
2110                    // cancelled while this volume was missing
2111                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2112
2113                    loadPrivatePackages(vol);
2114
2115                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2116                    unloadPrivatePackages(vol);
2117                }
2118            }
2119
2120            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2121                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2122                    updateExternalMediaStatus(true, false);
2123                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2124                    updateExternalMediaStatus(false, false);
2125                }
2126            }
2127        }
2128
2129        @Override
2130        public void onVolumeForgotten(String fsUuid) {
2131            if (TextUtils.isEmpty(fsUuid)) {
2132                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2133                return;
2134            }
2135
2136            // Remove any apps installed on the forgotten volume
2137            synchronized (mPackages) {
2138                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2139                for (PackageSetting ps : packages) {
2140                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2141                    deletePackageVersioned(new VersionedPackage(ps.name,
2142                            PackageManager.VERSION_CODE_HIGHEST),
2143                            new LegacyPackageDeleteObserver(null).getBinder(),
2144                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2145                    // Try very hard to release any references to this package
2146                    // so we don't risk the system server being killed due to
2147                    // open FDs
2148                    AttributeCache.instance().removePackage(ps.name);
2149                }
2150
2151                mSettings.onVolumeForgotten(fsUuid);
2152                mSettings.writeLPr();
2153            }
2154        }
2155    };
2156
2157    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2158            String[] grantedPermissions) {
2159        for (int userId : userIds) {
2160            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2161        }
2162    }
2163
2164    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2165            String[] grantedPermissions) {
2166        SettingBase sb = (SettingBase) pkg.mExtras;
2167        if (sb == null) {
2168            return;
2169        }
2170
2171        PermissionsState permissionsState = sb.getPermissionsState();
2172
2173        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2174                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2175
2176        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2177                >= Build.VERSION_CODES.M;
2178
2179        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2180
2181        for (String permission : pkg.requestedPermissions) {
2182            final BasePermission bp;
2183            synchronized (mPackages) {
2184                bp = mSettings.mPermissions.get(permission);
2185            }
2186            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2187                    && (!instantApp || bp.isInstant())
2188                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2189                    && (grantedPermissions == null
2190                           || ArrayUtils.contains(grantedPermissions, permission))) {
2191                final int flags = permissionsState.getPermissionFlags(permission, userId);
2192                if (supportsRuntimePermissions) {
2193                    // Installer cannot change immutable permissions.
2194                    if ((flags & immutableFlags) == 0) {
2195                        grantRuntimePermission(pkg.packageName, permission, userId);
2196                    }
2197                } else if (mPermissionReviewRequired) {
2198                    // In permission review mode we clear the review flag when we
2199                    // are asked to install the app with all permissions granted.
2200                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2201                        updatePermissionFlags(permission, pkg.packageName,
2202                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2203                    }
2204                }
2205            }
2206        }
2207    }
2208
2209    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2210        Bundle extras = null;
2211        switch (res.returnCode) {
2212            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2213                extras = new Bundle();
2214                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2215                        res.origPermission);
2216                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2217                        res.origPackage);
2218                break;
2219            }
2220            case PackageManager.INSTALL_SUCCEEDED: {
2221                extras = new Bundle();
2222                extras.putBoolean(Intent.EXTRA_REPLACING,
2223                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2224                break;
2225            }
2226        }
2227        return extras;
2228    }
2229
2230    void scheduleWriteSettingsLocked() {
2231        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2232            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2233        }
2234    }
2235
2236    void scheduleWritePackageListLocked(int userId) {
2237        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2238            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2239            msg.arg1 = userId;
2240            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2241        }
2242    }
2243
2244    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2245        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2246        scheduleWritePackageRestrictionsLocked(userId);
2247    }
2248
2249    void scheduleWritePackageRestrictionsLocked(int userId) {
2250        final int[] userIds = (userId == UserHandle.USER_ALL)
2251                ? sUserManager.getUserIds() : new int[]{userId};
2252        for (int nextUserId : userIds) {
2253            if (!sUserManager.exists(nextUserId)) return;
2254            mDirtyUsers.add(nextUserId);
2255            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2256                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2257            }
2258        }
2259    }
2260
2261    public static PackageManagerService main(Context context, Installer installer,
2262            boolean factoryTest, boolean onlyCore) {
2263        // Self-check for initial settings.
2264        PackageManagerServiceCompilerMapping.checkProperties();
2265
2266        PackageManagerService m = new PackageManagerService(context, installer,
2267                factoryTest, onlyCore);
2268        m.enableSystemUserPackages();
2269        ServiceManager.addService("package", m);
2270        return m;
2271    }
2272
2273    private void enableSystemUserPackages() {
2274        if (!UserManager.isSplitSystemUser()) {
2275            return;
2276        }
2277        // For system user, enable apps based on the following conditions:
2278        // - app is whitelisted or belong to one of these groups:
2279        //   -- system app which has no launcher icons
2280        //   -- system app which has INTERACT_ACROSS_USERS permission
2281        //   -- system IME app
2282        // - app is not in the blacklist
2283        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2284        Set<String> enableApps = new ArraySet<>();
2285        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2286                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2287                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2288        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2289        enableApps.addAll(wlApps);
2290        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2291                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2292        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2293        enableApps.removeAll(blApps);
2294        Log.i(TAG, "Applications installed for system user: " + enableApps);
2295        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2296                UserHandle.SYSTEM);
2297        final int allAppsSize = allAps.size();
2298        synchronized (mPackages) {
2299            for (int i = 0; i < allAppsSize; i++) {
2300                String pName = allAps.get(i);
2301                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2302                // Should not happen, but we shouldn't be failing if it does
2303                if (pkgSetting == null) {
2304                    continue;
2305                }
2306                boolean install = enableApps.contains(pName);
2307                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2308                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2309                            + " for system user");
2310                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2311                }
2312            }
2313            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2314        }
2315    }
2316
2317    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2318        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2319                Context.DISPLAY_SERVICE);
2320        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2321    }
2322
2323    /**
2324     * Requests that files preopted on a secondary system partition be copied to the data partition
2325     * if possible.  Note that the actual copying of the files is accomplished by init for security
2326     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2327     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2328     */
2329    private static void requestCopyPreoptedFiles() {
2330        final int WAIT_TIME_MS = 100;
2331        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2332        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2333            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2334            // We will wait for up to 100 seconds.
2335            final long timeStart = SystemClock.uptimeMillis();
2336            final long timeEnd = timeStart + 100 * 1000;
2337            long timeNow = timeStart;
2338            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2339                try {
2340                    Thread.sleep(WAIT_TIME_MS);
2341                } catch (InterruptedException e) {
2342                    // Do nothing
2343                }
2344                timeNow = SystemClock.uptimeMillis();
2345                if (timeNow > timeEnd) {
2346                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2347                    Slog.wtf(TAG, "cppreopt did not finish!");
2348                    break;
2349                }
2350            }
2351
2352            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2353        }
2354    }
2355
2356    public PackageManagerService(Context context, Installer installer,
2357            boolean factoryTest, boolean onlyCore) {
2358        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2359        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2360        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2361                SystemClock.uptimeMillis());
2362
2363        if (mSdkVersion <= 0) {
2364            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2365        }
2366
2367        mContext = context;
2368
2369        mPermissionReviewRequired = context.getResources().getBoolean(
2370                R.bool.config_permissionReviewRequired);
2371
2372        mFactoryTest = factoryTest;
2373        mOnlyCore = onlyCore;
2374        mMetrics = new DisplayMetrics();
2375        mSettings = new Settings(mPackages);
2376        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2377                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2378        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2379                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2380        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2381                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2382        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2383                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2384        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2385                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2386        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2387                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2388
2389        String separateProcesses = SystemProperties.get("debug.separate_processes");
2390        if (separateProcesses != null && separateProcesses.length() > 0) {
2391            if ("*".equals(separateProcesses)) {
2392                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2393                mSeparateProcesses = null;
2394                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2395            } else {
2396                mDefParseFlags = 0;
2397                mSeparateProcesses = separateProcesses.split(",");
2398                Slog.w(TAG, "Running with debug.separate_processes: "
2399                        + separateProcesses);
2400            }
2401        } else {
2402            mDefParseFlags = 0;
2403            mSeparateProcesses = null;
2404        }
2405
2406        mInstaller = installer;
2407        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2408                "*dexopt*");
2409        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2410        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2411
2412        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2413                FgThread.get().getLooper());
2414
2415        getDefaultDisplayMetrics(context, mMetrics);
2416
2417        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2418        SystemConfig systemConfig = SystemConfig.getInstance();
2419        mGlobalGids = systemConfig.getGlobalGids();
2420        mSystemPermissions = systemConfig.getSystemPermissions();
2421        mAvailableFeatures = systemConfig.getAvailableFeatures();
2422        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2423
2424        mProtectedPackages = new ProtectedPackages(mContext);
2425
2426        synchronized (mInstallLock) {
2427        // writer
2428        synchronized (mPackages) {
2429            mHandlerThread = new ServiceThread(TAG,
2430                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2431            mHandlerThread.start();
2432            mHandler = new PackageHandler(mHandlerThread.getLooper());
2433            mProcessLoggingHandler = new ProcessLoggingHandler();
2434            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2435
2436            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2437            mInstantAppRegistry = new InstantAppRegistry(this);
2438
2439            File dataDir = Environment.getDataDirectory();
2440            mAppInstallDir = new File(dataDir, "app");
2441            mAppLib32InstallDir = new File(dataDir, "app-lib");
2442            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2443            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2444            sUserManager = new UserManagerService(context, this,
2445                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2446
2447            // Propagate permission configuration in to package manager.
2448            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2449                    = systemConfig.getPermissions();
2450            for (int i=0; i<permConfig.size(); i++) {
2451                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2452                BasePermission bp = mSettings.mPermissions.get(perm.name);
2453                if (bp == null) {
2454                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2455                    mSettings.mPermissions.put(perm.name, bp);
2456                }
2457                if (perm.gids != null) {
2458                    bp.setGids(perm.gids, perm.perUser);
2459                }
2460            }
2461
2462            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2463            final int builtInLibCount = libConfig.size();
2464            for (int i = 0; i < builtInLibCount; i++) {
2465                String name = libConfig.keyAt(i);
2466                String path = libConfig.valueAt(i);
2467                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2468                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2469            }
2470
2471            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2472
2473            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2474            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2475            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2476
2477            // Clean up orphaned packages for which the code path doesn't exist
2478            // and they are an update to a system app - caused by bug/32321269
2479            final int packageSettingCount = mSettings.mPackages.size();
2480            for (int i = packageSettingCount - 1; i >= 0; i--) {
2481                PackageSetting ps = mSettings.mPackages.valueAt(i);
2482                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2483                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2484                    mSettings.mPackages.removeAt(i);
2485                    mSettings.enableSystemPackageLPw(ps.name);
2486                }
2487            }
2488
2489            if (mFirstBoot) {
2490                requestCopyPreoptedFiles();
2491            }
2492
2493            String customResolverActivity = Resources.getSystem().getString(
2494                    R.string.config_customResolverActivity);
2495            if (TextUtils.isEmpty(customResolverActivity)) {
2496                customResolverActivity = null;
2497            } else {
2498                mCustomResolverComponentName = ComponentName.unflattenFromString(
2499                        customResolverActivity);
2500            }
2501
2502            long startTime = SystemClock.uptimeMillis();
2503
2504            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2505                    startTime);
2506
2507            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2508            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2509
2510            if (bootClassPath == null) {
2511                Slog.w(TAG, "No BOOTCLASSPATH found!");
2512            }
2513
2514            if (systemServerClassPath == null) {
2515                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2516            }
2517
2518            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2519
2520            final VersionInfo ver = mSettings.getInternalVersion();
2521            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2522            if (mIsUpgrade) {
2523                logCriticalInfo(Log.INFO,
2524                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2525            }
2526
2527            // when upgrading from pre-M, promote system app permissions from install to runtime
2528            mPromoteSystemApps =
2529                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2530
2531            // When upgrading from pre-N, we need to handle package extraction like first boot,
2532            // as there is no profiling data available.
2533            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2534
2535            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2536
2537            // save off the names of pre-existing system packages prior to scanning; we don't
2538            // want to automatically grant runtime permissions for new system apps
2539            if (mPromoteSystemApps) {
2540                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2541                while (pkgSettingIter.hasNext()) {
2542                    PackageSetting ps = pkgSettingIter.next();
2543                    if (isSystemApp(ps)) {
2544                        mExistingSystemPackages.add(ps.name);
2545                    }
2546                }
2547            }
2548
2549            mCacheDir = preparePackageParserCache(mIsUpgrade);
2550
2551            // Set flag to monitor and not change apk file paths when
2552            // scanning install directories.
2553            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2554
2555            if (mIsUpgrade || mFirstBoot) {
2556                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2557            }
2558
2559            // Collect vendor overlay packages. (Do this before scanning any apps.)
2560            // For security and version matching reason, only consider
2561            // overlay packages if they reside in the right directory.
2562            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2563                    | PackageParser.PARSE_IS_SYSTEM
2564                    | PackageParser.PARSE_IS_SYSTEM_DIR
2565                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2566
2567            mParallelPackageParserCallback.findStaticOverlayPackages();
2568
2569            // Find base frameworks (resource packages without code).
2570            scanDirTracedLI(frameworkDir, mDefParseFlags
2571                    | PackageParser.PARSE_IS_SYSTEM
2572                    | PackageParser.PARSE_IS_SYSTEM_DIR
2573                    | PackageParser.PARSE_IS_PRIVILEGED,
2574                    scanFlags | SCAN_NO_DEX, 0);
2575
2576            // Collected privileged system packages.
2577            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2578            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2579                    | PackageParser.PARSE_IS_SYSTEM
2580                    | PackageParser.PARSE_IS_SYSTEM_DIR
2581                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2582
2583            // Collect ordinary system packages.
2584            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2585            scanDirTracedLI(systemAppDir, mDefParseFlags
2586                    | PackageParser.PARSE_IS_SYSTEM
2587                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2588
2589            // Collect all vendor packages.
2590            File vendorAppDir = new File("/vendor/app");
2591            try {
2592                vendorAppDir = vendorAppDir.getCanonicalFile();
2593            } catch (IOException e) {
2594                // failed to look up canonical path, continue with original one
2595            }
2596            scanDirTracedLI(vendorAppDir, mDefParseFlags
2597                    | PackageParser.PARSE_IS_SYSTEM
2598                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2599
2600            // Collect all OEM packages.
2601            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2602            scanDirTracedLI(oemAppDir, mDefParseFlags
2603                    | PackageParser.PARSE_IS_SYSTEM
2604                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2605
2606            // Prune any system packages that no longer exist.
2607            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2608            if (!mOnlyCore) {
2609                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2610                while (psit.hasNext()) {
2611                    PackageSetting ps = psit.next();
2612
2613                    /*
2614                     * If this is not a system app, it can't be a
2615                     * disable system app.
2616                     */
2617                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2618                        continue;
2619                    }
2620
2621                    /*
2622                     * If the package is scanned, it's not erased.
2623                     */
2624                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2625                    if (scannedPkg != null) {
2626                        /*
2627                         * If the system app is both scanned and in the
2628                         * disabled packages list, then it must have been
2629                         * added via OTA. Remove it from the currently
2630                         * scanned package so the previously user-installed
2631                         * application can be scanned.
2632                         */
2633                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2634                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2635                                    + ps.name + "; removing system app.  Last known codePath="
2636                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2637                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2638                                    + scannedPkg.mVersionCode);
2639                            removePackageLI(scannedPkg, true);
2640                            mExpectingBetter.put(ps.name, ps.codePath);
2641                        }
2642
2643                        continue;
2644                    }
2645
2646                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2647                        psit.remove();
2648                        logCriticalInfo(Log.WARN, "System package " + ps.name
2649                                + " no longer exists; it's data will be wiped");
2650                        // Actual deletion of code and data will be handled by later
2651                        // reconciliation step
2652                    } else {
2653                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2654                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2655                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2656                        }
2657                    }
2658                }
2659            }
2660
2661            //look for any incomplete package installations
2662            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2663            for (int i = 0; i < deletePkgsList.size(); i++) {
2664                // Actual deletion of code and data will be handled by later
2665                // reconciliation step
2666                final String packageName = deletePkgsList.get(i).name;
2667                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2668                synchronized (mPackages) {
2669                    mSettings.removePackageLPw(packageName);
2670                }
2671            }
2672
2673            //delete tmp files
2674            deleteTempPackageFiles();
2675
2676            // Remove any shared userIDs that have no associated packages
2677            mSettings.pruneSharedUsersLPw();
2678
2679            if (!mOnlyCore) {
2680                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2681                        SystemClock.uptimeMillis());
2682                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2683
2684                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2685                        | PackageParser.PARSE_FORWARD_LOCK,
2686                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2687
2688                /**
2689                 * Remove disable package settings for any updated system
2690                 * apps that were removed via an OTA. If they're not a
2691                 * previously-updated app, remove them completely.
2692                 * Otherwise, just revoke their system-level permissions.
2693                 */
2694                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2695                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2696                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2697
2698                    String msg;
2699                    if (deletedPkg == null) {
2700                        msg = "Updated system package " + deletedAppName
2701                                + " no longer exists; it's data will be wiped";
2702                        // Actual deletion of code and data will be handled by later
2703                        // reconciliation step
2704                    } else {
2705                        msg = "Updated system app + " + deletedAppName
2706                                + " no longer present; removing system privileges for "
2707                                + deletedAppName;
2708
2709                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2710
2711                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2712                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2713                    }
2714                    logCriticalInfo(Log.WARN, msg);
2715                }
2716
2717                /**
2718                 * Make sure all system apps that we expected to appear on
2719                 * the userdata partition actually showed up. If they never
2720                 * appeared, crawl back and revive the system version.
2721                 */
2722                for (int i = 0; i < mExpectingBetter.size(); i++) {
2723                    final String packageName = mExpectingBetter.keyAt(i);
2724                    if (!mPackages.containsKey(packageName)) {
2725                        final File scanFile = mExpectingBetter.valueAt(i);
2726
2727                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2728                                + " but never showed up; reverting to system");
2729
2730                        int reparseFlags = mDefParseFlags;
2731                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2732                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2733                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2734                                    | PackageParser.PARSE_IS_PRIVILEGED;
2735                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2736                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2737                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2738                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2739                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2740                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2741                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2742                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2743                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2744                        } else {
2745                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2746                            continue;
2747                        }
2748
2749                        mSettings.enableSystemPackageLPw(packageName);
2750
2751                        try {
2752                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2753                        } catch (PackageManagerException e) {
2754                            Slog.e(TAG, "Failed to parse original system package: "
2755                                    + e.getMessage());
2756                        }
2757                    }
2758                }
2759            }
2760            mExpectingBetter.clear();
2761
2762            // Resolve the storage manager.
2763            mStorageManagerPackage = getStorageManagerPackageName();
2764
2765            // Resolve protected action filters. Only the setup wizard is allowed to
2766            // have a high priority filter for these actions.
2767            mSetupWizardPackage = getSetupWizardPackageName();
2768            if (mProtectedFilters.size() > 0) {
2769                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2770                    Slog.i(TAG, "No setup wizard;"
2771                        + " All protected intents capped to priority 0");
2772                }
2773                for (ActivityIntentInfo filter : mProtectedFilters) {
2774                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2775                        if (DEBUG_FILTERS) {
2776                            Slog.i(TAG, "Found setup wizard;"
2777                                + " allow priority " + filter.getPriority() + ";"
2778                                + " package: " + filter.activity.info.packageName
2779                                + " activity: " + filter.activity.className
2780                                + " priority: " + filter.getPriority());
2781                        }
2782                        // skip setup wizard; allow it to keep the high priority filter
2783                        continue;
2784                    }
2785                    Slog.w(TAG, "Protected action; cap priority to 0;"
2786                            + " package: " + filter.activity.info.packageName
2787                            + " activity: " + filter.activity.className
2788                            + " origPrio: " + filter.getPriority());
2789                    filter.setPriority(0);
2790                }
2791            }
2792            mDeferProtectedFilters = false;
2793            mProtectedFilters.clear();
2794
2795            // Now that we know all of the shared libraries, update all clients to have
2796            // the correct library paths.
2797            updateAllSharedLibrariesLPw(null);
2798
2799            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2800                // NOTE: We ignore potential failures here during a system scan (like
2801                // the rest of the commands above) because there's precious little we
2802                // can do about it. A settings error is reported, though.
2803                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2804            }
2805
2806            // Now that we know all the packages we are keeping,
2807            // read and update their last usage times.
2808            mPackageUsage.read(mPackages);
2809            mCompilerStats.read();
2810
2811            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2812                    SystemClock.uptimeMillis());
2813            Slog.i(TAG, "Time to scan packages: "
2814                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2815                    + " seconds");
2816
2817            // If the platform SDK has changed since the last time we booted,
2818            // we need to re-grant app permission to catch any new ones that
2819            // appear.  This is really a hack, and means that apps can in some
2820            // cases get permissions that the user didn't initially explicitly
2821            // allow...  it would be nice to have some better way to handle
2822            // this situation.
2823            int updateFlags = UPDATE_PERMISSIONS_ALL;
2824            if (ver.sdkVersion != mSdkVersion) {
2825                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2826                        + mSdkVersion + "; regranting permissions for internal storage");
2827                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2828            }
2829            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2830            ver.sdkVersion = mSdkVersion;
2831
2832            // If this is the first boot or an update from pre-M, and it is a normal
2833            // boot, then we need to initialize the default preferred apps across
2834            // all defined users.
2835            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2836                for (UserInfo user : sUserManager.getUsers(true)) {
2837                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2838                    applyFactoryDefaultBrowserLPw(user.id);
2839                    primeDomainVerificationsLPw(user.id);
2840                }
2841            }
2842
2843            // Prepare storage for system user really early during boot,
2844            // since core system apps like SettingsProvider and SystemUI
2845            // can't wait for user to start
2846            final int storageFlags;
2847            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2848                storageFlags = StorageManager.FLAG_STORAGE_DE;
2849            } else {
2850                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2851            }
2852            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2853                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2854                    true /* onlyCoreApps */);
2855            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2856                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2857                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2858                traceLog.traceBegin("AppDataFixup");
2859                try {
2860                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2861                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2862                } catch (InstallerException e) {
2863                    Slog.w(TAG, "Trouble fixing GIDs", e);
2864                }
2865                traceLog.traceEnd();
2866
2867                traceLog.traceBegin("AppDataPrepare");
2868                if (deferPackages == null || deferPackages.isEmpty()) {
2869                    return;
2870                }
2871                int count = 0;
2872                for (String pkgName : deferPackages) {
2873                    PackageParser.Package pkg = null;
2874                    synchronized (mPackages) {
2875                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2876                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2877                            pkg = ps.pkg;
2878                        }
2879                    }
2880                    if (pkg != null) {
2881                        synchronized (mInstallLock) {
2882                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2883                                    true /* maybeMigrateAppData */);
2884                        }
2885                        count++;
2886                    }
2887                }
2888                traceLog.traceEnd();
2889                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2890            }, "prepareAppData");
2891
2892            // If this is first boot after an OTA, and a normal boot, then
2893            // we need to clear code cache directories.
2894            // Note that we do *not* clear the application profiles. These remain valid
2895            // across OTAs and are used to drive profile verification (post OTA) and
2896            // profile compilation (without waiting to collect a fresh set of profiles).
2897            if (mIsUpgrade && !onlyCore) {
2898                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2899                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2900                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2901                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2902                        // No apps are running this early, so no need to freeze
2903                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2904                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2905                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2906                    }
2907                }
2908                ver.fingerprint = Build.FINGERPRINT;
2909            }
2910
2911            checkDefaultBrowser();
2912
2913            // clear only after permissions and other defaults have been updated
2914            mExistingSystemPackages.clear();
2915            mPromoteSystemApps = false;
2916
2917            // All the changes are done during package scanning.
2918            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2919
2920            // can downgrade to reader
2921            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2922            mSettings.writeLPr();
2923            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2924
2925            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2926                    SystemClock.uptimeMillis());
2927
2928            if (!mOnlyCore) {
2929                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2930                mRequiredInstallerPackage = getRequiredInstallerLPr();
2931                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2932                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2933                if (mIntentFilterVerifierComponent != null) {
2934                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2935                            mIntentFilterVerifierComponent);
2936                } else {
2937                    mIntentFilterVerifier = null;
2938                }
2939                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2940                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2941                        SharedLibraryInfo.VERSION_UNDEFINED);
2942                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2943                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2944                        SharedLibraryInfo.VERSION_UNDEFINED);
2945            } else {
2946                mRequiredVerifierPackage = null;
2947                mRequiredInstallerPackage = null;
2948                mRequiredUninstallerPackage = null;
2949                mIntentFilterVerifierComponent = null;
2950                mIntentFilterVerifier = null;
2951                mServicesSystemSharedLibraryPackageName = null;
2952                mSharedSystemSharedLibraryPackageName = null;
2953            }
2954
2955            mInstallerService = new PackageInstallerService(context, this);
2956            final Pair<ComponentName, String> instantAppResolverComponent =
2957                    getInstantAppResolverLPr();
2958            if (instantAppResolverComponent != null) {
2959                if (DEBUG_EPHEMERAL) {
2960                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2961                }
2962                mInstantAppResolverConnection = new EphemeralResolverConnection(
2963                        mContext, instantAppResolverComponent.first,
2964                        instantAppResolverComponent.second);
2965                mInstantAppResolverSettingsComponent =
2966                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2967            } else {
2968                mInstantAppResolverConnection = null;
2969                mInstantAppResolverSettingsComponent = null;
2970            }
2971            updateInstantAppInstallerLocked(null);
2972
2973            // Read and update the usage of dex files.
2974            // Do this at the end of PM init so that all the packages have their
2975            // data directory reconciled.
2976            // At this point we know the code paths of the packages, so we can validate
2977            // the disk file and build the internal cache.
2978            // The usage file is expected to be small so loading and verifying it
2979            // should take a fairly small time compare to the other activities (e.g. package
2980            // scanning).
2981            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2982            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2983            for (int userId : currentUserIds) {
2984                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2985            }
2986            mDexManager.load(userPackages);
2987        } // synchronized (mPackages)
2988        } // synchronized (mInstallLock)
2989
2990        // Now after opening every single application zip, make sure they
2991        // are all flushed.  Not really needed, but keeps things nice and
2992        // tidy.
2993        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2994        Runtime.getRuntime().gc();
2995        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2996
2997        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2998        FallbackCategoryProvider.loadFallbacks();
2999        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3000
3001        // The initial scanning above does many calls into installd while
3002        // holding the mPackages lock, but we're mostly interested in yelling
3003        // once we have a booted system.
3004        mInstaller.setWarnIfHeld(mPackages);
3005
3006        // Expose private service for system components to use.
3007        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3008        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3009    }
3010
3011    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3012        // we're only interested in updating the installer appliction when 1) it's not
3013        // already set or 2) the modified package is the installer
3014        if (mInstantAppInstallerActivity != null
3015                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3016                        .equals(modifiedPackage)) {
3017            return;
3018        }
3019        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3020    }
3021
3022    private static File preparePackageParserCache(boolean isUpgrade) {
3023        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3024            return null;
3025        }
3026
3027        // Disable package parsing on eng builds to allow for faster incremental development.
3028        if ("eng".equals(Build.TYPE)) {
3029            return null;
3030        }
3031
3032        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3033            Slog.i(TAG, "Disabling package parser cache due to system property.");
3034            return null;
3035        }
3036
3037        // The base directory for the package parser cache lives under /data/system/.
3038        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3039                "package_cache");
3040        if (cacheBaseDir == null) {
3041            return null;
3042        }
3043
3044        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3045        // This also serves to "GC" unused entries when the package cache version changes (which
3046        // can only happen during upgrades).
3047        if (isUpgrade) {
3048            FileUtils.deleteContents(cacheBaseDir);
3049        }
3050
3051
3052        // Return the versioned package cache directory. This is something like
3053        // "/data/system/package_cache/1"
3054        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3055
3056        // The following is a workaround to aid development on non-numbered userdebug
3057        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3058        // the system partition is newer.
3059        //
3060        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3061        // that starts with "eng." to signify that this is an engineering build and not
3062        // destined for release.
3063        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3064            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3065
3066            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3067            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3068            // in general and should not be used for production changes. In this specific case,
3069            // we know that they will work.
3070            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3071            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3072                FileUtils.deleteContents(cacheBaseDir);
3073                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3074            }
3075        }
3076
3077        return cacheDir;
3078    }
3079
3080    @Override
3081    public boolean isFirstBoot() {
3082        return mFirstBoot;
3083    }
3084
3085    @Override
3086    public boolean isOnlyCoreApps() {
3087        return mOnlyCore;
3088    }
3089
3090    @Override
3091    public boolean isUpgrade() {
3092        return mIsUpgrade;
3093    }
3094
3095    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3096        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3097
3098        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3099                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3100                UserHandle.USER_SYSTEM);
3101        if (matches.size() == 1) {
3102            return matches.get(0).getComponentInfo().packageName;
3103        } else if (matches.size() == 0) {
3104            Log.e(TAG, "There should probably be a verifier, but, none were found");
3105            return null;
3106        }
3107        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3108    }
3109
3110    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3111        synchronized (mPackages) {
3112            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3113            if (libraryEntry == null) {
3114                throw new IllegalStateException("Missing required shared library:" + name);
3115            }
3116            return libraryEntry.apk;
3117        }
3118    }
3119
3120    private @NonNull String getRequiredInstallerLPr() {
3121        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3122        intent.addCategory(Intent.CATEGORY_DEFAULT);
3123        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3124
3125        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3126                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3127                UserHandle.USER_SYSTEM);
3128        if (matches.size() == 1) {
3129            ResolveInfo resolveInfo = matches.get(0);
3130            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3131                throw new RuntimeException("The installer must be a privileged app");
3132            }
3133            return matches.get(0).getComponentInfo().packageName;
3134        } else {
3135            throw new RuntimeException("There must be exactly one installer; found " + matches);
3136        }
3137    }
3138
3139    private @NonNull String getRequiredUninstallerLPr() {
3140        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3141        intent.addCategory(Intent.CATEGORY_DEFAULT);
3142        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3143
3144        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3145                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3146                UserHandle.USER_SYSTEM);
3147        if (resolveInfo == null ||
3148                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3149            throw new RuntimeException("There must be exactly one uninstaller; found "
3150                    + resolveInfo);
3151        }
3152        return resolveInfo.getComponentInfo().packageName;
3153    }
3154
3155    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3156        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3157
3158        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3159                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3160                UserHandle.USER_SYSTEM);
3161        ResolveInfo best = null;
3162        final int N = matches.size();
3163        for (int i = 0; i < N; i++) {
3164            final ResolveInfo cur = matches.get(i);
3165            final String packageName = cur.getComponentInfo().packageName;
3166            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3167                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3168                continue;
3169            }
3170
3171            if (best == null || cur.priority > best.priority) {
3172                best = cur;
3173            }
3174        }
3175
3176        if (best != null) {
3177            return best.getComponentInfo().getComponentName();
3178        }
3179        Slog.w(TAG, "Intent filter verifier not found");
3180        return null;
3181    }
3182
3183    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3184        final String[] packageArray =
3185                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3186        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3187            if (DEBUG_EPHEMERAL) {
3188                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3189            }
3190            return null;
3191        }
3192
3193        final int callingUid = Binder.getCallingUid();
3194        final int resolveFlags =
3195                MATCH_DIRECT_BOOT_AWARE
3196                | MATCH_DIRECT_BOOT_UNAWARE
3197                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3198        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3199        final Intent resolverIntent = new Intent(actionName);
3200        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3201                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3202        // temporarily look for the old action
3203        if (resolvers.size() == 0) {
3204            if (DEBUG_EPHEMERAL) {
3205                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3206            }
3207            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3208            resolverIntent.setAction(actionName);
3209            resolvers = queryIntentServicesInternal(resolverIntent, null,
3210                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3211        }
3212        final int N = resolvers.size();
3213        if (N == 0) {
3214            if (DEBUG_EPHEMERAL) {
3215                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3216            }
3217            return null;
3218        }
3219
3220        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3221        for (int i = 0; i < N; i++) {
3222            final ResolveInfo info = resolvers.get(i);
3223
3224            if (info.serviceInfo == null) {
3225                continue;
3226            }
3227
3228            final String packageName = info.serviceInfo.packageName;
3229            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3230                if (DEBUG_EPHEMERAL) {
3231                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3232                            + " pkg: " + packageName + ", info:" + info);
3233                }
3234                continue;
3235            }
3236
3237            if (DEBUG_EPHEMERAL) {
3238                Slog.v(TAG, "Ephemeral resolver found;"
3239                        + " pkg: " + packageName + ", info:" + info);
3240            }
3241            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3242        }
3243        if (DEBUG_EPHEMERAL) {
3244            Slog.v(TAG, "Ephemeral resolver NOT found");
3245        }
3246        return null;
3247    }
3248
3249    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3250        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3251        intent.addCategory(Intent.CATEGORY_DEFAULT);
3252        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3253
3254        final int resolveFlags =
3255                MATCH_DIRECT_BOOT_AWARE
3256                | MATCH_DIRECT_BOOT_UNAWARE
3257                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3258        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3259                resolveFlags, UserHandle.USER_SYSTEM);
3260        // temporarily look for the old action
3261        if (matches.isEmpty()) {
3262            if (DEBUG_EPHEMERAL) {
3263                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3264            }
3265            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3266            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3267                    resolveFlags, UserHandle.USER_SYSTEM);
3268        }
3269        Iterator<ResolveInfo> iter = matches.iterator();
3270        while (iter.hasNext()) {
3271            final ResolveInfo rInfo = iter.next();
3272            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3273            if (ps != null) {
3274                final PermissionsState permissionsState = ps.getPermissionsState();
3275                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3276                    continue;
3277                }
3278            }
3279            iter.remove();
3280        }
3281        if (matches.size() == 0) {
3282            return null;
3283        } else if (matches.size() == 1) {
3284            return (ActivityInfo) matches.get(0).getComponentInfo();
3285        } else {
3286            throw new RuntimeException(
3287                    "There must be at most one ephemeral installer; found " + matches);
3288        }
3289    }
3290
3291    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3292            @NonNull ComponentName resolver) {
3293        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3294                .addCategory(Intent.CATEGORY_DEFAULT)
3295                .setPackage(resolver.getPackageName());
3296        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3297        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3298                UserHandle.USER_SYSTEM);
3299        // temporarily look for the old action
3300        if (matches.isEmpty()) {
3301            if (DEBUG_EPHEMERAL) {
3302                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3303            }
3304            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3305            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3306                    UserHandle.USER_SYSTEM);
3307        }
3308        if (matches.isEmpty()) {
3309            return null;
3310        }
3311        return matches.get(0).getComponentInfo().getComponentName();
3312    }
3313
3314    private void primeDomainVerificationsLPw(int userId) {
3315        if (DEBUG_DOMAIN_VERIFICATION) {
3316            Slog.d(TAG, "Priming domain verifications in user " + userId);
3317        }
3318
3319        SystemConfig systemConfig = SystemConfig.getInstance();
3320        ArraySet<String> packages = systemConfig.getLinkedApps();
3321
3322        for (String packageName : packages) {
3323            PackageParser.Package pkg = mPackages.get(packageName);
3324            if (pkg != null) {
3325                if (!pkg.isSystemApp()) {
3326                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3327                    continue;
3328                }
3329
3330                ArraySet<String> domains = null;
3331                for (PackageParser.Activity a : pkg.activities) {
3332                    for (ActivityIntentInfo filter : a.intents) {
3333                        if (hasValidDomains(filter)) {
3334                            if (domains == null) {
3335                                domains = new ArraySet<String>();
3336                            }
3337                            domains.addAll(filter.getHostsList());
3338                        }
3339                    }
3340                }
3341
3342                if (domains != null && domains.size() > 0) {
3343                    if (DEBUG_DOMAIN_VERIFICATION) {
3344                        Slog.v(TAG, "      + " + packageName);
3345                    }
3346                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3347                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3348                    // and then 'always' in the per-user state actually used for intent resolution.
3349                    final IntentFilterVerificationInfo ivi;
3350                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3351                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3352                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3353                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3354                } else {
3355                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3356                            + "' does not handle web links");
3357                }
3358            } else {
3359                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3360            }
3361        }
3362
3363        scheduleWritePackageRestrictionsLocked(userId);
3364        scheduleWriteSettingsLocked();
3365    }
3366
3367    private void applyFactoryDefaultBrowserLPw(int userId) {
3368        // The default browser app's package name is stored in a string resource,
3369        // with a product-specific overlay used for vendor customization.
3370        String browserPkg = mContext.getResources().getString(
3371                com.android.internal.R.string.default_browser);
3372        if (!TextUtils.isEmpty(browserPkg)) {
3373            // non-empty string => required to be a known package
3374            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3375            if (ps == null) {
3376                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3377                browserPkg = null;
3378            } else {
3379                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3380            }
3381        }
3382
3383        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3384        // default.  If there's more than one, just leave everything alone.
3385        if (browserPkg == null) {
3386            calculateDefaultBrowserLPw(userId);
3387        }
3388    }
3389
3390    private void calculateDefaultBrowserLPw(int userId) {
3391        List<String> allBrowsers = resolveAllBrowserApps(userId);
3392        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3393        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3394    }
3395
3396    private List<String> resolveAllBrowserApps(int userId) {
3397        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3398        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3399                PackageManager.MATCH_ALL, userId);
3400
3401        final int count = list.size();
3402        List<String> result = new ArrayList<String>(count);
3403        for (int i=0; i<count; i++) {
3404            ResolveInfo info = list.get(i);
3405            if (info.activityInfo == null
3406                    || !info.handleAllWebDataURI
3407                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3408                    || result.contains(info.activityInfo.packageName)) {
3409                continue;
3410            }
3411            result.add(info.activityInfo.packageName);
3412        }
3413
3414        return result;
3415    }
3416
3417    private boolean packageIsBrowser(String packageName, int userId) {
3418        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3419                PackageManager.MATCH_ALL, userId);
3420        final int N = list.size();
3421        for (int i = 0; i < N; i++) {
3422            ResolveInfo info = list.get(i);
3423            if (packageName.equals(info.activityInfo.packageName)) {
3424                return true;
3425            }
3426        }
3427        return false;
3428    }
3429
3430    private void checkDefaultBrowser() {
3431        final int myUserId = UserHandle.myUserId();
3432        final String packageName = getDefaultBrowserPackageName(myUserId);
3433        if (packageName != null) {
3434            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3435            if (info == null) {
3436                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3437                synchronized (mPackages) {
3438                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3439                }
3440            }
3441        }
3442    }
3443
3444    @Override
3445    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3446            throws RemoteException {
3447        try {
3448            return super.onTransact(code, data, reply, flags);
3449        } catch (RuntimeException e) {
3450            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3451                Slog.wtf(TAG, "Package Manager Crash", e);
3452            }
3453            throw e;
3454        }
3455    }
3456
3457    static int[] appendInts(int[] cur, int[] add) {
3458        if (add == null) return cur;
3459        if (cur == null) return add;
3460        final int N = add.length;
3461        for (int i=0; i<N; i++) {
3462            cur = appendInt(cur, add[i]);
3463        }
3464        return cur;
3465    }
3466
3467    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3468        if (!sUserManager.exists(userId)) return null;
3469        if (ps == null) {
3470            return null;
3471        }
3472        final PackageParser.Package p = ps.pkg;
3473        if (p == null) {
3474            return null;
3475        }
3476        // Filter out ephemeral app metadata:
3477        //   * The system/shell/root can see metadata for any app
3478        //   * An installed app can see metadata for 1) other installed apps
3479        //     and 2) ephemeral apps that have explicitly interacted with it
3480        //   * Ephemeral apps can only see their own data and exposed installed apps
3481        //   * Holding a signature permission allows seeing instant apps
3482        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3483        if (callingAppId != Process.SYSTEM_UID
3484                && callingAppId != Process.SHELL_UID
3485                && callingAppId != Process.ROOT_UID
3486                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3487                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3488            final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid());
3489            if (instantAppPackageName != null) {
3490                // ephemeral apps can only get information on themselves or
3491                // installed apps that are exposed.
3492                if (!instantAppPackageName.equals(p.packageName)
3493                        && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) {
3494                    return null;
3495                }
3496            } else {
3497                if (ps.getInstantApp(userId)) {
3498                    // only get access to the ephemeral app if we've been granted access
3499                    if (!mInstantAppRegistry.isInstantAccessGranted(
3500                            userId, callingAppId, ps.appId)) {
3501                        return null;
3502                    }
3503                }
3504            }
3505        }
3506
3507        final PermissionsState permissionsState = ps.getPermissionsState();
3508
3509        // Compute GIDs only if requested
3510        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3511                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3512        // Compute granted permissions only if package has requested permissions
3513        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3514                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3515        final PackageUserState state = ps.readUserState(userId);
3516
3517        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3518                && ps.isSystem()) {
3519            flags |= MATCH_ANY_USER;
3520        }
3521
3522        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3523                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3524
3525        if (packageInfo == null) {
3526            return null;
3527        }
3528
3529        rebaseEnabledOverlays(packageInfo.applicationInfo, userId);
3530
3531        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3532                resolveExternalPackageNameLPr(p);
3533
3534        return packageInfo;
3535    }
3536
3537    @Override
3538    public void checkPackageStartable(String packageName, int userId) {
3539        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3540
3541        synchronized (mPackages) {
3542            final PackageSetting ps = mSettings.mPackages.get(packageName);
3543            if (ps == null) {
3544                throw new SecurityException("Package " + packageName + " was not found!");
3545            }
3546
3547            if (!ps.getInstalled(userId)) {
3548                throw new SecurityException(
3549                        "Package " + packageName + " was not installed for user " + userId + "!");
3550            }
3551
3552            if (mSafeMode && !ps.isSystem()) {
3553                throw new SecurityException("Package " + packageName + " not a system app!");
3554            }
3555
3556            if (mFrozenPackages.contains(packageName)) {
3557                throw new SecurityException("Package " + packageName + " is currently frozen!");
3558            }
3559
3560            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3561                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3562                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3563            }
3564        }
3565    }
3566
3567    @Override
3568    public boolean isPackageAvailable(String packageName, int userId) {
3569        if (!sUserManager.exists(userId)) return false;
3570        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3571                false /* requireFullPermission */, false /* checkShell */, "is package available");
3572        synchronized (mPackages) {
3573            PackageParser.Package p = mPackages.get(packageName);
3574            if (p != null) {
3575                final PackageSetting ps = (PackageSetting) p.mExtras;
3576                if (ps != null) {
3577                    final PackageUserState state = ps.readUserState(userId);
3578                    if (state != null) {
3579                        return PackageParser.isAvailable(state);
3580                    }
3581                }
3582            }
3583        }
3584        return false;
3585    }
3586
3587    @Override
3588    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3589        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3590                flags, userId);
3591    }
3592
3593    @Override
3594    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3595            int flags, int userId) {
3596        return getPackageInfoInternal(versionedPackage.getPackageName(),
3597                // TODO: We will change version code to long, so in the new API it is long
3598                (int) versionedPackage.getVersionCode(), flags, userId);
3599    }
3600
3601    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3602            int flags, int userId) {
3603        if (!sUserManager.exists(userId)) return null;
3604        flags = updateFlagsForPackage(flags, userId, packageName);
3605        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3606                false /* requireFullPermission */, false /* checkShell */, "get package info");
3607
3608        // reader
3609        synchronized (mPackages) {
3610            // Normalize package name to handle renamed packages and static libs
3611            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3612
3613            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3614            if (matchFactoryOnly) {
3615                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3616                if (ps != null) {
3617                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3618                        return null;
3619                    }
3620                    return generatePackageInfo(ps, flags, userId);
3621                }
3622            }
3623
3624            PackageParser.Package p = mPackages.get(packageName);
3625            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3626                return null;
3627            }
3628            if (DEBUG_PACKAGE_INFO)
3629                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3630            if (p != null) {
3631                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3632                        Binder.getCallingUid(), userId)) {
3633                    return null;
3634                }
3635                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3636            }
3637            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3638                final PackageSetting ps = mSettings.mPackages.get(packageName);
3639                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3640                    return null;
3641                }
3642                return generatePackageInfo(ps, flags, userId);
3643            }
3644        }
3645        return null;
3646    }
3647
3648
3649    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) {
3650        // System/shell/root get to see all static libs
3651        final int appId = UserHandle.getAppId(uid);
3652        if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3653                || appId == Process.ROOT_UID) {
3654            return false;
3655        }
3656
3657        // No package means no static lib as it is always on internal storage
3658        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3659            return false;
3660        }
3661
3662        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3663                ps.pkg.staticSharedLibVersion);
3664        if (libEntry == null) {
3665            return false;
3666        }
3667
3668        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3669        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3670        if (uidPackageNames == null) {
3671            return true;
3672        }
3673
3674        for (String uidPackageName : uidPackageNames) {
3675            if (ps.name.equals(uidPackageName)) {
3676                return false;
3677            }
3678            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3679            if (uidPs != null) {
3680                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3681                        libEntry.info.getName());
3682                if (index < 0) {
3683                    continue;
3684                }
3685                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3686                    return false;
3687                }
3688            }
3689        }
3690        return true;
3691    }
3692
3693    @Override
3694    public String[] currentToCanonicalPackageNames(String[] names) {
3695        String[] out = new String[names.length];
3696        // reader
3697        synchronized (mPackages) {
3698            for (int i=names.length-1; i>=0; i--) {
3699                PackageSetting ps = mSettings.mPackages.get(names[i]);
3700                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3701            }
3702        }
3703        return out;
3704    }
3705
3706    @Override
3707    public String[] canonicalToCurrentPackageNames(String[] names) {
3708        String[] out = new String[names.length];
3709        // reader
3710        synchronized (mPackages) {
3711            for (int i=names.length-1; i>=0; i--) {
3712                String cur = mSettings.getRenamedPackageLPr(names[i]);
3713                out[i] = cur != null ? cur : names[i];
3714            }
3715        }
3716        return out;
3717    }
3718
3719    @Override
3720    public int getPackageUid(String packageName, int flags, int userId) {
3721        if (!sUserManager.exists(userId)) return -1;
3722        flags = updateFlagsForPackage(flags, userId, packageName);
3723        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3724                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3725
3726        // reader
3727        synchronized (mPackages) {
3728            final PackageParser.Package p = mPackages.get(packageName);
3729            if (p != null && p.isMatch(flags)) {
3730                return UserHandle.getUid(userId, p.applicationInfo.uid);
3731            }
3732            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3733                final PackageSetting ps = mSettings.mPackages.get(packageName);
3734                if (ps != null && ps.isMatch(flags)) {
3735                    return UserHandle.getUid(userId, ps.appId);
3736                }
3737            }
3738        }
3739
3740        return -1;
3741    }
3742
3743    @Override
3744    public int[] getPackageGids(String packageName, int flags, int userId) {
3745        if (!sUserManager.exists(userId)) return null;
3746        flags = updateFlagsForPackage(flags, userId, packageName);
3747        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3748                false /* requireFullPermission */, false /* checkShell */,
3749                "getPackageGids");
3750
3751        // reader
3752        synchronized (mPackages) {
3753            final PackageParser.Package p = mPackages.get(packageName);
3754            if (p != null && p.isMatch(flags)) {
3755                PackageSetting ps = (PackageSetting) p.mExtras;
3756                // TODO: Shouldn't this be checking for package installed state for userId and
3757                // return null?
3758                return ps.getPermissionsState().computeGids(userId);
3759            }
3760            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3761                final PackageSetting ps = mSettings.mPackages.get(packageName);
3762                if (ps != null && ps.isMatch(flags)) {
3763                    return ps.getPermissionsState().computeGids(userId);
3764                }
3765            }
3766        }
3767
3768        return null;
3769    }
3770
3771    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3772        if (bp.perm != null) {
3773            return PackageParser.generatePermissionInfo(bp.perm, flags);
3774        }
3775        PermissionInfo pi = new PermissionInfo();
3776        pi.name = bp.name;
3777        pi.packageName = bp.sourcePackage;
3778        pi.nonLocalizedLabel = bp.name;
3779        pi.protectionLevel = bp.protectionLevel;
3780        return pi;
3781    }
3782
3783    @Override
3784    public PermissionInfo getPermissionInfo(String name, int flags) {
3785        // reader
3786        synchronized (mPackages) {
3787            final BasePermission p = mSettings.mPermissions.get(name);
3788            if (p != null) {
3789                return generatePermissionInfo(p, flags);
3790            }
3791            return null;
3792        }
3793    }
3794
3795    @Override
3796    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3797            int flags) {
3798        // reader
3799        synchronized (mPackages) {
3800            if (group != null && !mPermissionGroups.containsKey(group)) {
3801                // This is thrown as NameNotFoundException
3802                return null;
3803            }
3804
3805            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3806            for (BasePermission p : mSettings.mPermissions.values()) {
3807                if (group == null) {
3808                    if (p.perm == null || p.perm.info.group == null) {
3809                        out.add(generatePermissionInfo(p, flags));
3810                    }
3811                } else {
3812                    if (p.perm != null && group.equals(p.perm.info.group)) {
3813                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3814                    }
3815                }
3816            }
3817            return new ParceledListSlice<>(out);
3818        }
3819    }
3820
3821    @Override
3822    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3823        // reader
3824        synchronized (mPackages) {
3825            return PackageParser.generatePermissionGroupInfo(
3826                    mPermissionGroups.get(name), flags);
3827        }
3828    }
3829
3830    @Override
3831    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3832        // reader
3833        synchronized (mPackages) {
3834            final int N = mPermissionGroups.size();
3835            ArrayList<PermissionGroupInfo> out
3836                    = new ArrayList<PermissionGroupInfo>(N);
3837            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3838                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3839            }
3840            return new ParceledListSlice<>(out);
3841        }
3842    }
3843
3844    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3845            int uid, int userId) {
3846        if (!sUserManager.exists(userId)) return null;
3847        PackageSetting ps = mSettings.mPackages.get(packageName);
3848        if (ps != null) {
3849            if (filterSharedLibPackageLPr(ps, uid, userId)) {
3850                return null;
3851            }
3852            if (ps.pkg == null) {
3853                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3854                if (pInfo != null) {
3855                    return pInfo.applicationInfo;
3856                }
3857                return null;
3858            }
3859            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3860                    ps.readUserState(userId), userId);
3861            if (ai != null) {
3862                rebaseEnabledOverlays(ai, userId);
3863                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3864            }
3865            return ai;
3866        }
3867        return null;
3868    }
3869
3870    @Override
3871    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3872        if (!sUserManager.exists(userId)) return null;
3873        flags = updateFlagsForApplication(flags, userId, packageName);
3874        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3875                false /* requireFullPermission */, false /* checkShell */, "get application info");
3876
3877        // writer
3878        synchronized (mPackages) {
3879            // Normalize package name to handle renamed packages and static libs
3880            packageName = resolveInternalPackageNameLPr(packageName,
3881                    PackageManager.VERSION_CODE_HIGHEST);
3882
3883            PackageParser.Package p = mPackages.get(packageName);
3884            if (DEBUG_PACKAGE_INFO) Log.v(
3885                    TAG, "getApplicationInfo " + packageName
3886                    + ": " + p);
3887            if (p != null) {
3888                PackageSetting ps = mSettings.mPackages.get(packageName);
3889                if (ps == null) return null;
3890                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3891                    return null;
3892                }
3893                // Note: isEnabledLP() does not apply here - always return info
3894                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3895                        p, flags, ps.readUserState(userId), userId);
3896                if (ai != null) {
3897                    rebaseEnabledOverlays(ai, userId);
3898                    ai.packageName = resolveExternalPackageNameLPr(p);
3899                }
3900                return ai;
3901            }
3902            if ("android".equals(packageName)||"system".equals(packageName)) {
3903                return mAndroidApplication;
3904            }
3905            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3906                // Already generates the external package name
3907                return generateApplicationInfoFromSettingsLPw(packageName,
3908                        Binder.getCallingUid(), flags, userId);
3909            }
3910        }
3911        return null;
3912    }
3913
3914    private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) {
3915        List<String> paths = new ArrayList<>();
3916        ArrayMap<String, ArrayList<String>> userSpecificOverlays =
3917            mEnabledOverlayPaths.get(userId);
3918        if (userSpecificOverlays != null) {
3919            if (!"android".equals(ai.packageName)) {
3920                ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android");
3921                if (frameworkOverlays != null) {
3922                    paths.addAll(frameworkOverlays);
3923                }
3924            }
3925
3926            ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName);
3927            if (appOverlays != null) {
3928                paths.addAll(appOverlays);
3929            }
3930        }
3931        ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null;
3932    }
3933
3934    private String normalizePackageNameLPr(String packageName) {
3935        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3936        return normalizedPackageName != null ? normalizedPackageName : packageName;
3937    }
3938
3939    @Override
3940    public void deletePreloadsFileCache() {
3941        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
3942            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
3943        }
3944        File dir = Environment.getDataPreloadsFileCacheDirectory();
3945        Slog.i(TAG, "Deleting preloaded file cache " + dir);
3946        FileUtils.deleteContents(dir);
3947    }
3948
3949    @Override
3950    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3951            final IPackageDataObserver observer) {
3952        mContext.enforceCallingOrSelfPermission(
3953                android.Manifest.permission.CLEAR_APP_CACHE, null);
3954        mHandler.post(() -> {
3955            boolean success = false;
3956            try {
3957                freeStorage(volumeUuid, freeStorageSize, 0);
3958                success = true;
3959            } catch (IOException e) {
3960                Slog.w(TAG, e);
3961            }
3962            if (observer != null) {
3963                try {
3964                    observer.onRemoveCompleted(null, success);
3965                } catch (RemoteException e) {
3966                    Slog.w(TAG, e);
3967                }
3968            }
3969        });
3970    }
3971
3972    @Override
3973    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3974            final IntentSender pi) {
3975        mContext.enforceCallingOrSelfPermission(
3976                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
3977        mHandler.post(() -> {
3978            boolean success = false;
3979            try {
3980                freeStorage(volumeUuid, freeStorageSize, 0);
3981                success = true;
3982            } catch (IOException e) {
3983                Slog.w(TAG, e);
3984            }
3985            if (pi != null) {
3986                try {
3987                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
3988                } catch (SendIntentException e) {
3989                    Slog.w(TAG, e);
3990                }
3991            }
3992        });
3993    }
3994
3995    /**
3996     * Blocking call to clear various types of cached data across the system
3997     * until the requested bytes are available.
3998     */
3999    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4000        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4001        final File file = storage.findPathForUuid(volumeUuid);
4002        if (file.getUsableSpace() >= bytes) return;
4003
4004        if (ENABLE_FREE_CACHE_V2) {
4005            final boolean aggressive = (storageFlags
4006                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4007            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4008                    volumeUuid);
4009
4010            // 1. Pre-flight to determine if we have any chance to succeed
4011            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4012            if (internalVolume && (aggressive || SystemProperties
4013                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4014                deletePreloadsFileCache();
4015                if (file.getUsableSpace() >= bytes) return;
4016            }
4017
4018            // 3. Consider parsed APK data (aggressive only)
4019            if (internalVolume && aggressive) {
4020                FileUtils.deleteContents(mCacheDir);
4021                if (file.getUsableSpace() >= bytes) return;
4022            }
4023
4024            // 4. Consider cached app data (above quotas)
4025            try {
4026                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2);
4027            } catch (InstallerException ignored) {
4028            }
4029            if (file.getUsableSpace() >= bytes) return;
4030
4031            // 5. Consider shared libraries with refcount=0 and age>2h
4032            // 6. Consider dexopt output (aggressive only)
4033            // 7. Consider ephemeral apps not used in last week
4034
4035            // 8. Consider cached app data (below quotas)
4036            try {
4037                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2
4038                        | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4039            } catch (InstallerException ignored) {
4040            }
4041            if (file.getUsableSpace() >= bytes) return;
4042
4043            // 9. Consider DropBox entries
4044            // 10. Consider ephemeral cookies
4045
4046        } else {
4047            try {
4048                mInstaller.freeCache(volumeUuid, bytes, 0);
4049            } catch (InstallerException ignored) {
4050            }
4051            if (file.getUsableSpace() >= bytes) return;
4052        }
4053
4054        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4055    }
4056
4057    /**
4058     * Update given flags based on encryption status of current user.
4059     */
4060    private int updateFlags(int flags, int userId) {
4061        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4062                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4063            // Caller expressed an explicit opinion about what encryption
4064            // aware/unaware components they want to see, so fall through and
4065            // give them what they want
4066        } else {
4067            // Caller expressed no opinion, so match based on user state
4068            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4069                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4070            } else {
4071                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4072            }
4073        }
4074        return flags;
4075    }
4076
4077    private UserManagerInternal getUserManagerInternal() {
4078        if (mUserManagerInternal == null) {
4079            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4080        }
4081        return mUserManagerInternal;
4082    }
4083
4084    private DeviceIdleController.LocalService getDeviceIdleController() {
4085        if (mDeviceIdleController == null) {
4086            mDeviceIdleController =
4087                    LocalServices.getService(DeviceIdleController.LocalService.class);
4088        }
4089        return mDeviceIdleController;
4090    }
4091
4092    /**
4093     * Update given flags when being used to request {@link PackageInfo}.
4094     */
4095    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4096        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4097        boolean triaged = true;
4098        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4099                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4100            // Caller is asking for component details, so they'd better be
4101            // asking for specific encryption matching behavior, or be triaged
4102            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4103                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4104                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4105                triaged = false;
4106            }
4107        }
4108        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4109                | PackageManager.MATCH_SYSTEM_ONLY
4110                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4111            triaged = false;
4112        }
4113        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4114            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4115                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4116                    + Debug.getCallers(5));
4117        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4118                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4119            // If the caller wants all packages and has a restricted profile associated with it,
4120            // then match all users. This is to make sure that launchers that need to access work
4121            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4122            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4123            flags |= PackageManager.MATCH_ANY_USER;
4124        }
4125        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4126            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4127                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4128        }
4129        return updateFlags(flags, userId);
4130    }
4131
4132    /**
4133     * Update given flags when being used to request {@link ApplicationInfo}.
4134     */
4135    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4136        return updateFlagsForPackage(flags, userId, cookie);
4137    }
4138
4139    /**
4140     * Update given flags when being used to request {@link ComponentInfo}.
4141     */
4142    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4143        if (cookie instanceof Intent) {
4144            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4145                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4146            }
4147        }
4148
4149        boolean triaged = true;
4150        // Caller is asking for component details, so they'd better be
4151        // asking for specific encryption matching behavior, or be triaged
4152        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4153                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4154                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4155            triaged = false;
4156        }
4157        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4158            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4159                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4160        }
4161
4162        return updateFlags(flags, userId);
4163    }
4164
4165    /**
4166     * Update given intent when being used to request {@link ResolveInfo}.
4167     */
4168    private Intent updateIntentForResolve(Intent intent) {
4169        if (intent.getSelector() != null) {
4170            intent = intent.getSelector();
4171        }
4172        if (DEBUG_PREFERRED) {
4173            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4174        }
4175        return intent;
4176    }
4177
4178    /**
4179     * Update given flags when being used to request {@link ResolveInfo}.
4180     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4181     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4182     * flag set. However, this flag is only honoured in three circumstances:
4183     * <ul>
4184     * <li>when called from a system process</li>
4185     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4186     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4187     * action and a {@code android.intent.category.BROWSABLE} category</li>
4188     * </ul>
4189     */
4190    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4191        return updateFlagsForResolve(flags, userId, intent, callingUid,
4192                false /*includeInstantApps*/, false /*onlyExposedExplicitly*/);
4193    }
4194    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4195            boolean includeInstantApps) {
4196        return updateFlagsForResolve(flags, userId, intent, callingUid,
4197                includeInstantApps, false /*onlyExposedExplicitly*/);
4198    }
4199    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4200            boolean includeInstantApps, boolean onlyExposedExplicitly) {
4201        // Safe mode means we shouldn't match any third-party components
4202        if (mSafeMode) {
4203            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4204        }
4205        if (getInstantAppPackageName(callingUid) != null) {
4206            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4207            if (onlyExposedExplicitly) {
4208                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4209            }
4210            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4211            flags |= PackageManager.MATCH_INSTANT;
4212        } else {
4213            // Otherwise, prevent leaking ephemeral components
4214            final boolean isSpecialProcess =
4215                    callingUid == Process.SYSTEM_UID
4216                    || callingUid == Process.SHELL_UID
4217                    || callingUid == 0;
4218            final boolean allowMatchInstant =
4219                    (includeInstantApps
4220                            && Intent.ACTION_VIEW.equals(intent.getAction())
4221                            && intent.hasCategory(Intent.CATEGORY_BROWSABLE)
4222                            && hasWebURI(intent))
4223                    || isSpecialProcess
4224                    || mContext.checkCallingOrSelfPermission(
4225                            android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED;
4226            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4227                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4228            if (!allowMatchInstant) {
4229                flags &= ~PackageManager.MATCH_INSTANT;
4230            }
4231        }
4232        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4233    }
4234
4235    private ActivityInfo generateActivityInfo(ActivityInfo ai, int flags, PackageUserState state,
4236            int userId) {
4237        ActivityInfo ret = PackageParser.generateActivityInfo(ai, flags, state, userId);
4238        if (ret != null) {
4239            rebaseEnabledOverlays(ret.applicationInfo, userId);
4240        }
4241        return ret;
4242    }
4243
4244    private ActivityInfo generateActivityInfo(PackageParser.Activity a, int flags,
4245            PackageUserState state, int userId) {
4246        ActivityInfo ai = PackageParser.generateActivityInfo(a, flags, state, userId);
4247        if (ai != null) {
4248            rebaseEnabledOverlays(ai.applicationInfo, userId);
4249        }
4250        return ai;
4251    }
4252
4253    @Override
4254    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4255        if (!sUserManager.exists(userId)) return null;
4256        flags = updateFlagsForComponent(flags, userId, component);
4257        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4258                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4259        synchronized (mPackages) {
4260            PackageParser.Activity a = mActivities.mActivities.get(component);
4261
4262            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4263            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4264                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4265                if (ps == null) return null;
4266                return generateActivityInfo(a, flags, ps.readUserState(userId), userId);
4267            }
4268            if (mResolveComponentName.equals(component)) {
4269                return generateActivityInfo(mResolveActivity, flags, new PackageUserState(),
4270                        userId);
4271            }
4272        }
4273        return null;
4274    }
4275
4276    @Override
4277    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4278            String resolvedType) {
4279        synchronized (mPackages) {
4280            if (component.equals(mResolveComponentName)) {
4281                // The resolver supports EVERYTHING!
4282                return true;
4283            }
4284            PackageParser.Activity a = mActivities.mActivities.get(component);
4285            if (a == null) {
4286                return false;
4287            }
4288            for (int i=0; i<a.intents.size(); i++) {
4289                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4290                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4291                    return true;
4292                }
4293            }
4294            return false;
4295        }
4296    }
4297
4298    @Override
4299    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4300        if (!sUserManager.exists(userId)) return null;
4301        flags = updateFlagsForComponent(flags, userId, component);
4302        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4303                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4304        synchronized (mPackages) {
4305            PackageParser.Activity a = mReceivers.mActivities.get(component);
4306            if (DEBUG_PACKAGE_INFO) Log.v(
4307                TAG, "getReceiverInfo " + component + ": " + a);
4308            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4309                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4310                if (ps == null) return null;
4311                return generateActivityInfo(a, flags, ps.readUserState(userId), userId);
4312            }
4313        }
4314        return null;
4315    }
4316
4317    @Override
4318    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4319        if (!sUserManager.exists(userId)) return null;
4320        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4321
4322        flags = updateFlagsForPackage(flags, userId, null);
4323
4324        final boolean canSeeStaticLibraries =
4325                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4326                        == PERMISSION_GRANTED
4327                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4328                        == PERMISSION_GRANTED
4329                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4330                        == PERMISSION_GRANTED
4331                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4332                        == PERMISSION_GRANTED;
4333
4334        synchronized (mPackages) {
4335            List<SharedLibraryInfo> result = null;
4336
4337            final int libCount = mSharedLibraries.size();
4338            for (int i = 0; i < libCount; i++) {
4339                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4340                if (versionedLib == null) {
4341                    continue;
4342                }
4343
4344                final int versionCount = versionedLib.size();
4345                for (int j = 0; j < versionCount; j++) {
4346                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4347                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4348                        break;
4349                    }
4350                    final long identity = Binder.clearCallingIdentity();
4351                    try {
4352                        // TODO: We will change version code to long, so in the new API it is long
4353                        PackageInfo packageInfo = getPackageInfoVersioned(
4354                                libInfo.getDeclaringPackage(), flags, userId);
4355                        if (packageInfo == null) {
4356                            continue;
4357                        }
4358                    } finally {
4359                        Binder.restoreCallingIdentity(identity);
4360                    }
4361
4362                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4363                            libInfo.getVersion(), libInfo.getType(),
4364                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4365                            flags, userId));
4366
4367                    if (result == null) {
4368                        result = new ArrayList<>();
4369                    }
4370                    result.add(resLibInfo);
4371                }
4372            }
4373
4374            return result != null ? new ParceledListSlice<>(result) : null;
4375        }
4376    }
4377
4378    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4379            SharedLibraryInfo libInfo, int flags, int userId) {
4380        List<VersionedPackage> versionedPackages = null;
4381        final int packageCount = mSettings.mPackages.size();
4382        for (int i = 0; i < packageCount; i++) {
4383            PackageSetting ps = mSettings.mPackages.valueAt(i);
4384
4385            if (ps == null) {
4386                continue;
4387            }
4388
4389            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4390                continue;
4391            }
4392
4393            final String libName = libInfo.getName();
4394            if (libInfo.isStatic()) {
4395                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4396                if (libIdx < 0) {
4397                    continue;
4398                }
4399                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4400                    continue;
4401                }
4402                if (versionedPackages == null) {
4403                    versionedPackages = new ArrayList<>();
4404                }
4405                // If the dependent is a static shared lib, use the public package name
4406                String dependentPackageName = ps.name;
4407                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4408                    dependentPackageName = ps.pkg.manifestPackageName;
4409                }
4410                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4411            } else if (ps.pkg != null) {
4412                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4413                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4414                    if (versionedPackages == null) {
4415                        versionedPackages = new ArrayList<>();
4416                    }
4417                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4418                }
4419            }
4420        }
4421
4422        return versionedPackages;
4423    }
4424
4425    @Override
4426    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4427        if (!sUserManager.exists(userId)) return null;
4428        flags = updateFlagsForComponent(flags, userId, component);
4429        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4430                false /* requireFullPermission */, false /* checkShell */, "get service info");
4431        synchronized (mPackages) {
4432            PackageParser.Service s = mServices.mServices.get(component);
4433            if (DEBUG_PACKAGE_INFO) Log.v(
4434                TAG, "getServiceInfo " + component + ": " + s);
4435            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4436                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4437                if (ps == null) return null;
4438                ServiceInfo si = PackageParser.generateServiceInfo(s, flags,
4439                        ps.readUserState(userId), userId);
4440                if (si != null) {
4441                    rebaseEnabledOverlays(si.applicationInfo, userId);
4442                }
4443                return si;
4444            }
4445        }
4446        return null;
4447    }
4448
4449    @Override
4450    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4451        if (!sUserManager.exists(userId)) return null;
4452        flags = updateFlagsForComponent(flags, userId, component);
4453        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4454                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4455        synchronized (mPackages) {
4456            PackageParser.Provider p = mProviders.mProviders.get(component);
4457            if (DEBUG_PACKAGE_INFO) Log.v(
4458                TAG, "getProviderInfo " + component + ": " + p);
4459            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4460                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4461                if (ps == null) return null;
4462                ProviderInfo pi = PackageParser.generateProviderInfo(p, flags,
4463                        ps.readUserState(userId), userId);
4464                if (pi != null) {
4465                    rebaseEnabledOverlays(pi.applicationInfo, userId);
4466                }
4467                return pi;
4468            }
4469        }
4470        return null;
4471    }
4472
4473    @Override
4474    public String[] getSystemSharedLibraryNames() {
4475        synchronized (mPackages) {
4476            Set<String> libs = null;
4477            final int libCount = mSharedLibraries.size();
4478            for (int i = 0; i < libCount; i++) {
4479                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4480                if (versionedLib == null) {
4481                    continue;
4482                }
4483                final int versionCount = versionedLib.size();
4484                for (int j = 0; j < versionCount; j++) {
4485                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4486                    if (!libEntry.info.isStatic()) {
4487                        if (libs == null) {
4488                            libs = new ArraySet<>();
4489                        }
4490                        libs.add(libEntry.info.getName());
4491                        break;
4492                    }
4493                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4494                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4495                            UserHandle.getUserId(Binder.getCallingUid()))) {
4496                        if (libs == null) {
4497                            libs = new ArraySet<>();
4498                        }
4499                        libs.add(libEntry.info.getName());
4500                        break;
4501                    }
4502                }
4503            }
4504
4505            if (libs != null) {
4506                String[] libsArray = new String[libs.size()];
4507                libs.toArray(libsArray);
4508                return libsArray;
4509            }
4510
4511            return null;
4512        }
4513    }
4514
4515    @Override
4516    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4517        synchronized (mPackages) {
4518            return mServicesSystemSharedLibraryPackageName;
4519        }
4520    }
4521
4522    @Override
4523    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4524        synchronized (mPackages) {
4525            return mSharedSystemSharedLibraryPackageName;
4526        }
4527    }
4528
4529    private void updateSequenceNumberLP(String packageName, int[] userList) {
4530        for (int i = userList.length - 1; i >= 0; --i) {
4531            final int userId = userList[i];
4532            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4533            if (changedPackages == null) {
4534                changedPackages = new SparseArray<>();
4535                mChangedPackages.put(userId, changedPackages);
4536            }
4537            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4538            if (sequenceNumbers == null) {
4539                sequenceNumbers = new HashMap<>();
4540                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4541            }
4542            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4543            if (sequenceNumber != null) {
4544                changedPackages.remove(sequenceNumber);
4545            }
4546            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4547            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4548        }
4549        mChangedPackagesSequenceNumber++;
4550    }
4551
4552    @Override
4553    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4554        synchronized (mPackages) {
4555            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4556                return null;
4557            }
4558            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4559            if (changedPackages == null) {
4560                return null;
4561            }
4562            final List<String> packageNames =
4563                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4564            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4565                final String packageName = changedPackages.get(i);
4566                if (packageName != null) {
4567                    packageNames.add(packageName);
4568                }
4569            }
4570            return packageNames.isEmpty()
4571                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4572        }
4573    }
4574
4575    @Override
4576    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4577        ArrayList<FeatureInfo> res;
4578        synchronized (mAvailableFeatures) {
4579            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4580            res.addAll(mAvailableFeatures.values());
4581        }
4582        final FeatureInfo fi = new FeatureInfo();
4583        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4584                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4585        res.add(fi);
4586
4587        return new ParceledListSlice<>(res);
4588    }
4589
4590    @Override
4591    public boolean hasSystemFeature(String name, int version) {
4592        synchronized (mAvailableFeatures) {
4593            final FeatureInfo feat = mAvailableFeatures.get(name);
4594            if (feat == null) {
4595                return false;
4596            } else {
4597                return feat.version >= version;
4598            }
4599        }
4600    }
4601
4602    @Override
4603    public int checkPermission(String permName, String pkgName, int userId) {
4604        if (!sUserManager.exists(userId)) {
4605            return PackageManager.PERMISSION_DENIED;
4606        }
4607
4608        synchronized (mPackages) {
4609            final PackageParser.Package p = mPackages.get(pkgName);
4610            if (p != null && p.mExtras != null) {
4611                final PackageSetting ps = (PackageSetting) p.mExtras;
4612                final PermissionsState permissionsState = ps.getPermissionsState();
4613                if (permissionsState.hasPermission(permName, userId)) {
4614                    return PackageManager.PERMISSION_GRANTED;
4615                }
4616                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4617                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4618                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4619                    return PackageManager.PERMISSION_GRANTED;
4620                }
4621            }
4622        }
4623
4624        return PackageManager.PERMISSION_DENIED;
4625    }
4626
4627    @Override
4628    public int checkUidPermission(String permName, int uid) {
4629        final int userId = UserHandle.getUserId(uid);
4630
4631        if (!sUserManager.exists(userId)) {
4632            return PackageManager.PERMISSION_DENIED;
4633        }
4634
4635        synchronized (mPackages) {
4636            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4637            if (obj != null) {
4638                final SettingBase ps = (SettingBase) obj;
4639                final PermissionsState permissionsState = ps.getPermissionsState();
4640                if (permissionsState.hasPermission(permName, userId)) {
4641                    return PackageManager.PERMISSION_GRANTED;
4642                }
4643                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4644                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4645                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4646                    return PackageManager.PERMISSION_GRANTED;
4647                }
4648            } else {
4649                ArraySet<String> perms = mSystemPermissions.get(uid);
4650                if (perms != null) {
4651                    if (perms.contains(permName)) {
4652                        return PackageManager.PERMISSION_GRANTED;
4653                    }
4654                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4655                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4656                        return PackageManager.PERMISSION_GRANTED;
4657                    }
4658                }
4659            }
4660        }
4661
4662        return PackageManager.PERMISSION_DENIED;
4663    }
4664
4665    @Override
4666    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4667        if (UserHandle.getCallingUserId() != userId) {
4668            mContext.enforceCallingPermission(
4669                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4670                    "isPermissionRevokedByPolicy for user " + userId);
4671        }
4672
4673        if (checkPermission(permission, packageName, userId)
4674                == PackageManager.PERMISSION_GRANTED) {
4675            return false;
4676        }
4677
4678        final long identity = Binder.clearCallingIdentity();
4679        try {
4680            final int flags = getPermissionFlags(permission, packageName, userId);
4681            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4682        } finally {
4683            Binder.restoreCallingIdentity(identity);
4684        }
4685    }
4686
4687    @Override
4688    public String getPermissionControllerPackageName() {
4689        synchronized (mPackages) {
4690            return mRequiredInstallerPackage;
4691        }
4692    }
4693
4694    /**
4695     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4696     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4697     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4698     * @param message the message to log on security exception
4699     */
4700    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4701            boolean checkShell, String message) {
4702        if (userId < 0) {
4703            throw new IllegalArgumentException("Invalid userId " + userId);
4704        }
4705        if (checkShell) {
4706            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4707        }
4708        if (userId == UserHandle.getUserId(callingUid)) return;
4709        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4710            if (requireFullPermission) {
4711                mContext.enforceCallingOrSelfPermission(
4712                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4713            } else {
4714                try {
4715                    mContext.enforceCallingOrSelfPermission(
4716                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4717                } catch (SecurityException se) {
4718                    mContext.enforceCallingOrSelfPermission(
4719                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4720                }
4721            }
4722        }
4723    }
4724
4725    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4726        if (callingUid == Process.SHELL_UID) {
4727            if (userHandle >= 0
4728                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4729                throw new SecurityException("Shell does not have permission to access user "
4730                        + userHandle);
4731            } else if (userHandle < 0) {
4732                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4733                        + Debug.getCallers(3));
4734            }
4735        }
4736    }
4737
4738    private BasePermission findPermissionTreeLP(String permName) {
4739        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4740            if (permName.startsWith(bp.name) &&
4741                    permName.length() > bp.name.length() &&
4742                    permName.charAt(bp.name.length()) == '.') {
4743                return bp;
4744            }
4745        }
4746        return null;
4747    }
4748
4749    private BasePermission checkPermissionTreeLP(String permName) {
4750        if (permName != null) {
4751            BasePermission bp = findPermissionTreeLP(permName);
4752            if (bp != null) {
4753                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4754                    return bp;
4755                }
4756                throw new SecurityException("Calling uid "
4757                        + Binder.getCallingUid()
4758                        + " is not allowed to add to permission tree "
4759                        + bp.name + " owned by uid " + bp.uid);
4760            }
4761        }
4762        throw new SecurityException("No permission tree found for " + permName);
4763    }
4764
4765    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4766        if (s1 == null) {
4767            return s2 == null;
4768        }
4769        if (s2 == null) {
4770            return false;
4771        }
4772        if (s1.getClass() != s2.getClass()) {
4773            return false;
4774        }
4775        return s1.equals(s2);
4776    }
4777
4778    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4779        if (pi1.icon != pi2.icon) return false;
4780        if (pi1.logo != pi2.logo) return false;
4781        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4782        if (!compareStrings(pi1.name, pi2.name)) return false;
4783        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4784        // We'll take care of setting this one.
4785        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4786        // These are not currently stored in settings.
4787        //if (!compareStrings(pi1.group, pi2.group)) return false;
4788        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4789        //if (pi1.labelRes != pi2.labelRes) return false;
4790        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4791        return true;
4792    }
4793
4794    int permissionInfoFootprint(PermissionInfo info) {
4795        int size = info.name.length();
4796        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4797        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4798        return size;
4799    }
4800
4801    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4802        int size = 0;
4803        for (BasePermission perm : mSettings.mPermissions.values()) {
4804            if (perm.uid == tree.uid) {
4805                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4806            }
4807        }
4808        return size;
4809    }
4810
4811    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4812        // We calculate the max size of permissions defined by this uid and throw
4813        // if that plus the size of 'info' would exceed our stated maximum.
4814        if (tree.uid != Process.SYSTEM_UID) {
4815            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4816            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4817                throw new SecurityException("Permission tree size cap exceeded");
4818            }
4819        }
4820    }
4821
4822    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4823        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4824            throw new SecurityException("Label must be specified in permission");
4825        }
4826        BasePermission tree = checkPermissionTreeLP(info.name);
4827        BasePermission bp = mSettings.mPermissions.get(info.name);
4828        boolean added = bp == null;
4829        boolean changed = true;
4830        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4831        if (added) {
4832            enforcePermissionCapLocked(info, tree);
4833            bp = new BasePermission(info.name, tree.sourcePackage,
4834                    BasePermission.TYPE_DYNAMIC);
4835        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4836            throw new SecurityException(
4837                    "Not allowed to modify non-dynamic permission "
4838                    + info.name);
4839        } else {
4840            if (bp.protectionLevel == fixedLevel
4841                    && bp.perm.owner.equals(tree.perm.owner)
4842                    && bp.uid == tree.uid
4843                    && comparePermissionInfos(bp.perm.info, info)) {
4844                changed = false;
4845            }
4846        }
4847        bp.protectionLevel = fixedLevel;
4848        info = new PermissionInfo(info);
4849        info.protectionLevel = fixedLevel;
4850        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4851        bp.perm.info.packageName = tree.perm.info.packageName;
4852        bp.uid = tree.uid;
4853        if (added) {
4854            mSettings.mPermissions.put(info.name, bp);
4855        }
4856        if (changed) {
4857            if (!async) {
4858                mSettings.writeLPr();
4859            } else {
4860                scheduleWriteSettingsLocked();
4861            }
4862        }
4863        return added;
4864    }
4865
4866    @Override
4867    public boolean addPermission(PermissionInfo info) {
4868        synchronized (mPackages) {
4869            return addPermissionLocked(info, false);
4870        }
4871    }
4872
4873    @Override
4874    public boolean addPermissionAsync(PermissionInfo info) {
4875        synchronized (mPackages) {
4876            return addPermissionLocked(info, true);
4877        }
4878    }
4879
4880    @Override
4881    public void removePermission(String name) {
4882        synchronized (mPackages) {
4883            checkPermissionTreeLP(name);
4884            BasePermission bp = mSettings.mPermissions.get(name);
4885            if (bp != null) {
4886                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4887                    throw new SecurityException(
4888                            "Not allowed to modify non-dynamic permission "
4889                            + name);
4890                }
4891                mSettings.mPermissions.remove(name);
4892                mSettings.writeLPr();
4893            }
4894        }
4895    }
4896
4897    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4898            BasePermission bp) {
4899        int index = pkg.requestedPermissions.indexOf(bp.name);
4900        if (index == -1) {
4901            throw new SecurityException("Package " + pkg.packageName
4902                    + " has not requested permission " + bp.name);
4903        }
4904        if (!bp.isRuntime() && !bp.isDevelopment()) {
4905            throw new SecurityException("Permission " + bp.name
4906                    + " is not a changeable permission type");
4907        }
4908    }
4909
4910    @Override
4911    public void grantRuntimePermission(String packageName, String name, final int userId) {
4912        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4913    }
4914
4915    private void grantRuntimePermission(String packageName, String name, final int userId,
4916            boolean overridePolicy) {
4917        if (!sUserManager.exists(userId)) {
4918            Log.e(TAG, "No such user:" + userId);
4919            return;
4920        }
4921
4922        mContext.enforceCallingOrSelfPermission(
4923                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4924                "grantRuntimePermission");
4925
4926        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4927                true /* requireFullPermission */, true /* checkShell */,
4928                "grantRuntimePermission");
4929
4930        final int uid;
4931        final SettingBase sb;
4932
4933        synchronized (mPackages) {
4934            final PackageParser.Package pkg = mPackages.get(packageName);
4935            if (pkg == null) {
4936                throw new IllegalArgumentException("Unknown package: " + packageName);
4937            }
4938
4939            final BasePermission bp = mSettings.mPermissions.get(name);
4940            if (bp == null) {
4941                throw new IllegalArgumentException("Unknown permission: " + name);
4942            }
4943
4944            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4945
4946            // If a permission review is required for legacy apps we represent
4947            // their permissions as always granted runtime ones since we need
4948            // to keep the review required permission flag per user while an
4949            // install permission's state is shared across all users.
4950            if (mPermissionReviewRequired
4951                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4952                    && bp.isRuntime()) {
4953                return;
4954            }
4955
4956            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4957            sb = (SettingBase) pkg.mExtras;
4958            if (sb == null) {
4959                throw new IllegalArgumentException("Unknown package: " + packageName);
4960            }
4961
4962            final PermissionsState permissionsState = sb.getPermissionsState();
4963
4964            final int flags = permissionsState.getPermissionFlags(name, userId);
4965            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4966                throw new SecurityException("Cannot grant system fixed permission "
4967                        + name + " for package " + packageName);
4968            }
4969            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4970                throw new SecurityException("Cannot grant policy fixed permission "
4971                        + name + " for package " + packageName);
4972            }
4973
4974            if (bp.isDevelopment()) {
4975                // Development permissions must be handled specially, since they are not
4976                // normal runtime permissions.  For now they apply to all users.
4977                if (permissionsState.grantInstallPermission(bp) !=
4978                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4979                    scheduleWriteSettingsLocked();
4980                }
4981                return;
4982            }
4983
4984            final PackageSetting ps = mSettings.mPackages.get(packageName);
4985            if (ps.getInstantApp(userId) && !bp.isInstant()) {
4986                throw new SecurityException("Cannot grant non-ephemeral permission"
4987                        + name + " for package " + packageName);
4988            }
4989
4990            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4991                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4992                return;
4993            }
4994
4995            final int result = permissionsState.grantRuntimePermission(bp, userId);
4996            switch (result) {
4997                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4998                    return;
4999                }
5000
5001                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5002                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5003                    mHandler.post(new Runnable() {
5004                        @Override
5005                        public void run() {
5006                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5007                        }
5008                    });
5009                }
5010                break;
5011            }
5012
5013            if (bp.isRuntime()) {
5014                logPermissionGranted(mContext, name, packageName);
5015            }
5016
5017            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5018
5019            // Not critical if that is lost - app has to request again.
5020            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5021        }
5022
5023        // Only need to do this if user is initialized. Otherwise it's a new user
5024        // and there are no processes running as the user yet and there's no need
5025        // to make an expensive call to remount processes for the changed permissions.
5026        if (READ_EXTERNAL_STORAGE.equals(name)
5027                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5028            final long token = Binder.clearCallingIdentity();
5029            try {
5030                if (sUserManager.isInitialized(userId)) {
5031                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5032                            StorageManagerInternal.class);
5033                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5034                }
5035            } finally {
5036                Binder.restoreCallingIdentity(token);
5037            }
5038        }
5039    }
5040
5041    @Override
5042    public void revokeRuntimePermission(String packageName, String name, int userId) {
5043        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5044    }
5045
5046    private void revokeRuntimePermission(String packageName, String name, int userId,
5047            boolean overridePolicy) {
5048        if (!sUserManager.exists(userId)) {
5049            Log.e(TAG, "No such user:" + userId);
5050            return;
5051        }
5052
5053        mContext.enforceCallingOrSelfPermission(
5054                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5055                "revokeRuntimePermission");
5056
5057        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5058                true /* requireFullPermission */, true /* checkShell */,
5059                "revokeRuntimePermission");
5060
5061        final int appId;
5062
5063        synchronized (mPackages) {
5064            final PackageParser.Package pkg = mPackages.get(packageName);
5065            if (pkg == null) {
5066                throw new IllegalArgumentException("Unknown package: " + packageName);
5067            }
5068
5069            final BasePermission bp = mSettings.mPermissions.get(name);
5070            if (bp == null) {
5071                throw new IllegalArgumentException("Unknown permission: " + name);
5072            }
5073
5074            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5075
5076            // If a permission review is required for legacy apps we represent
5077            // their permissions as always granted runtime ones since we need
5078            // to keep the review required permission flag per user while an
5079            // install permission's state is shared across all users.
5080            if (mPermissionReviewRequired
5081                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5082                    && bp.isRuntime()) {
5083                return;
5084            }
5085
5086            SettingBase sb = (SettingBase) pkg.mExtras;
5087            if (sb == null) {
5088                throw new IllegalArgumentException("Unknown package: " + packageName);
5089            }
5090
5091            final PermissionsState permissionsState = sb.getPermissionsState();
5092
5093            final int flags = permissionsState.getPermissionFlags(name, userId);
5094            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5095                throw new SecurityException("Cannot revoke system fixed permission "
5096                        + name + " for package " + packageName);
5097            }
5098            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5099                throw new SecurityException("Cannot revoke policy fixed permission "
5100                        + name + " for package " + packageName);
5101            }
5102
5103            if (bp.isDevelopment()) {
5104                // Development permissions must be handled specially, since they are not
5105                // normal runtime permissions.  For now they apply to all users.
5106                if (permissionsState.revokeInstallPermission(bp) !=
5107                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5108                    scheduleWriteSettingsLocked();
5109                }
5110                return;
5111            }
5112
5113            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5114                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5115                return;
5116            }
5117
5118            if (bp.isRuntime()) {
5119                logPermissionRevoked(mContext, name, packageName);
5120            }
5121
5122            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5123
5124            // Critical, after this call app should never have the permission.
5125            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5126
5127            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5128        }
5129
5130        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5131    }
5132
5133    /**
5134     * Get the first event id for the permission.
5135     *
5136     * <p>There are four events for each permission: <ul>
5137     *     <li>Request permission: first id + 0</li>
5138     *     <li>Grant permission: first id + 1</li>
5139     *     <li>Request for permission denied: first id + 2</li>
5140     *     <li>Revoke permission: first id + 3</li>
5141     * </ul></p>
5142     *
5143     * @param name name of the permission
5144     *
5145     * @return The first event id for the permission
5146     */
5147    private static int getBaseEventId(@NonNull String name) {
5148        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5149
5150        if (eventIdIndex == -1) {
5151            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5152                    || "user".equals(Build.TYPE)) {
5153                Log.i(TAG, "Unknown permission " + name);
5154
5155                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5156            } else {
5157                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5158                //
5159                // Also update
5160                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5161                // - metrics_constants.proto
5162                throw new IllegalStateException("Unknown permission " + name);
5163            }
5164        }
5165
5166        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5167    }
5168
5169    /**
5170     * Log that a permission was revoked.
5171     *
5172     * @param context Context of the caller
5173     * @param name name of the permission
5174     * @param packageName package permission if for
5175     */
5176    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5177            @NonNull String packageName) {
5178        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5179    }
5180
5181    /**
5182     * Log that a permission request was granted.
5183     *
5184     * @param context Context of the caller
5185     * @param name name of the permission
5186     * @param packageName package permission if for
5187     */
5188    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5189            @NonNull String packageName) {
5190        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5191    }
5192
5193    @Override
5194    public void resetRuntimePermissions() {
5195        mContext.enforceCallingOrSelfPermission(
5196                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5197                "revokeRuntimePermission");
5198
5199        int callingUid = Binder.getCallingUid();
5200        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5201            mContext.enforceCallingOrSelfPermission(
5202                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5203                    "resetRuntimePermissions");
5204        }
5205
5206        synchronized (mPackages) {
5207            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5208            for (int userId : UserManagerService.getInstance().getUserIds()) {
5209                final int packageCount = mPackages.size();
5210                for (int i = 0; i < packageCount; i++) {
5211                    PackageParser.Package pkg = mPackages.valueAt(i);
5212                    if (!(pkg.mExtras instanceof PackageSetting)) {
5213                        continue;
5214                    }
5215                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5216                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5217                }
5218            }
5219        }
5220    }
5221
5222    @Override
5223    public int getPermissionFlags(String name, String packageName, int userId) {
5224        if (!sUserManager.exists(userId)) {
5225            return 0;
5226        }
5227
5228        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5229
5230        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5231                true /* requireFullPermission */, false /* checkShell */,
5232                "getPermissionFlags");
5233
5234        synchronized (mPackages) {
5235            final PackageParser.Package pkg = mPackages.get(packageName);
5236            if (pkg == null) {
5237                return 0;
5238            }
5239
5240            final BasePermission bp = mSettings.mPermissions.get(name);
5241            if (bp == null) {
5242                return 0;
5243            }
5244
5245            SettingBase sb = (SettingBase) pkg.mExtras;
5246            if (sb == null) {
5247                return 0;
5248            }
5249
5250            PermissionsState permissionsState = sb.getPermissionsState();
5251            return permissionsState.getPermissionFlags(name, userId);
5252        }
5253    }
5254
5255    @Override
5256    public void updatePermissionFlags(String name, String packageName, int flagMask,
5257            int flagValues, int userId) {
5258        if (!sUserManager.exists(userId)) {
5259            return;
5260        }
5261
5262        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5263
5264        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5265                true /* requireFullPermission */, true /* checkShell */,
5266                "updatePermissionFlags");
5267
5268        // Only the system can change these flags and nothing else.
5269        if (getCallingUid() != Process.SYSTEM_UID) {
5270            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5271            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5272            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5273            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5274            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5275        }
5276
5277        synchronized (mPackages) {
5278            final PackageParser.Package pkg = mPackages.get(packageName);
5279            if (pkg == null) {
5280                throw new IllegalArgumentException("Unknown package: " + packageName);
5281            }
5282
5283            final BasePermission bp = mSettings.mPermissions.get(name);
5284            if (bp == null) {
5285                throw new IllegalArgumentException("Unknown permission: " + name);
5286            }
5287
5288            SettingBase sb = (SettingBase) pkg.mExtras;
5289            if (sb == null) {
5290                throw new IllegalArgumentException("Unknown package: " + packageName);
5291            }
5292
5293            PermissionsState permissionsState = sb.getPermissionsState();
5294
5295            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5296
5297            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5298                // Install and runtime permissions are stored in different places,
5299                // so figure out what permission changed and persist the change.
5300                if (permissionsState.getInstallPermissionState(name) != null) {
5301                    scheduleWriteSettingsLocked();
5302                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5303                        || hadState) {
5304                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5305                }
5306            }
5307        }
5308    }
5309
5310    /**
5311     * Update the permission flags for all packages and runtime permissions of a user in order
5312     * to allow device or profile owner to remove POLICY_FIXED.
5313     */
5314    @Override
5315    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5316        if (!sUserManager.exists(userId)) {
5317            return;
5318        }
5319
5320        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5321
5322        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5323                true /* requireFullPermission */, true /* checkShell */,
5324                "updatePermissionFlagsForAllApps");
5325
5326        // Only the system can change system fixed flags.
5327        if (getCallingUid() != Process.SYSTEM_UID) {
5328            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5329            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5330        }
5331
5332        synchronized (mPackages) {
5333            boolean changed = false;
5334            final int packageCount = mPackages.size();
5335            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5336                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5337                SettingBase sb = (SettingBase) pkg.mExtras;
5338                if (sb == null) {
5339                    continue;
5340                }
5341                PermissionsState permissionsState = sb.getPermissionsState();
5342                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5343                        userId, flagMask, flagValues);
5344            }
5345            if (changed) {
5346                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5347            }
5348        }
5349    }
5350
5351    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5352        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5353                != PackageManager.PERMISSION_GRANTED
5354            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5355                != PackageManager.PERMISSION_GRANTED) {
5356            throw new SecurityException(message + " requires "
5357                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5358                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5359        }
5360    }
5361
5362    @Override
5363    public boolean shouldShowRequestPermissionRationale(String permissionName,
5364            String packageName, int userId) {
5365        if (UserHandle.getCallingUserId() != userId) {
5366            mContext.enforceCallingPermission(
5367                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5368                    "canShowRequestPermissionRationale for user " + userId);
5369        }
5370
5371        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5372        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5373            return false;
5374        }
5375
5376        if (checkPermission(permissionName, packageName, userId)
5377                == PackageManager.PERMISSION_GRANTED) {
5378            return false;
5379        }
5380
5381        final int flags;
5382
5383        final long identity = Binder.clearCallingIdentity();
5384        try {
5385            flags = getPermissionFlags(permissionName,
5386                    packageName, userId);
5387        } finally {
5388            Binder.restoreCallingIdentity(identity);
5389        }
5390
5391        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5392                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5393                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5394
5395        if ((flags & fixedFlags) != 0) {
5396            return false;
5397        }
5398
5399        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5400    }
5401
5402    @Override
5403    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5404        mContext.enforceCallingOrSelfPermission(
5405                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5406                "addOnPermissionsChangeListener");
5407
5408        synchronized (mPackages) {
5409            mOnPermissionChangeListeners.addListenerLocked(listener);
5410        }
5411    }
5412
5413    @Override
5414    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5415        synchronized (mPackages) {
5416            mOnPermissionChangeListeners.removeListenerLocked(listener);
5417        }
5418    }
5419
5420    @Override
5421    public boolean isProtectedBroadcast(String actionName) {
5422        synchronized (mPackages) {
5423            if (mProtectedBroadcasts.contains(actionName)) {
5424                return true;
5425            } else if (actionName != null) {
5426                // TODO: remove these terrible hacks
5427                if (actionName.startsWith("android.net.netmon.lingerExpired")
5428                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5429                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5430                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5431                    return true;
5432                }
5433            }
5434        }
5435        return false;
5436    }
5437
5438    @Override
5439    public int checkSignatures(String pkg1, String pkg2) {
5440        synchronized (mPackages) {
5441            final PackageParser.Package p1 = mPackages.get(pkg1);
5442            final PackageParser.Package p2 = mPackages.get(pkg2);
5443            if (p1 == null || p1.mExtras == null
5444                    || p2 == null || p2.mExtras == null) {
5445                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5446            }
5447            return compareSignatures(p1.mSignatures, p2.mSignatures);
5448        }
5449    }
5450
5451    @Override
5452    public int checkUidSignatures(int uid1, int uid2) {
5453        // Map to base uids.
5454        uid1 = UserHandle.getAppId(uid1);
5455        uid2 = UserHandle.getAppId(uid2);
5456        // reader
5457        synchronized (mPackages) {
5458            Signature[] s1;
5459            Signature[] s2;
5460            Object obj = mSettings.getUserIdLPr(uid1);
5461            if (obj != null) {
5462                if (obj instanceof SharedUserSetting) {
5463                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5464                } else if (obj instanceof PackageSetting) {
5465                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5466                } else {
5467                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5468                }
5469            } else {
5470                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5471            }
5472            obj = mSettings.getUserIdLPr(uid2);
5473            if (obj != null) {
5474                if (obj instanceof SharedUserSetting) {
5475                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5476                } else if (obj instanceof PackageSetting) {
5477                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5478                } else {
5479                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5480                }
5481            } else {
5482                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5483            }
5484            return compareSignatures(s1, s2);
5485        }
5486    }
5487
5488    /**
5489     * This method should typically only be used when granting or revoking
5490     * permissions, since the app may immediately restart after this call.
5491     * <p>
5492     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5493     * guard your work against the app being relaunched.
5494     */
5495    private void killUid(int appId, int userId, String reason) {
5496        final long identity = Binder.clearCallingIdentity();
5497        try {
5498            IActivityManager am = ActivityManager.getService();
5499            if (am != null) {
5500                try {
5501                    am.killUid(appId, userId, reason);
5502                } catch (RemoteException e) {
5503                    /* ignore - same process */
5504                }
5505            }
5506        } finally {
5507            Binder.restoreCallingIdentity(identity);
5508        }
5509    }
5510
5511    /**
5512     * Compares two sets of signatures. Returns:
5513     * <br />
5514     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5515     * <br />
5516     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5517     * <br />
5518     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5519     * <br />
5520     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5521     * <br />
5522     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5523     */
5524    static int compareSignatures(Signature[] s1, Signature[] s2) {
5525        if (s1 == null) {
5526            return s2 == null
5527                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5528                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5529        }
5530
5531        if (s2 == null) {
5532            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5533        }
5534
5535        if (s1.length != s2.length) {
5536            return PackageManager.SIGNATURE_NO_MATCH;
5537        }
5538
5539        // Since both signature sets are of size 1, we can compare without HashSets.
5540        if (s1.length == 1) {
5541            return s1[0].equals(s2[0]) ?
5542                    PackageManager.SIGNATURE_MATCH :
5543                    PackageManager.SIGNATURE_NO_MATCH;
5544        }
5545
5546        ArraySet<Signature> set1 = new ArraySet<Signature>();
5547        for (Signature sig : s1) {
5548            set1.add(sig);
5549        }
5550        ArraySet<Signature> set2 = new ArraySet<Signature>();
5551        for (Signature sig : s2) {
5552            set2.add(sig);
5553        }
5554        // Make sure s2 contains all signatures in s1.
5555        if (set1.equals(set2)) {
5556            return PackageManager.SIGNATURE_MATCH;
5557        }
5558        return PackageManager.SIGNATURE_NO_MATCH;
5559    }
5560
5561    /**
5562     * If the database version for this type of package (internal storage or
5563     * external storage) is less than the version where package signatures
5564     * were updated, return true.
5565     */
5566    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5567        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5568        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5569    }
5570
5571    /**
5572     * Used for backward compatibility to make sure any packages with
5573     * certificate chains get upgraded to the new style. {@code existingSigs}
5574     * will be in the old format (since they were stored on disk from before the
5575     * system upgrade) and {@code scannedSigs} will be in the newer format.
5576     */
5577    private int compareSignaturesCompat(PackageSignatures existingSigs,
5578            PackageParser.Package scannedPkg) {
5579        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5580            return PackageManager.SIGNATURE_NO_MATCH;
5581        }
5582
5583        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5584        for (Signature sig : existingSigs.mSignatures) {
5585            existingSet.add(sig);
5586        }
5587        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5588        for (Signature sig : scannedPkg.mSignatures) {
5589            try {
5590                Signature[] chainSignatures = sig.getChainSignatures();
5591                for (Signature chainSig : chainSignatures) {
5592                    scannedCompatSet.add(chainSig);
5593                }
5594            } catch (CertificateEncodingException e) {
5595                scannedCompatSet.add(sig);
5596            }
5597        }
5598        /*
5599         * Make sure the expanded scanned set contains all signatures in the
5600         * existing one.
5601         */
5602        if (scannedCompatSet.equals(existingSet)) {
5603            // Migrate the old signatures to the new scheme.
5604            existingSigs.assignSignatures(scannedPkg.mSignatures);
5605            // The new KeySets will be re-added later in the scanning process.
5606            synchronized (mPackages) {
5607                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5608            }
5609            return PackageManager.SIGNATURE_MATCH;
5610        }
5611        return PackageManager.SIGNATURE_NO_MATCH;
5612    }
5613
5614    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5615        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5616        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5617    }
5618
5619    private int compareSignaturesRecover(PackageSignatures existingSigs,
5620            PackageParser.Package scannedPkg) {
5621        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5622            return PackageManager.SIGNATURE_NO_MATCH;
5623        }
5624
5625        String msg = null;
5626        try {
5627            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5628                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5629                        + scannedPkg.packageName);
5630                return PackageManager.SIGNATURE_MATCH;
5631            }
5632        } catch (CertificateException e) {
5633            msg = e.getMessage();
5634        }
5635
5636        logCriticalInfo(Log.INFO,
5637                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5638        return PackageManager.SIGNATURE_NO_MATCH;
5639    }
5640
5641    @Override
5642    public List<String> getAllPackages() {
5643        synchronized (mPackages) {
5644            return new ArrayList<String>(mPackages.keySet());
5645        }
5646    }
5647
5648    @Override
5649    public String[] getPackagesForUid(int uid) {
5650        final int userId = UserHandle.getUserId(uid);
5651        uid = UserHandle.getAppId(uid);
5652        // reader
5653        synchronized (mPackages) {
5654            Object obj = mSettings.getUserIdLPr(uid);
5655            if (obj instanceof SharedUserSetting) {
5656                final SharedUserSetting sus = (SharedUserSetting) obj;
5657                final int N = sus.packages.size();
5658                String[] res = new String[N];
5659                final Iterator<PackageSetting> it = sus.packages.iterator();
5660                int i = 0;
5661                while (it.hasNext()) {
5662                    PackageSetting ps = it.next();
5663                    if (ps.getInstalled(userId)) {
5664                        res[i++] = ps.name;
5665                    } else {
5666                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5667                    }
5668                }
5669                return res;
5670            } else if (obj instanceof PackageSetting) {
5671                final PackageSetting ps = (PackageSetting) obj;
5672                if (ps.getInstalled(userId)) {
5673                    return new String[]{ps.name};
5674                }
5675            }
5676        }
5677        return null;
5678    }
5679
5680    @Override
5681    public String getNameForUid(int uid) {
5682        // reader
5683        synchronized (mPackages) {
5684            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5685            if (obj instanceof SharedUserSetting) {
5686                final SharedUserSetting sus = (SharedUserSetting) obj;
5687                return sus.name + ":" + sus.userId;
5688            } else if (obj instanceof PackageSetting) {
5689                final PackageSetting ps = (PackageSetting) obj;
5690                return ps.name;
5691            }
5692        }
5693        return null;
5694    }
5695
5696    @Override
5697    public int getUidForSharedUser(String sharedUserName) {
5698        if(sharedUserName == null) {
5699            return -1;
5700        }
5701        // reader
5702        synchronized (mPackages) {
5703            SharedUserSetting suid;
5704            try {
5705                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5706                if (suid != null) {
5707                    return suid.userId;
5708                }
5709            } catch (PackageManagerException ignore) {
5710                // can't happen, but, still need to catch it
5711            }
5712            return -1;
5713        }
5714    }
5715
5716    @Override
5717    public int getFlagsForUid(int uid) {
5718        synchronized (mPackages) {
5719            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5720            if (obj instanceof SharedUserSetting) {
5721                final SharedUserSetting sus = (SharedUserSetting) obj;
5722                return sus.pkgFlags;
5723            } else if (obj instanceof PackageSetting) {
5724                final PackageSetting ps = (PackageSetting) obj;
5725                return ps.pkgFlags;
5726            }
5727        }
5728        return 0;
5729    }
5730
5731    @Override
5732    public int getPrivateFlagsForUid(int uid) {
5733        synchronized (mPackages) {
5734            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5735            if (obj instanceof SharedUserSetting) {
5736                final SharedUserSetting sus = (SharedUserSetting) obj;
5737                return sus.pkgPrivateFlags;
5738            } else if (obj instanceof PackageSetting) {
5739                final PackageSetting ps = (PackageSetting) obj;
5740                return ps.pkgPrivateFlags;
5741            }
5742        }
5743        return 0;
5744    }
5745
5746    @Override
5747    public boolean isUidPrivileged(int uid) {
5748        uid = UserHandle.getAppId(uid);
5749        // reader
5750        synchronized (mPackages) {
5751            Object obj = mSettings.getUserIdLPr(uid);
5752            if (obj instanceof SharedUserSetting) {
5753                final SharedUserSetting sus = (SharedUserSetting) obj;
5754                final Iterator<PackageSetting> it = sus.packages.iterator();
5755                while (it.hasNext()) {
5756                    if (it.next().isPrivileged()) {
5757                        return true;
5758                    }
5759                }
5760            } else if (obj instanceof PackageSetting) {
5761                final PackageSetting ps = (PackageSetting) obj;
5762                return ps.isPrivileged();
5763            }
5764        }
5765        return false;
5766    }
5767
5768    @Override
5769    public String[] getAppOpPermissionPackages(String permissionName) {
5770        synchronized (mPackages) {
5771            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5772            if (pkgs == null) {
5773                return null;
5774            }
5775            return pkgs.toArray(new String[pkgs.size()]);
5776        }
5777    }
5778
5779    @Override
5780    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5781            int flags, int userId) {
5782        return resolveIntentInternal(
5783                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
5784    }
5785
5786    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5787            int flags, int userId, boolean resolveForStart) {
5788        try {
5789            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5790
5791            if (!sUserManager.exists(userId)) return null;
5792            final int callingUid = Binder.getCallingUid();
5793            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5794            enforceCrossUserPermission(callingUid, userId,
5795                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5796
5797            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5798            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5799                    flags, userId, resolveForStart);
5800            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5801
5802            final ResolveInfo bestChoice =
5803                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5804            return bestChoice;
5805        } finally {
5806            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5807        }
5808    }
5809
5810    @Override
5811    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5812        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5813            throw new SecurityException(
5814                    "findPersistentPreferredActivity can only be run by the system");
5815        }
5816        if (!sUserManager.exists(userId)) {
5817            return null;
5818        }
5819        final int callingUid = Binder.getCallingUid();
5820        intent = updateIntentForResolve(intent);
5821        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5822        final int flags = updateFlagsForResolve(
5823                0, userId, intent, callingUid, false /*includeInstantApps*/);
5824        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5825                userId);
5826        synchronized (mPackages) {
5827            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5828                    userId);
5829        }
5830    }
5831
5832    @Override
5833    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5834            IntentFilter filter, int match, ComponentName activity) {
5835        final int userId = UserHandle.getCallingUserId();
5836        if (DEBUG_PREFERRED) {
5837            Log.v(TAG, "setLastChosenActivity intent=" + intent
5838                + " resolvedType=" + resolvedType
5839                + " flags=" + flags
5840                + " filter=" + filter
5841                + " match=" + match
5842                + " activity=" + activity);
5843            filter.dump(new PrintStreamPrinter(System.out), "    ");
5844        }
5845        intent.setComponent(null);
5846        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5847                userId);
5848        // Find any earlier preferred or last chosen entries and nuke them
5849        findPreferredActivity(intent, resolvedType,
5850                flags, query, 0, false, true, false, userId);
5851        // Add the new activity as the last chosen for this filter
5852        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5853                "Setting last chosen");
5854    }
5855
5856    @Override
5857    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5858        final int userId = UserHandle.getCallingUserId();
5859        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5860        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5861                userId);
5862        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5863                false, false, false, userId);
5864    }
5865
5866    /**
5867     * Returns whether or not instant apps have been disabled remotely.
5868     */
5869    private boolean isEphemeralDisabled() {
5870        return mEphemeralAppsDisabled;
5871    }
5872
5873    private boolean isInstantAppAllowed(
5874            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5875            boolean skipPackageCheck) {
5876        if (mInstantAppResolverConnection == null) {
5877            return false;
5878        }
5879        if (mInstantAppInstallerActivity == null) {
5880            return false;
5881        }
5882        if (intent.getComponent() != null) {
5883            return false;
5884        }
5885        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5886            return false;
5887        }
5888        if (!skipPackageCheck && intent.getPackage() != null) {
5889            return false;
5890        }
5891        final boolean isWebUri = hasWebURI(intent);
5892        if (!isWebUri || intent.getData().getHost() == null) {
5893            return false;
5894        }
5895        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5896        // Or if there's already an ephemeral app installed that handles the action
5897        synchronized (mPackages) {
5898            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5899            for (int n = 0; n < count; n++) {
5900                final ResolveInfo info = resolvedActivities.get(n);
5901                final String packageName = info.activityInfo.packageName;
5902                final PackageSetting ps = mSettings.mPackages.get(packageName);
5903                if (ps != null) {
5904                    // only check domain verification status if the app is not a browser
5905                    if (!info.handleAllWebDataURI) {
5906                        // Try to get the status from User settings first
5907                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5908                        final int status = (int) (packedStatus >> 32);
5909                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5910                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5911                            if (DEBUG_EPHEMERAL) {
5912                                Slog.v(TAG, "DENY instant app;"
5913                                    + " pkg: " + packageName + ", status: " + status);
5914                            }
5915                            return false;
5916                        }
5917                    }
5918                    if (ps.getInstantApp(userId)) {
5919                        if (DEBUG_EPHEMERAL) {
5920                            Slog.v(TAG, "DENY instant app installed;"
5921                                    + " pkg: " + packageName);
5922                        }
5923                        return false;
5924                    }
5925                }
5926            }
5927        }
5928        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5929        return true;
5930    }
5931
5932    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5933            Intent origIntent, String resolvedType, String callingPackage,
5934            Bundle verificationBundle, int userId) {
5935        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5936                new InstantAppRequest(responseObj, origIntent, resolvedType,
5937                        callingPackage, userId, verificationBundle));
5938        mHandler.sendMessage(msg);
5939    }
5940
5941    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5942            int flags, List<ResolveInfo> query, int userId) {
5943        if (query != null) {
5944            final int N = query.size();
5945            if (N == 1) {
5946                return query.get(0);
5947            } else if (N > 1) {
5948                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5949                // If there is more than one activity with the same priority,
5950                // then let the user decide between them.
5951                ResolveInfo r0 = query.get(0);
5952                ResolveInfo r1 = query.get(1);
5953                if (DEBUG_INTENT_MATCHING || debug) {
5954                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5955                            + r1.activityInfo.name + "=" + r1.priority);
5956                }
5957                // If the first activity has a higher priority, or a different
5958                // default, then it is always desirable to pick it.
5959                if (r0.priority != r1.priority
5960                        || r0.preferredOrder != r1.preferredOrder
5961                        || r0.isDefault != r1.isDefault) {
5962                    return query.get(0);
5963                }
5964                // If we have saved a preference for a preferred activity for
5965                // this Intent, use that.
5966                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5967                        flags, query, r0.priority, true, false, debug, userId);
5968                if (ri != null) {
5969                    return ri;
5970                }
5971                // If we have an ephemeral app, use it
5972                for (int i = 0; i < N; i++) {
5973                    ri = query.get(i);
5974                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5975                        final String packageName = ri.activityInfo.packageName;
5976                        final PackageSetting ps = mSettings.mPackages.get(packageName);
5977                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5978                        final int status = (int)(packedStatus >> 32);
5979                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5980                            return ri;
5981                        }
5982                    }
5983                }
5984                ri = new ResolveInfo(mResolveInfo);
5985                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5986                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5987                // If all of the options come from the same package, show the application's
5988                // label and icon instead of the generic resolver's.
5989                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5990                // and then throw away the ResolveInfo itself, meaning that the caller loses
5991                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5992                // a fallback for this case; we only set the target package's resources on
5993                // the ResolveInfo, not the ActivityInfo.
5994                final String intentPackage = intent.getPackage();
5995                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5996                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5997                    ri.resolvePackageName = intentPackage;
5998                    if (userNeedsBadging(userId)) {
5999                        ri.noResourceId = true;
6000                    } else {
6001                        ri.icon = appi.icon;
6002                    }
6003                    ri.iconResourceId = appi.icon;
6004                    ri.labelRes = appi.labelRes;
6005                }
6006                ri.activityInfo.applicationInfo = new ApplicationInfo(
6007                        ri.activityInfo.applicationInfo);
6008                if (userId != 0) {
6009                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6010                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6011                }
6012                // Make sure that the resolver is displayable in car mode
6013                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6014                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6015                return ri;
6016            }
6017        }
6018        return null;
6019    }
6020
6021    /**
6022     * Return true if the given list is not empty and all of its contents have
6023     * an activityInfo with the given package name.
6024     */
6025    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6026        if (ArrayUtils.isEmpty(list)) {
6027            return false;
6028        }
6029        for (int i = 0, N = list.size(); i < N; i++) {
6030            final ResolveInfo ri = list.get(i);
6031            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6032            if (ai == null || !packageName.equals(ai.packageName)) {
6033                return false;
6034            }
6035        }
6036        return true;
6037    }
6038
6039    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6040            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6041        final int N = query.size();
6042        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6043                .get(userId);
6044        // Get the list of persistent preferred activities that handle the intent
6045        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6046        List<PersistentPreferredActivity> pprefs = ppir != null
6047                ? ppir.queryIntent(intent, resolvedType,
6048                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6049                        userId)
6050                : null;
6051        if (pprefs != null && pprefs.size() > 0) {
6052            final int M = pprefs.size();
6053            for (int i=0; i<M; i++) {
6054                final PersistentPreferredActivity ppa = pprefs.get(i);
6055                if (DEBUG_PREFERRED || debug) {
6056                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6057                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6058                            + "\n  component=" + ppa.mComponent);
6059                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6060                }
6061                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6062                        flags | MATCH_DISABLED_COMPONENTS, userId);
6063                if (DEBUG_PREFERRED || debug) {
6064                    Slog.v(TAG, "Found persistent preferred activity:");
6065                    if (ai != null) {
6066                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6067                    } else {
6068                        Slog.v(TAG, "  null");
6069                    }
6070                }
6071                if (ai == null) {
6072                    // This previously registered persistent preferred activity
6073                    // component is no longer known. Ignore it and do NOT remove it.
6074                    continue;
6075                }
6076                for (int j=0; j<N; j++) {
6077                    final ResolveInfo ri = query.get(j);
6078                    if (!ri.activityInfo.applicationInfo.packageName
6079                            .equals(ai.applicationInfo.packageName)) {
6080                        continue;
6081                    }
6082                    if (!ri.activityInfo.name.equals(ai.name)) {
6083                        continue;
6084                    }
6085                    //  Found a persistent preference that can handle the intent.
6086                    if (DEBUG_PREFERRED || debug) {
6087                        Slog.v(TAG, "Returning persistent preferred activity: " +
6088                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6089                    }
6090                    return ri;
6091                }
6092            }
6093        }
6094        return null;
6095    }
6096
6097    // TODO: handle preferred activities missing while user has amnesia
6098    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6099            List<ResolveInfo> query, int priority, boolean always,
6100            boolean removeMatches, boolean debug, int userId) {
6101        if (!sUserManager.exists(userId)) return null;
6102        final int callingUid = Binder.getCallingUid();
6103        flags = updateFlagsForResolve(
6104                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6105        intent = updateIntentForResolve(intent);
6106        // writer
6107        synchronized (mPackages) {
6108            // Try to find a matching persistent preferred activity.
6109            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6110                    debug, userId);
6111
6112            // If a persistent preferred activity matched, use it.
6113            if (pri != null) {
6114                return pri;
6115            }
6116
6117            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6118            // Get the list of preferred activities that handle the intent
6119            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6120            List<PreferredActivity> prefs = pir != null
6121                    ? pir.queryIntent(intent, resolvedType,
6122                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6123                            userId)
6124                    : null;
6125            if (prefs != null && prefs.size() > 0) {
6126                boolean changed = false;
6127                try {
6128                    // First figure out how good the original match set is.
6129                    // We will only allow preferred activities that came
6130                    // from the same match quality.
6131                    int match = 0;
6132
6133                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6134
6135                    final int N = query.size();
6136                    for (int j=0; j<N; j++) {
6137                        final ResolveInfo ri = query.get(j);
6138                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6139                                + ": 0x" + Integer.toHexString(match));
6140                        if (ri.match > match) {
6141                            match = ri.match;
6142                        }
6143                    }
6144
6145                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6146                            + Integer.toHexString(match));
6147
6148                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6149                    final int M = prefs.size();
6150                    for (int i=0; i<M; i++) {
6151                        final PreferredActivity pa = prefs.get(i);
6152                        if (DEBUG_PREFERRED || debug) {
6153                            Slog.v(TAG, "Checking PreferredActivity ds="
6154                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6155                                    + "\n  component=" + pa.mPref.mComponent);
6156                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6157                        }
6158                        if (pa.mPref.mMatch != match) {
6159                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6160                                    + Integer.toHexString(pa.mPref.mMatch));
6161                            continue;
6162                        }
6163                        // If it's not an "always" type preferred activity and that's what we're
6164                        // looking for, skip it.
6165                        if (always && !pa.mPref.mAlways) {
6166                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6167                            continue;
6168                        }
6169                        final ActivityInfo ai = getActivityInfo(
6170                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6171                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6172                                userId);
6173                        if (DEBUG_PREFERRED || debug) {
6174                            Slog.v(TAG, "Found preferred activity:");
6175                            if (ai != null) {
6176                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6177                            } else {
6178                                Slog.v(TAG, "  null");
6179                            }
6180                        }
6181                        if (ai == null) {
6182                            // This previously registered preferred activity
6183                            // component is no longer known.  Most likely an update
6184                            // to the app was installed and in the new version this
6185                            // component no longer exists.  Clean it up by removing
6186                            // it from the preferred activities list, and skip it.
6187                            Slog.w(TAG, "Removing dangling preferred activity: "
6188                                    + pa.mPref.mComponent);
6189                            pir.removeFilter(pa);
6190                            changed = true;
6191                            continue;
6192                        }
6193                        for (int j=0; j<N; j++) {
6194                            final ResolveInfo ri = query.get(j);
6195                            if (!ri.activityInfo.applicationInfo.packageName
6196                                    .equals(ai.applicationInfo.packageName)) {
6197                                continue;
6198                            }
6199                            if (!ri.activityInfo.name.equals(ai.name)) {
6200                                continue;
6201                            }
6202
6203                            if (removeMatches) {
6204                                pir.removeFilter(pa);
6205                                changed = true;
6206                                if (DEBUG_PREFERRED) {
6207                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6208                                }
6209                                break;
6210                            }
6211
6212                            // Okay we found a previously set preferred or last chosen app.
6213                            // If the result set is different from when this
6214                            // was created, we need to clear it and re-ask the
6215                            // user their preference, if we're looking for an "always" type entry.
6216                            if (always && !pa.mPref.sameSet(query)) {
6217                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6218                                        + intent + " type " + resolvedType);
6219                                if (DEBUG_PREFERRED) {
6220                                    Slog.v(TAG, "Removing preferred activity since set changed "
6221                                            + pa.mPref.mComponent);
6222                                }
6223                                pir.removeFilter(pa);
6224                                // Re-add the filter as a "last chosen" entry (!always)
6225                                PreferredActivity lastChosen = new PreferredActivity(
6226                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6227                                pir.addFilter(lastChosen);
6228                                changed = true;
6229                                return null;
6230                            }
6231
6232                            // Yay! Either the set matched or we're looking for the last chosen
6233                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6234                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6235                            return ri;
6236                        }
6237                    }
6238                } finally {
6239                    if (changed) {
6240                        if (DEBUG_PREFERRED) {
6241                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6242                        }
6243                        scheduleWritePackageRestrictionsLocked(userId);
6244                    }
6245                }
6246            }
6247        }
6248        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6249        return null;
6250    }
6251
6252    /*
6253     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6254     */
6255    @Override
6256    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6257            int targetUserId) {
6258        mContext.enforceCallingOrSelfPermission(
6259                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6260        List<CrossProfileIntentFilter> matches =
6261                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6262        if (matches != null) {
6263            int size = matches.size();
6264            for (int i = 0; i < size; i++) {
6265                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6266            }
6267        }
6268        if (hasWebURI(intent)) {
6269            // cross-profile app linking works only towards the parent.
6270            final int callingUid = Binder.getCallingUid();
6271            final UserInfo parent = getProfileParent(sourceUserId);
6272            synchronized(mPackages) {
6273                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6274                        false /*includeInstantApps*/);
6275                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6276                        intent, resolvedType, flags, sourceUserId, parent.id);
6277                return xpDomainInfo != null;
6278            }
6279        }
6280        return false;
6281    }
6282
6283    private UserInfo getProfileParent(int userId) {
6284        final long identity = Binder.clearCallingIdentity();
6285        try {
6286            return sUserManager.getProfileParent(userId);
6287        } finally {
6288            Binder.restoreCallingIdentity(identity);
6289        }
6290    }
6291
6292    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6293            String resolvedType, int userId) {
6294        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6295        if (resolver != null) {
6296            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6297        }
6298        return null;
6299    }
6300
6301    @Override
6302    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6303            String resolvedType, int flags, int userId) {
6304        try {
6305            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6306
6307            return new ParceledListSlice<>(
6308                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6309        } finally {
6310            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6311        }
6312    }
6313
6314    /**
6315     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6316     * instant, returns {@code null}.
6317     */
6318    private String getInstantAppPackageName(int callingUid) {
6319        // If the caller is an isolated app use the owner's uid for the lookup.
6320        if (Process.isIsolated(callingUid)) {
6321            callingUid = mIsolatedOwners.get(callingUid);
6322        }
6323        final int appId = UserHandle.getAppId(callingUid);
6324        synchronized (mPackages) {
6325            final Object obj = mSettings.getUserIdLPr(appId);
6326            if (obj instanceof PackageSetting) {
6327                final PackageSetting ps = (PackageSetting) obj;
6328                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6329                return isInstantApp ? ps.pkg.packageName : null;
6330            }
6331        }
6332        return null;
6333    }
6334
6335    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6336            String resolvedType, int flags, int userId) {
6337        return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false);
6338    }
6339
6340    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6341            String resolvedType, int flags, int userId, boolean resolveForStart) {
6342        if (!sUserManager.exists(userId)) return Collections.emptyList();
6343        final int callingUid = Binder.getCallingUid();
6344        final String instantAppPkgName = getInstantAppPackageName(callingUid);
6345        enforceCrossUserPermission(callingUid, userId,
6346                false /* requireFullPermission */, false /* checkShell */,
6347                "query intent activities");
6348        final String pkgName = intent.getPackage();
6349        ComponentName comp = intent.getComponent();
6350        if (comp == null) {
6351            if (intent.getSelector() != null) {
6352                intent = intent.getSelector();
6353                comp = intent.getComponent();
6354            }
6355        }
6356
6357        flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart,
6358                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6359        if (comp != null) {
6360            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6361            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6362            if (ai != null) {
6363                // When specifying an explicit component, we prevent the activity from being
6364                // used when either 1) the calling package is normal and the activity is within
6365                // an ephemeral application or 2) the calling package is ephemeral and the
6366                // activity is not visible to ephemeral applications.
6367                final boolean matchInstantApp =
6368                        (flags & PackageManager.MATCH_INSTANT) != 0;
6369                final boolean matchVisibleToInstantAppOnly =
6370                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6371                final boolean matchExplicitlyVisibleOnly =
6372                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6373                final boolean isCallerInstantApp =
6374                        instantAppPkgName != null;
6375                final boolean isTargetSameInstantApp =
6376                        comp.getPackageName().equals(instantAppPkgName);
6377                final boolean isTargetInstantApp =
6378                        (ai.applicationInfo.privateFlags
6379                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6380                final boolean isTargetVisibleToInstantApp =
6381                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6382                final boolean isTargetExplicitlyVisibleToInstantApp =
6383                        isTargetVisibleToInstantApp
6384                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6385                final boolean isTargetHiddenFromInstantApp =
6386                        !isTargetVisibleToInstantApp
6387                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6388                final boolean blockResolution =
6389                        !isTargetSameInstantApp
6390                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6391                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6392                                        && isTargetHiddenFromInstantApp));
6393                if (!blockResolution) {
6394                    final ResolveInfo ri = new ResolveInfo();
6395                    ri.activityInfo = ai;
6396                    list.add(ri);
6397                }
6398            }
6399            return applyPostResolutionFilter(list, instantAppPkgName);
6400        }
6401
6402        // reader
6403        boolean sortResult = false;
6404        boolean addEphemeral = false;
6405        List<ResolveInfo> result;
6406        final boolean ephemeralDisabled = isEphemeralDisabled();
6407        synchronized (mPackages) {
6408            if (pkgName == null) {
6409                List<CrossProfileIntentFilter> matchingFilters =
6410                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6411                // Check for results that need to skip the current profile.
6412                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6413                        resolvedType, flags, userId);
6414                if (xpResolveInfo != null) {
6415                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6416                    xpResult.add(xpResolveInfo);
6417                    return applyPostResolutionFilter(
6418                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6419                }
6420
6421                // Check for results in the current profile.
6422                result = filterIfNotSystemUser(mActivities.queryIntent(
6423                        intent, resolvedType, flags, userId), userId);
6424                addEphemeral = !ephemeralDisabled
6425                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6426                // Check for cross profile results.
6427                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6428                xpResolveInfo = queryCrossProfileIntents(
6429                        matchingFilters, intent, resolvedType, flags, userId,
6430                        hasNonNegativePriorityResult);
6431                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6432                    boolean isVisibleToUser = filterIfNotSystemUser(
6433                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6434                    if (isVisibleToUser) {
6435                        result.add(xpResolveInfo);
6436                        sortResult = true;
6437                    }
6438                }
6439                if (hasWebURI(intent)) {
6440                    CrossProfileDomainInfo xpDomainInfo = null;
6441                    final UserInfo parent = getProfileParent(userId);
6442                    if (parent != null) {
6443                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6444                                flags, userId, parent.id);
6445                    }
6446                    if (xpDomainInfo != null) {
6447                        if (xpResolveInfo != null) {
6448                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6449                            // in the result.
6450                            result.remove(xpResolveInfo);
6451                        }
6452                        if (result.size() == 0 && !addEphemeral) {
6453                            // No result in current profile, but found candidate in parent user.
6454                            // And we are not going to add emphemeral app, so we can return the
6455                            // result straight away.
6456                            result.add(xpDomainInfo.resolveInfo);
6457                            return applyPostResolutionFilter(result, instantAppPkgName);
6458                        }
6459                    } else if (result.size() <= 1 && !addEphemeral) {
6460                        // No result in parent user and <= 1 result in current profile, and we
6461                        // are not going to add emphemeral app, so we can return the result without
6462                        // further processing.
6463                        return applyPostResolutionFilter(result, instantAppPkgName);
6464                    }
6465                    // We have more than one candidate (combining results from current and parent
6466                    // profile), so we need filtering and sorting.
6467                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6468                            intent, flags, result, xpDomainInfo, userId);
6469                    sortResult = true;
6470                }
6471            } else {
6472                final PackageParser.Package pkg = mPackages.get(pkgName);
6473                if (pkg != null) {
6474                    return applyPostResolutionFilter(filterIfNotSystemUser(
6475                            mActivities.queryIntentForPackage(
6476                                    intent, resolvedType, flags, pkg.activities, userId),
6477                            userId), instantAppPkgName);
6478                } else {
6479                    // the caller wants to resolve for a particular package; however, there
6480                    // were no installed results, so, try to find an ephemeral result
6481                    addEphemeral = !ephemeralDisabled
6482                            && isInstantAppAllowed(
6483                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6484                    result = new ArrayList<ResolveInfo>();
6485                }
6486            }
6487        }
6488        if (addEphemeral) {
6489            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
6490        }
6491        if (sortResult) {
6492            Collections.sort(result, mResolvePrioritySorter);
6493        }
6494        return applyPostResolutionFilter(result, instantAppPkgName);
6495    }
6496
6497    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6498            String resolvedType, int flags, int userId) {
6499        // first, check to see if we've got an instant app already installed
6500        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6501        boolean localInstantAppAvailable = false;
6502        boolean blockResolution = false;
6503        if (!alreadyResolvedLocally) {
6504            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6505                    flags
6506                        | PackageManager.MATCH_INSTANT
6507                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6508                    userId);
6509            for (int i = instantApps.size() - 1; i >= 0; --i) {
6510                final ResolveInfo info = instantApps.get(i);
6511                final String packageName = info.activityInfo.packageName;
6512                final PackageSetting ps = mSettings.mPackages.get(packageName);
6513                if (ps.getInstantApp(userId)) {
6514                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6515                    final int status = (int)(packedStatus >> 32);
6516                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6517                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6518                        // there's a local instant application installed, but, the user has
6519                        // chosen to never use it; skip resolution and don't acknowledge
6520                        // an instant application is even available
6521                        if (DEBUG_EPHEMERAL) {
6522                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6523                        }
6524                        blockResolution = true;
6525                        break;
6526                    } else {
6527                        // we have a locally installed instant application; skip resolution
6528                        // but acknowledge there's an instant application available
6529                        if (DEBUG_EPHEMERAL) {
6530                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6531                        }
6532                        localInstantAppAvailable = true;
6533                        break;
6534                    }
6535                }
6536            }
6537        }
6538        // no app installed, let's see if one's available
6539        AuxiliaryResolveInfo auxiliaryResponse = null;
6540        if (!localInstantAppAvailable && !blockResolution) {
6541            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6542            final InstantAppRequest requestObject = new InstantAppRequest(
6543                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
6544                    null /*callingPackage*/, userId, null /*verificationBundle*/);
6545            auxiliaryResponse =
6546                    InstantAppResolver.doInstantAppResolutionPhaseOne(
6547                            mContext, mInstantAppResolverConnection, requestObject);
6548            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6549        }
6550        if (localInstantAppAvailable || auxiliaryResponse != null) {
6551            if (DEBUG_EPHEMERAL) {
6552                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6553            }
6554            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6555            final PackageSetting ps =
6556                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6557            if (ps != null) {
6558                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6559                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6560                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6561                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6562                // make sure this resolver is the default
6563                ephemeralInstaller.isDefault = true;
6564                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6565                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6566                // add a non-generic filter
6567                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6568                ephemeralInstaller.filter.addDataPath(
6569                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6570                ephemeralInstaller.instantAppAvailable = true;
6571                result.add(ephemeralInstaller);
6572            }
6573        }
6574        return result;
6575    }
6576
6577    private static class CrossProfileDomainInfo {
6578        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6579        ResolveInfo resolveInfo;
6580        /* Best domain verification status of the activities found in the other profile */
6581        int bestDomainVerificationStatus;
6582    }
6583
6584    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6585            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6586        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6587                sourceUserId)) {
6588            return null;
6589        }
6590        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6591                resolvedType, flags, parentUserId);
6592
6593        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6594            return null;
6595        }
6596        CrossProfileDomainInfo result = null;
6597        int size = resultTargetUser.size();
6598        for (int i = 0; i < size; i++) {
6599            ResolveInfo riTargetUser = resultTargetUser.get(i);
6600            // Intent filter verification is only for filters that specify a host. So don't return
6601            // those that handle all web uris.
6602            if (riTargetUser.handleAllWebDataURI) {
6603                continue;
6604            }
6605            String packageName = riTargetUser.activityInfo.packageName;
6606            PackageSetting ps = mSettings.mPackages.get(packageName);
6607            if (ps == null) {
6608                continue;
6609            }
6610            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6611            int status = (int)(verificationState >> 32);
6612            if (result == null) {
6613                result = new CrossProfileDomainInfo();
6614                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6615                        sourceUserId, parentUserId);
6616                result.bestDomainVerificationStatus = status;
6617            } else {
6618                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6619                        result.bestDomainVerificationStatus);
6620            }
6621        }
6622        // Don't consider matches with status NEVER across profiles.
6623        if (result != null && result.bestDomainVerificationStatus
6624                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6625            return null;
6626        }
6627        return result;
6628    }
6629
6630    /**
6631     * Verification statuses are ordered from the worse to the best, except for
6632     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6633     */
6634    private int bestDomainVerificationStatus(int status1, int status2) {
6635        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6636            return status2;
6637        }
6638        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6639            return status1;
6640        }
6641        return (int) MathUtils.max(status1, status2);
6642    }
6643
6644    private boolean isUserEnabled(int userId) {
6645        long callingId = Binder.clearCallingIdentity();
6646        try {
6647            UserInfo userInfo = sUserManager.getUserInfo(userId);
6648            return userInfo != null && userInfo.isEnabled();
6649        } finally {
6650            Binder.restoreCallingIdentity(callingId);
6651        }
6652    }
6653
6654    /**
6655     * Filter out activities with systemUserOnly flag set, when current user is not System.
6656     *
6657     * @return filtered list
6658     */
6659    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6660        if (userId == UserHandle.USER_SYSTEM) {
6661            return resolveInfos;
6662        }
6663        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6664            ResolveInfo info = resolveInfos.get(i);
6665            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6666                resolveInfos.remove(i);
6667            }
6668        }
6669        return resolveInfos;
6670    }
6671
6672    /**
6673     * Filters out ephemeral activities.
6674     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6675     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6676     *
6677     * @param resolveInfos The pre-filtered list of resolved activities
6678     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6679     *          is performed.
6680     * @return A filtered list of resolved activities.
6681     */
6682    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6683            String ephemeralPkgName) {
6684        // TODO: When adding on-demand split support for non-instant apps, remove this check
6685        // and always apply post filtering
6686        if (ephemeralPkgName == null) {
6687            return resolveInfos;
6688        }
6689        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6690            final ResolveInfo info = resolveInfos.get(i);
6691            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6692            // allow activities that are defined in the provided package
6693            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6694                if (info.activityInfo.splitName != null
6695                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6696                                info.activityInfo.splitName)) {
6697                    // requested activity is defined in a split that hasn't been installed yet.
6698                    // add the installer to the resolve list
6699                    if (DEBUG_EPHEMERAL) {
6700                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6701                    }
6702                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6703                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6704                            info.activityInfo.packageName, info.activityInfo.splitName,
6705                            info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
6706                    // make sure this resolver is the default
6707                    installerInfo.isDefault = true;
6708                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6709                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6710                    // add a non-generic filter
6711                    installerInfo.filter = new IntentFilter();
6712                    // load resources from the correct package
6713                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6714                    resolveInfos.set(i, installerInfo);
6715                }
6716                continue;
6717            }
6718            // allow activities that have been explicitly exposed to ephemeral apps
6719            if (!isEphemeralApp
6720                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6721                continue;
6722            }
6723            resolveInfos.remove(i);
6724        }
6725        return resolveInfos;
6726    }
6727
6728    /**
6729     * @param resolveInfos list of resolve infos in descending priority order
6730     * @return if the list contains a resolve info with non-negative priority
6731     */
6732    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6733        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6734    }
6735
6736    private static boolean hasWebURI(Intent intent) {
6737        if (intent.getData() == null) {
6738            return false;
6739        }
6740        final String scheme = intent.getScheme();
6741        if (TextUtils.isEmpty(scheme)) {
6742            return false;
6743        }
6744        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6745    }
6746
6747    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6748            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6749            int userId) {
6750        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6751
6752        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6753            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6754                    candidates.size());
6755        }
6756
6757        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6758        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6759        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6760        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6761        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6762        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6763
6764        synchronized (mPackages) {
6765            final int count = candidates.size();
6766            // First, try to use linked apps. Partition the candidates into four lists:
6767            // one for the final results, one for the "do not use ever", one for "undefined status"
6768            // and finally one for "browser app type".
6769            for (int n=0; n<count; n++) {
6770                ResolveInfo info = candidates.get(n);
6771                String packageName = info.activityInfo.packageName;
6772                PackageSetting ps = mSettings.mPackages.get(packageName);
6773                if (ps != null) {
6774                    // Add to the special match all list (Browser use case)
6775                    if (info.handleAllWebDataURI) {
6776                        matchAllList.add(info);
6777                        continue;
6778                    }
6779                    // Try to get the status from User settings first
6780                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6781                    int status = (int)(packedStatus >> 32);
6782                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6783                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6784                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6785                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6786                                    + " : linkgen=" + linkGeneration);
6787                        }
6788                        // Use link-enabled generation as preferredOrder, i.e.
6789                        // prefer newly-enabled over earlier-enabled.
6790                        info.preferredOrder = linkGeneration;
6791                        alwaysList.add(info);
6792                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6793                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6794                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6795                        }
6796                        neverList.add(info);
6797                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6798                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6799                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6800                        }
6801                        alwaysAskList.add(info);
6802                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6803                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6804                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6805                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6806                        }
6807                        undefinedList.add(info);
6808                    }
6809                }
6810            }
6811
6812            // We'll want to include browser possibilities in a few cases
6813            boolean includeBrowser = false;
6814
6815            // First try to add the "always" resolution(s) for the current user, if any
6816            if (alwaysList.size() > 0) {
6817                result.addAll(alwaysList);
6818            } else {
6819                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6820                result.addAll(undefinedList);
6821                // Maybe add one for the other profile.
6822                if (xpDomainInfo != null && (
6823                        xpDomainInfo.bestDomainVerificationStatus
6824                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6825                    result.add(xpDomainInfo.resolveInfo);
6826                }
6827                includeBrowser = true;
6828            }
6829
6830            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6831            // If there were 'always' entries their preferred order has been set, so we also
6832            // back that off to make the alternatives equivalent
6833            if (alwaysAskList.size() > 0) {
6834                for (ResolveInfo i : result) {
6835                    i.preferredOrder = 0;
6836                }
6837                result.addAll(alwaysAskList);
6838                includeBrowser = true;
6839            }
6840
6841            if (includeBrowser) {
6842                // Also add browsers (all of them or only the default one)
6843                if (DEBUG_DOMAIN_VERIFICATION) {
6844                    Slog.v(TAG, "   ...including browsers in candidate set");
6845                }
6846                if ((matchFlags & MATCH_ALL) != 0) {
6847                    result.addAll(matchAllList);
6848                } else {
6849                    // Browser/generic handling case.  If there's a default browser, go straight
6850                    // to that (but only if there is no other higher-priority match).
6851                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6852                    int maxMatchPrio = 0;
6853                    ResolveInfo defaultBrowserMatch = null;
6854                    final int numCandidates = matchAllList.size();
6855                    for (int n = 0; n < numCandidates; n++) {
6856                        ResolveInfo info = matchAllList.get(n);
6857                        // track the highest overall match priority...
6858                        if (info.priority > maxMatchPrio) {
6859                            maxMatchPrio = info.priority;
6860                        }
6861                        // ...and the highest-priority default browser match
6862                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6863                            if (defaultBrowserMatch == null
6864                                    || (defaultBrowserMatch.priority < info.priority)) {
6865                                if (debug) {
6866                                    Slog.v(TAG, "Considering default browser match " + info);
6867                                }
6868                                defaultBrowserMatch = info;
6869                            }
6870                        }
6871                    }
6872                    if (defaultBrowserMatch != null
6873                            && defaultBrowserMatch.priority >= maxMatchPrio
6874                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6875                    {
6876                        if (debug) {
6877                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6878                        }
6879                        result.add(defaultBrowserMatch);
6880                    } else {
6881                        result.addAll(matchAllList);
6882                    }
6883                }
6884
6885                // If there is nothing selected, add all candidates and remove the ones that the user
6886                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6887                if (result.size() == 0) {
6888                    result.addAll(candidates);
6889                    result.removeAll(neverList);
6890                }
6891            }
6892        }
6893        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6894            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6895                    result.size());
6896            for (ResolveInfo info : result) {
6897                Slog.v(TAG, "  + " + info.activityInfo);
6898            }
6899        }
6900        return result;
6901    }
6902
6903    // Returns a packed value as a long:
6904    //
6905    // high 'int'-sized word: link status: undefined/ask/never/always.
6906    // low 'int'-sized word: relative priority among 'always' results.
6907    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6908        long result = ps.getDomainVerificationStatusForUser(userId);
6909        // if none available, get the master status
6910        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6911            if (ps.getIntentFilterVerificationInfo() != null) {
6912                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6913            }
6914        }
6915        return result;
6916    }
6917
6918    private ResolveInfo querySkipCurrentProfileIntents(
6919            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6920            int flags, int sourceUserId) {
6921        if (matchingFilters != null) {
6922            int size = matchingFilters.size();
6923            for (int i = 0; i < size; i ++) {
6924                CrossProfileIntentFilter filter = matchingFilters.get(i);
6925                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6926                    // Checking if there are activities in the target user that can handle the
6927                    // intent.
6928                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6929                            resolvedType, flags, sourceUserId);
6930                    if (resolveInfo != null) {
6931                        return resolveInfo;
6932                    }
6933                }
6934            }
6935        }
6936        return null;
6937    }
6938
6939    // Return matching ResolveInfo in target user if any.
6940    private ResolveInfo queryCrossProfileIntents(
6941            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6942            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6943        if (matchingFilters != null) {
6944            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6945            // match the same intent. For performance reasons, it is better not to
6946            // run queryIntent twice for the same userId
6947            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6948            int size = matchingFilters.size();
6949            for (int i = 0; i < size; i++) {
6950                CrossProfileIntentFilter filter = matchingFilters.get(i);
6951                int targetUserId = filter.getTargetUserId();
6952                boolean skipCurrentProfile =
6953                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6954                boolean skipCurrentProfileIfNoMatchFound =
6955                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6956                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6957                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6958                    // Checking if there are activities in the target user that can handle the
6959                    // intent.
6960                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6961                            resolvedType, flags, sourceUserId);
6962                    if (resolveInfo != null) return resolveInfo;
6963                    alreadyTriedUserIds.put(targetUserId, true);
6964                }
6965            }
6966        }
6967        return null;
6968    }
6969
6970    /**
6971     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6972     * will forward the intent to the filter's target user.
6973     * Otherwise, returns null.
6974     */
6975    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6976            String resolvedType, int flags, int sourceUserId) {
6977        int targetUserId = filter.getTargetUserId();
6978        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6979                resolvedType, flags, targetUserId);
6980        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6981            // If all the matches in the target profile are suspended, return null.
6982            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6983                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6984                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6985                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6986                            targetUserId);
6987                }
6988            }
6989        }
6990        return null;
6991    }
6992
6993    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6994            int sourceUserId, int targetUserId) {
6995        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6996        long ident = Binder.clearCallingIdentity();
6997        boolean targetIsProfile;
6998        try {
6999            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7000        } finally {
7001            Binder.restoreCallingIdentity(ident);
7002        }
7003        String className;
7004        if (targetIsProfile) {
7005            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7006        } else {
7007            className = FORWARD_INTENT_TO_PARENT;
7008        }
7009        ComponentName forwardingActivityComponentName = new ComponentName(
7010                mAndroidApplication.packageName, className);
7011        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7012                sourceUserId);
7013        if (!targetIsProfile) {
7014            forwardingActivityInfo.showUserIcon = targetUserId;
7015            forwardingResolveInfo.noResourceId = true;
7016        }
7017        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7018        forwardingResolveInfo.priority = 0;
7019        forwardingResolveInfo.preferredOrder = 0;
7020        forwardingResolveInfo.match = 0;
7021        forwardingResolveInfo.isDefault = true;
7022        forwardingResolveInfo.filter = filter;
7023        forwardingResolveInfo.targetUserId = targetUserId;
7024        return forwardingResolveInfo;
7025    }
7026
7027    @Override
7028    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7029            Intent[] specifics, String[] specificTypes, Intent intent,
7030            String resolvedType, int flags, int userId) {
7031        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7032                specificTypes, intent, resolvedType, flags, userId));
7033    }
7034
7035    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7036            Intent[] specifics, String[] specificTypes, Intent intent,
7037            String resolvedType, int flags, int userId) {
7038        if (!sUserManager.exists(userId)) return Collections.emptyList();
7039        final int callingUid = Binder.getCallingUid();
7040        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7041                false /*includeInstantApps*/);
7042        enforceCrossUserPermission(callingUid, userId,
7043                false /*requireFullPermission*/, false /*checkShell*/,
7044                "query intent activity options");
7045        final String resultsAction = intent.getAction();
7046
7047        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7048                | PackageManager.GET_RESOLVED_FILTER, userId);
7049
7050        if (DEBUG_INTENT_MATCHING) {
7051            Log.v(TAG, "Query " + intent + ": " + results);
7052        }
7053
7054        int specificsPos = 0;
7055        int N;
7056
7057        // todo: note that the algorithm used here is O(N^2).  This
7058        // isn't a problem in our current environment, but if we start running
7059        // into situations where we have more than 5 or 10 matches then this
7060        // should probably be changed to something smarter...
7061
7062        // First we go through and resolve each of the specific items
7063        // that were supplied, taking care of removing any corresponding
7064        // duplicate items in the generic resolve list.
7065        if (specifics != null) {
7066            for (int i=0; i<specifics.length; i++) {
7067                final Intent sintent = specifics[i];
7068                if (sintent == null) {
7069                    continue;
7070                }
7071
7072                if (DEBUG_INTENT_MATCHING) {
7073                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7074                }
7075
7076                String action = sintent.getAction();
7077                if (resultsAction != null && resultsAction.equals(action)) {
7078                    // If this action was explicitly requested, then don't
7079                    // remove things that have it.
7080                    action = null;
7081                }
7082
7083                ResolveInfo ri = null;
7084                ActivityInfo ai = null;
7085
7086                ComponentName comp = sintent.getComponent();
7087                if (comp == null) {
7088                    ri = resolveIntent(
7089                        sintent,
7090                        specificTypes != null ? specificTypes[i] : null,
7091                            flags, userId);
7092                    if (ri == null) {
7093                        continue;
7094                    }
7095                    if (ri == mResolveInfo) {
7096                        // ACK!  Must do something better with this.
7097                    }
7098                    ai = ri.activityInfo;
7099                    comp = new ComponentName(ai.applicationInfo.packageName,
7100                            ai.name);
7101                } else {
7102                    ai = getActivityInfo(comp, flags, userId);
7103                    if (ai == null) {
7104                        continue;
7105                    }
7106                }
7107
7108                // Look for any generic query activities that are duplicates
7109                // of this specific one, and remove them from the results.
7110                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7111                N = results.size();
7112                int j;
7113                for (j=specificsPos; j<N; j++) {
7114                    ResolveInfo sri = results.get(j);
7115                    if ((sri.activityInfo.name.equals(comp.getClassName())
7116                            && sri.activityInfo.applicationInfo.packageName.equals(
7117                                    comp.getPackageName()))
7118                        || (action != null && sri.filter.matchAction(action))) {
7119                        results.remove(j);
7120                        if (DEBUG_INTENT_MATCHING) Log.v(
7121                            TAG, "Removing duplicate item from " + j
7122                            + " due to specific " + specificsPos);
7123                        if (ri == null) {
7124                            ri = sri;
7125                        }
7126                        j--;
7127                        N--;
7128                    }
7129                }
7130
7131                // Add this specific item to its proper place.
7132                if (ri == null) {
7133                    ri = new ResolveInfo();
7134                    ri.activityInfo = ai;
7135                }
7136                results.add(specificsPos, ri);
7137                ri.specificIndex = i;
7138                specificsPos++;
7139            }
7140        }
7141
7142        // Now we go through the remaining generic results and remove any
7143        // duplicate actions that are found here.
7144        N = results.size();
7145        for (int i=specificsPos; i<N-1; i++) {
7146            final ResolveInfo rii = results.get(i);
7147            if (rii.filter == null) {
7148                continue;
7149            }
7150
7151            // Iterate over all of the actions of this result's intent
7152            // filter...  typically this should be just one.
7153            final Iterator<String> it = rii.filter.actionsIterator();
7154            if (it == null) {
7155                continue;
7156            }
7157            while (it.hasNext()) {
7158                final String action = it.next();
7159                if (resultsAction != null && resultsAction.equals(action)) {
7160                    // If this action was explicitly requested, then don't
7161                    // remove things that have it.
7162                    continue;
7163                }
7164                for (int j=i+1; j<N; j++) {
7165                    final ResolveInfo rij = results.get(j);
7166                    if (rij.filter != null && rij.filter.hasAction(action)) {
7167                        results.remove(j);
7168                        if (DEBUG_INTENT_MATCHING) Log.v(
7169                            TAG, "Removing duplicate item from " + j
7170                            + " due to action " + action + " at " + i);
7171                        j--;
7172                        N--;
7173                    }
7174                }
7175            }
7176
7177            // If the caller didn't request filter information, drop it now
7178            // so we don't have to marshall/unmarshall it.
7179            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7180                rii.filter = null;
7181            }
7182        }
7183
7184        // Filter out the caller activity if so requested.
7185        if (caller != null) {
7186            N = results.size();
7187            for (int i=0; i<N; i++) {
7188                ActivityInfo ainfo = results.get(i).activityInfo;
7189                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7190                        && caller.getClassName().equals(ainfo.name)) {
7191                    results.remove(i);
7192                    break;
7193                }
7194            }
7195        }
7196
7197        // If the caller didn't request filter information,
7198        // drop them now so we don't have to
7199        // marshall/unmarshall it.
7200        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7201            N = results.size();
7202            for (int i=0; i<N; i++) {
7203                results.get(i).filter = null;
7204            }
7205        }
7206
7207        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7208        return results;
7209    }
7210
7211    @Override
7212    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7213            String resolvedType, int flags, int userId) {
7214        return new ParceledListSlice<>(
7215                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7216    }
7217
7218    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7219            String resolvedType, int flags, int userId) {
7220        if (!sUserManager.exists(userId)) return Collections.emptyList();
7221        final int callingUid = Binder.getCallingUid();
7222        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7223                false /*includeInstantApps*/);
7224        ComponentName comp = intent.getComponent();
7225        if (comp == null) {
7226            if (intent.getSelector() != null) {
7227                intent = intent.getSelector();
7228                comp = intent.getComponent();
7229            }
7230        }
7231        if (comp != null) {
7232            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7233            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7234            if (ai != null) {
7235                ResolveInfo ri = new ResolveInfo();
7236                ri.activityInfo = ai;
7237                list.add(ri);
7238            }
7239            return list;
7240        }
7241
7242        // reader
7243        synchronized (mPackages) {
7244            String pkgName = intent.getPackage();
7245            if (pkgName == null) {
7246                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
7247            }
7248            final PackageParser.Package pkg = mPackages.get(pkgName);
7249            if (pkg != null) {
7250                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
7251                        userId);
7252            }
7253            return Collections.emptyList();
7254        }
7255    }
7256
7257    @Override
7258    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7259        final int callingUid = Binder.getCallingUid();
7260        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7261    }
7262
7263    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7264            int userId, int callingUid) {
7265        if (!sUserManager.exists(userId)) return null;
7266        flags = updateFlagsForResolve(
7267                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7268        List<ResolveInfo> query = queryIntentServicesInternal(
7269                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7270        if (query != null) {
7271            if (query.size() >= 1) {
7272                // If there is more than one service with the same priority,
7273                // just arbitrarily pick the first one.
7274                return query.get(0);
7275            }
7276        }
7277        return null;
7278    }
7279
7280    @Override
7281    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7282            String resolvedType, int flags, int userId) {
7283        final int callingUid = Binder.getCallingUid();
7284        return new ParceledListSlice<>(queryIntentServicesInternal(
7285                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7286    }
7287
7288    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7289            String resolvedType, int flags, int userId, int callingUid,
7290            boolean includeInstantApps) {
7291        if (!sUserManager.exists(userId)) return Collections.emptyList();
7292        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7293        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7294        ComponentName comp = intent.getComponent();
7295        if (comp == null) {
7296            if (intent.getSelector() != null) {
7297                intent = intent.getSelector();
7298                comp = intent.getComponent();
7299            }
7300        }
7301        if (comp != null) {
7302            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7303            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7304            if (si != null) {
7305                // When specifying an explicit component, we prevent the service from being
7306                // used when either 1) the service is in an instant application and the
7307                // caller is not the same instant application or 2) the calling package is
7308                // ephemeral and the activity is not visible to ephemeral applications.
7309                final boolean matchInstantApp =
7310                        (flags & PackageManager.MATCH_INSTANT) != 0;
7311                final boolean matchVisibleToInstantAppOnly =
7312                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7313                final boolean isCallerInstantApp =
7314                        instantAppPkgName != null;
7315                final boolean isTargetSameInstantApp =
7316                        comp.getPackageName().equals(instantAppPkgName);
7317                final boolean isTargetInstantApp =
7318                        (si.applicationInfo.privateFlags
7319                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7320                final boolean isTargetHiddenFromInstantApp =
7321                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7322                final boolean blockResolution =
7323                        !isTargetSameInstantApp
7324                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7325                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7326                                        && isTargetHiddenFromInstantApp));
7327                if (!blockResolution) {
7328                    final ResolveInfo ri = new ResolveInfo();
7329                    ri.serviceInfo = si;
7330                    list.add(ri);
7331                }
7332            }
7333            return list;
7334        }
7335
7336        // reader
7337        synchronized (mPackages) {
7338            String pkgName = intent.getPackage();
7339            if (pkgName == null) {
7340                return applyPostServiceResolutionFilter(
7341                        mServices.queryIntent(intent, resolvedType, flags, userId),
7342                        instantAppPkgName);
7343            }
7344            final PackageParser.Package pkg = mPackages.get(pkgName);
7345            if (pkg != null) {
7346                return applyPostServiceResolutionFilter(
7347                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7348                                userId),
7349                        instantAppPkgName);
7350            }
7351            return Collections.emptyList();
7352        }
7353    }
7354
7355    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7356            String instantAppPkgName) {
7357        // TODO: When adding on-demand split support for non-instant apps, remove this check
7358        // and always apply post filtering
7359        if (instantAppPkgName == null) {
7360            return resolveInfos;
7361        }
7362        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7363            final ResolveInfo info = resolveInfos.get(i);
7364            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7365            // allow services that are defined in the provided package
7366            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7367                if (info.serviceInfo.splitName != null
7368                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7369                                info.serviceInfo.splitName)) {
7370                    // requested service is defined in a split that hasn't been installed yet.
7371                    // add the installer to the resolve list
7372                    if (DEBUG_EPHEMERAL) {
7373                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7374                    }
7375                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7376                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7377                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7378                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
7379                    // make sure this resolver is the default
7380                    installerInfo.isDefault = true;
7381                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7382                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7383                    // add a non-generic filter
7384                    installerInfo.filter = new IntentFilter();
7385                    // load resources from the correct package
7386                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7387                    resolveInfos.set(i, installerInfo);
7388                }
7389                continue;
7390            }
7391            // allow services that have been explicitly exposed to ephemeral apps
7392            if (!isEphemeralApp
7393                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7394                continue;
7395            }
7396            resolveInfos.remove(i);
7397        }
7398        return resolveInfos;
7399    }
7400
7401    @Override
7402    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7403            String resolvedType, int flags, int userId) {
7404        return new ParceledListSlice<>(
7405                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7406    }
7407
7408    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7409            Intent intent, String resolvedType, int flags, int userId) {
7410        if (!sUserManager.exists(userId)) return Collections.emptyList();
7411        final int callingUid = Binder.getCallingUid();
7412        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7413        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7414                false /*includeInstantApps*/);
7415        ComponentName comp = intent.getComponent();
7416        if (comp == null) {
7417            if (intent.getSelector() != null) {
7418                intent = intent.getSelector();
7419                comp = intent.getComponent();
7420            }
7421        }
7422        if (comp != null) {
7423            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7424            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7425            if (pi != null) {
7426                // When specifying an explicit component, we prevent the provider from being
7427                // used when either 1) the provider is in an instant application and the
7428                // caller is not the same instant application or 2) the calling package is an
7429                // instant application and the provider is not visible to instant applications.
7430                final boolean matchInstantApp =
7431                        (flags & PackageManager.MATCH_INSTANT) != 0;
7432                final boolean matchVisibleToInstantAppOnly =
7433                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7434                final boolean isCallerInstantApp =
7435                        instantAppPkgName != null;
7436                final boolean isTargetSameInstantApp =
7437                        comp.getPackageName().equals(instantAppPkgName);
7438                final boolean isTargetInstantApp =
7439                        (pi.applicationInfo.privateFlags
7440                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7441                final boolean isTargetHiddenFromInstantApp =
7442                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7443                final boolean blockResolution =
7444                        !isTargetSameInstantApp
7445                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7446                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7447                                        && isTargetHiddenFromInstantApp));
7448                if (!blockResolution) {
7449                    final ResolveInfo ri = new ResolveInfo();
7450                    ri.providerInfo = pi;
7451                    list.add(ri);
7452                }
7453            }
7454            return list;
7455        }
7456
7457        // reader
7458        synchronized (mPackages) {
7459            String pkgName = intent.getPackage();
7460            if (pkgName == null) {
7461                return applyPostContentProviderResolutionFilter(
7462                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7463                        instantAppPkgName);
7464            }
7465            final PackageParser.Package pkg = mPackages.get(pkgName);
7466            if (pkg != null) {
7467                return applyPostContentProviderResolutionFilter(
7468                        mProviders.queryIntentForPackage(
7469                        intent, resolvedType, flags, pkg.providers, userId),
7470                        instantAppPkgName);
7471            }
7472            return Collections.emptyList();
7473        }
7474    }
7475
7476    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7477            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7478        // TODO: When adding on-demand split support for non-instant applications, remove
7479        // this check and always apply post filtering
7480        if (instantAppPkgName == null) {
7481            return resolveInfos;
7482        }
7483        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7484            final ResolveInfo info = resolveInfos.get(i);
7485            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7486            // allow providers that are defined in the provided package
7487            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7488                if (info.providerInfo.splitName != null
7489                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7490                                info.providerInfo.splitName)) {
7491                    // requested provider is defined in a split that hasn't been installed yet.
7492                    // add the installer to the resolve list
7493                    if (DEBUG_EPHEMERAL) {
7494                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7495                    }
7496                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7497                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7498                            info.providerInfo.packageName, info.providerInfo.splitName,
7499                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
7500                    // make sure this resolver is the default
7501                    installerInfo.isDefault = true;
7502                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7503                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7504                    // add a non-generic filter
7505                    installerInfo.filter = new IntentFilter();
7506                    // load resources from the correct package
7507                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7508                    resolveInfos.set(i, installerInfo);
7509                }
7510                continue;
7511            }
7512            // allow providers that have been explicitly exposed to instant applications
7513            if (!isEphemeralApp
7514                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7515                continue;
7516            }
7517            resolveInfos.remove(i);
7518        }
7519        return resolveInfos;
7520    }
7521
7522    @Override
7523    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7524        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7525        flags = updateFlagsForPackage(flags, userId, null);
7526        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7527        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7528                true /* requireFullPermission */, false /* checkShell */,
7529                "get installed packages");
7530
7531        // writer
7532        synchronized (mPackages) {
7533            ArrayList<PackageInfo> list;
7534            if (listUninstalled) {
7535                list = new ArrayList<>(mSettings.mPackages.size());
7536                for (PackageSetting ps : mSettings.mPackages.values()) {
7537                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7538                        continue;
7539                    }
7540                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7541                    if (pi != null) {
7542                        list.add(pi);
7543                    }
7544                }
7545            } else {
7546                list = new ArrayList<>(mPackages.size());
7547                for (PackageParser.Package p : mPackages.values()) {
7548                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
7549                            Binder.getCallingUid(), userId)) {
7550                        continue;
7551                    }
7552                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7553                            p.mExtras, flags, userId);
7554                    if (pi != null) {
7555                        list.add(pi);
7556                    }
7557                }
7558            }
7559
7560            return new ParceledListSlice<>(list);
7561        }
7562    }
7563
7564    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7565            String[] permissions, boolean[] tmp, int flags, int userId) {
7566        int numMatch = 0;
7567        final PermissionsState permissionsState = ps.getPermissionsState();
7568        for (int i=0; i<permissions.length; i++) {
7569            final String permission = permissions[i];
7570            if (permissionsState.hasPermission(permission, userId)) {
7571                tmp[i] = true;
7572                numMatch++;
7573            } else {
7574                tmp[i] = false;
7575            }
7576        }
7577        if (numMatch == 0) {
7578            return;
7579        }
7580        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7581
7582        // The above might return null in cases of uninstalled apps or install-state
7583        // skew across users/profiles.
7584        if (pi != null) {
7585            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7586                if (numMatch == permissions.length) {
7587                    pi.requestedPermissions = permissions;
7588                } else {
7589                    pi.requestedPermissions = new String[numMatch];
7590                    numMatch = 0;
7591                    for (int i=0; i<permissions.length; i++) {
7592                        if (tmp[i]) {
7593                            pi.requestedPermissions[numMatch] = permissions[i];
7594                            numMatch++;
7595                        }
7596                    }
7597                }
7598            }
7599            list.add(pi);
7600        }
7601    }
7602
7603    @Override
7604    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7605            String[] permissions, int flags, int userId) {
7606        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7607        flags = updateFlagsForPackage(flags, userId, permissions);
7608        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7609                true /* requireFullPermission */, false /* checkShell */,
7610                "get packages holding permissions");
7611        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7612
7613        // writer
7614        synchronized (mPackages) {
7615            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7616            boolean[] tmpBools = new boolean[permissions.length];
7617            if (listUninstalled) {
7618                for (PackageSetting ps : mSettings.mPackages.values()) {
7619                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7620                            userId);
7621                }
7622            } else {
7623                for (PackageParser.Package pkg : mPackages.values()) {
7624                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7625                    if (ps != null) {
7626                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7627                                userId);
7628                    }
7629                }
7630            }
7631
7632            return new ParceledListSlice<PackageInfo>(list);
7633        }
7634    }
7635
7636    @Override
7637    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7638        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7639        flags = updateFlagsForApplication(flags, userId, null);
7640        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7641
7642        // writer
7643        synchronized (mPackages) {
7644            ArrayList<ApplicationInfo> list;
7645            if (listUninstalled) {
7646                list = new ArrayList<>(mSettings.mPackages.size());
7647                for (PackageSetting ps : mSettings.mPackages.values()) {
7648                    ApplicationInfo ai;
7649                    int effectiveFlags = flags;
7650                    if (ps.isSystem()) {
7651                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7652                    }
7653                    if (ps.pkg != null) {
7654                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7655                            continue;
7656                        }
7657                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7658                                ps.readUserState(userId), userId);
7659                        if (ai != null) {
7660                            rebaseEnabledOverlays(ai, userId);
7661                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7662                        }
7663                    } else {
7664                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7665                        // and already converts to externally visible package name
7666                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7667                                Binder.getCallingUid(), effectiveFlags, userId);
7668                    }
7669                    if (ai != null) {
7670                        list.add(ai);
7671                    }
7672                }
7673            } else {
7674                list = new ArrayList<>(mPackages.size());
7675                for (PackageParser.Package p : mPackages.values()) {
7676                    if (p.mExtras != null) {
7677                        PackageSetting ps = (PackageSetting) p.mExtras;
7678                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7679                            continue;
7680                        }
7681                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7682                                ps.readUserState(userId), userId);
7683                        if (ai != null) {
7684                            rebaseEnabledOverlays(ai, userId);
7685                            ai.packageName = resolveExternalPackageNameLPr(p);
7686                            list.add(ai);
7687                        }
7688                    }
7689                }
7690            }
7691
7692            return new ParceledListSlice<>(list);
7693        }
7694    }
7695
7696    @Override
7697    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7698        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7699            return null;
7700        }
7701
7702        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7703                "getEphemeralApplications");
7704        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7705                true /* requireFullPermission */, false /* checkShell */,
7706                "getEphemeralApplications");
7707        synchronized (mPackages) {
7708            List<InstantAppInfo> instantApps = mInstantAppRegistry
7709                    .getInstantAppsLPr(userId);
7710            if (instantApps != null) {
7711                return new ParceledListSlice<>(instantApps);
7712            }
7713        }
7714        return null;
7715    }
7716
7717    @Override
7718    public boolean isInstantApp(String packageName, int userId) {
7719        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7720                true /* requireFullPermission */, false /* checkShell */,
7721                "isInstantApp");
7722        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7723            return false;
7724        }
7725        int uid = Binder.getCallingUid();
7726        if (Process.isIsolated(uid)) {
7727            uid = mIsolatedOwners.get(uid);
7728        }
7729
7730        synchronized (mPackages) {
7731            final PackageSetting ps = mSettings.mPackages.get(packageName);
7732            PackageParser.Package pkg = mPackages.get(packageName);
7733            final boolean returnAllowed =
7734                    ps != null
7735                    && (isCallerSameApp(packageName, uid)
7736                            || mContext.checkCallingOrSelfPermission(
7737                                    android.Manifest.permission.ACCESS_INSTANT_APPS)
7738                                            == PERMISSION_GRANTED
7739                            || mInstantAppRegistry.isInstantAccessGranted(
7740                                    userId, UserHandle.getAppId(uid), ps.appId));
7741            if (returnAllowed) {
7742                return ps.getInstantApp(userId);
7743            }
7744        }
7745        return false;
7746    }
7747
7748    @Override
7749    public byte[] getInstantAppCookie(String packageName, int userId) {
7750        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7751            return null;
7752        }
7753
7754        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7755                true /* requireFullPermission */, false /* checkShell */,
7756                "getInstantAppCookie");
7757        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7758            return null;
7759        }
7760        synchronized (mPackages) {
7761            return mInstantAppRegistry.getInstantAppCookieLPw(
7762                    packageName, userId);
7763        }
7764    }
7765
7766    @Override
7767    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7768        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7769            return true;
7770        }
7771
7772        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7773                true /* requireFullPermission */, true /* checkShell */,
7774                "setInstantAppCookie");
7775        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7776            return false;
7777        }
7778        synchronized (mPackages) {
7779            return mInstantAppRegistry.setInstantAppCookieLPw(
7780                    packageName, cookie, userId);
7781        }
7782    }
7783
7784    @Override
7785    public Bitmap getInstantAppIcon(String packageName, int userId) {
7786        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7787            return null;
7788        }
7789
7790        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7791                "getInstantAppIcon");
7792
7793        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7794                true /* requireFullPermission */, false /* checkShell */,
7795                "getInstantAppIcon");
7796
7797        synchronized (mPackages) {
7798            return mInstantAppRegistry.getInstantAppIconLPw(
7799                    packageName, userId);
7800        }
7801    }
7802
7803    private boolean isCallerSameApp(String packageName, int uid) {
7804        PackageParser.Package pkg = mPackages.get(packageName);
7805        return pkg != null
7806                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
7807    }
7808
7809    @Override
7810    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7811        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7812    }
7813
7814    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7815        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7816
7817        // reader
7818        synchronized (mPackages) {
7819            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7820            final int userId = UserHandle.getCallingUserId();
7821            while (i.hasNext()) {
7822                final PackageParser.Package p = i.next();
7823                if (p.applicationInfo == null) continue;
7824
7825                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7826                        && !p.applicationInfo.isDirectBootAware();
7827                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7828                        && p.applicationInfo.isDirectBootAware();
7829
7830                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7831                        && (!mSafeMode || isSystemApp(p))
7832                        && (matchesUnaware || matchesAware)) {
7833                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7834                    if (ps != null) {
7835                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7836                                ps.readUserState(userId), userId);
7837                        if (ai != null) {
7838                            rebaseEnabledOverlays(ai, userId);
7839                            finalList.add(ai);
7840                        }
7841                    }
7842                }
7843            }
7844        }
7845
7846        return finalList;
7847    }
7848
7849    @Override
7850    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7851        if (!sUserManager.exists(userId)) return null;
7852        flags = updateFlagsForComponent(flags, userId, name);
7853        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
7854        // reader
7855        synchronized (mPackages) {
7856            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7857            PackageSetting ps = provider != null
7858                    ? mSettings.mPackages.get(provider.owner.packageName)
7859                    : null;
7860            if (ps != null) {
7861                final boolean isInstantApp = ps.getInstantApp(userId);
7862                // normal application; filter out instant application provider
7863                if (instantAppPkgName == null && isInstantApp) {
7864                    return null;
7865                }
7866                // instant application; filter out other instant applications
7867                if (instantAppPkgName != null
7868                        && isInstantApp
7869                        && !provider.owner.packageName.equals(instantAppPkgName)) {
7870                    return null;
7871                }
7872                // instant application; filter out non-exposed provider
7873                if (instantAppPkgName != null
7874                        && !isInstantApp
7875                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
7876                    return null;
7877                }
7878                // provider not enabled
7879                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
7880                    return null;
7881                }
7882                return PackageParser.generateProviderInfo(
7883                        provider, flags, ps.readUserState(userId), userId);
7884            }
7885            return null;
7886        }
7887    }
7888
7889    /**
7890     * @deprecated
7891     */
7892    @Deprecated
7893    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7894        // reader
7895        synchronized (mPackages) {
7896            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7897                    .entrySet().iterator();
7898            final int userId = UserHandle.getCallingUserId();
7899            while (i.hasNext()) {
7900                Map.Entry<String, PackageParser.Provider> entry = i.next();
7901                PackageParser.Provider p = entry.getValue();
7902                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7903
7904                if (ps != null && p.syncable
7905                        && (!mSafeMode || (p.info.applicationInfo.flags
7906                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7907                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7908                            ps.readUserState(userId), userId);
7909                    if (info != null) {
7910                        outNames.add(entry.getKey());
7911                        outInfo.add(info);
7912                    }
7913                }
7914            }
7915        }
7916    }
7917
7918    @Override
7919    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7920            int uid, int flags, String metaDataKey) {
7921        final int userId = processName != null ? UserHandle.getUserId(uid)
7922                : UserHandle.getCallingUserId();
7923        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7924        flags = updateFlagsForComponent(flags, userId, processName);
7925
7926        ArrayList<ProviderInfo> finalList = null;
7927        // reader
7928        synchronized (mPackages) {
7929            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7930            while (i.hasNext()) {
7931                final PackageParser.Provider p = i.next();
7932                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7933                if (ps != null && p.info.authority != null
7934                        && (processName == null
7935                                || (p.info.processName.equals(processName)
7936                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7937                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7938
7939                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
7940                    // parameter.
7941                    if (metaDataKey != null
7942                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
7943                        continue;
7944                    }
7945
7946                    if (finalList == null) {
7947                        finalList = new ArrayList<ProviderInfo>(3);
7948                    }
7949                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7950                            ps.readUserState(userId), userId);
7951                    if (info != null) {
7952                        finalList.add(info);
7953                    }
7954                }
7955            }
7956        }
7957
7958        if (finalList != null) {
7959            Collections.sort(finalList, mProviderInitOrderSorter);
7960            return new ParceledListSlice<ProviderInfo>(finalList);
7961        }
7962
7963        return ParceledListSlice.emptyList();
7964    }
7965
7966    @Override
7967    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7968        // reader
7969        synchronized (mPackages) {
7970            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7971            return PackageParser.generateInstrumentationInfo(i, flags);
7972        }
7973    }
7974
7975    @Override
7976    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7977            String targetPackage, int flags) {
7978        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7979    }
7980
7981    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7982            int flags) {
7983        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7984
7985        // reader
7986        synchronized (mPackages) {
7987            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7988            while (i.hasNext()) {
7989                final PackageParser.Instrumentation p = i.next();
7990                if (targetPackage == null
7991                        || targetPackage.equals(p.info.targetPackage)) {
7992                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7993                            flags);
7994                    if (ii != null) {
7995                        finalList.add(ii);
7996                    }
7997                }
7998            }
7999        }
8000
8001        return finalList;
8002    }
8003
8004    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8005        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8006        try {
8007            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8008        } finally {
8009            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8010        }
8011    }
8012
8013    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8014        final File[] files = dir.listFiles();
8015        if (ArrayUtils.isEmpty(files)) {
8016            Log.d(TAG, "No files in app dir " + dir);
8017            return;
8018        }
8019
8020        if (DEBUG_PACKAGE_SCANNING) {
8021            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8022                    + " flags=0x" + Integer.toHexString(parseFlags));
8023        }
8024        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8025                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8026                mParallelPackageParserCallback);
8027
8028        // Submit files for parsing in parallel
8029        int fileCount = 0;
8030        for (File file : files) {
8031            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8032                    && !PackageInstallerService.isStageName(file.getName());
8033            if (!isPackage) {
8034                // Ignore entries which are not packages
8035                continue;
8036            }
8037            parallelPackageParser.submit(file, parseFlags);
8038            fileCount++;
8039        }
8040
8041        // Process results one by one
8042        for (; fileCount > 0; fileCount--) {
8043            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8044            Throwable throwable = parseResult.throwable;
8045            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8046
8047            if (throwable == null) {
8048                // Static shared libraries have synthetic package names
8049                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8050                    renameStaticSharedLibraryPackage(parseResult.pkg);
8051                }
8052                try {
8053                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8054                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8055                                currentTime, null);
8056                    }
8057                } catch (PackageManagerException e) {
8058                    errorCode = e.error;
8059                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8060                }
8061            } else if (throwable instanceof PackageParser.PackageParserException) {
8062                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8063                        throwable;
8064                errorCode = e.error;
8065                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8066            } else {
8067                throw new IllegalStateException("Unexpected exception occurred while parsing "
8068                        + parseResult.scanFile, throwable);
8069            }
8070
8071            // Delete invalid userdata apps
8072            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8073                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8074                logCriticalInfo(Log.WARN,
8075                        "Deleting invalid package at " + parseResult.scanFile);
8076                removeCodePathLI(parseResult.scanFile);
8077            }
8078        }
8079        parallelPackageParser.close();
8080    }
8081
8082    private static File getSettingsProblemFile() {
8083        File dataDir = Environment.getDataDirectory();
8084        File systemDir = new File(dataDir, "system");
8085        File fname = new File(systemDir, "uiderrors.txt");
8086        return fname;
8087    }
8088
8089    static void reportSettingsProblem(int priority, String msg) {
8090        logCriticalInfo(priority, msg);
8091    }
8092
8093    public static void logCriticalInfo(int priority, String msg) {
8094        Slog.println(priority, TAG, msg);
8095        EventLogTags.writePmCriticalInfo(msg);
8096        try {
8097            File fname = getSettingsProblemFile();
8098            FileOutputStream out = new FileOutputStream(fname, true);
8099            PrintWriter pw = new FastPrintWriter(out);
8100            SimpleDateFormat formatter = new SimpleDateFormat();
8101            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8102            pw.println(dateString + ": " + msg);
8103            pw.close();
8104            FileUtils.setPermissions(
8105                    fname.toString(),
8106                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8107                    -1, -1);
8108        } catch (java.io.IOException e) {
8109        }
8110    }
8111
8112    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8113        if (srcFile.isDirectory()) {
8114            final File baseFile = new File(pkg.baseCodePath);
8115            long maxModifiedTime = baseFile.lastModified();
8116            if (pkg.splitCodePaths != null) {
8117                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8118                    final File splitFile = new File(pkg.splitCodePaths[i]);
8119                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8120                }
8121            }
8122            return maxModifiedTime;
8123        }
8124        return srcFile.lastModified();
8125    }
8126
8127    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8128            final int policyFlags) throws PackageManagerException {
8129        // When upgrading from pre-N MR1, verify the package time stamp using the package
8130        // directory and not the APK file.
8131        final long lastModifiedTime = mIsPreNMR1Upgrade
8132                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8133        if (ps != null
8134                && ps.codePath.equals(srcFile)
8135                && ps.timeStamp == lastModifiedTime
8136                && !isCompatSignatureUpdateNeeded(pkg)
8137                && !isRecoverSignatureUpdateNeeded(pkg)) {
8138            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8139            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8140            ArraySet<PublicKey> signingKs;
8141            synchronized (mPackages) {
8142                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8143            }
8144            if (ps.signatures.mSignatures != null
8145                    && ps.signatures.mSignatures.length != 0
8146                    && signingKs != null) {
8147                // Optimization: reuse the existing cached certificates
8148                // if the package appears to be unchanged.
8149                pkg.mSignatures = ps.signatures.mSignatures;
8150                pkg.mSigningKeys = signingKs;
8151                return;
8152            }
8153
8154            Slog.w(TAG, "PackageSetting for " + ps.name
8155                    + " is missing signatures.  Collecting certs again to recover them.");
8156        } else {
8157            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8158        }
8159
8160        try {
8161            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8162            PackageParser.collectCertificates(pkg, policyFlags);
8163        } catch (PackageParserException e) {
8164            throw PackageManagerException.from(e);
8165        } finally {
8166            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8167        }
8168    }
8169
8170    /**
8171     *  Traces a package scan.
8172     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8173     */
8174    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8175            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8176        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8177        try {
8178            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8179        } finally {
8180            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8181        }
8182    }
8183
8184    /**
8185     *  Scans a package and returns the newly parsed package.
8186     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8187     */
8188    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8189            long currentTime, UserHandle user) throws PackageManagerException {
8190        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8191        PackageParser pp = new PackageParser();
8192        pp.setSeparateProcesses(mSeparateProcesses);
8193        pp.setOnlyCoreApps(mOnlyCore);
8194        pp.setDisplayMetrics(mMetrics);
8195        pp.setCallback(mPackageParserCallback);
8196
8197        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8198            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8199        }
8200
8201        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8202        final PackageParser.Package pkg;
8203        try {
8204            pkg = pp.parsePackage(scanFile, parseFlags);
8205        } catch (PackageParserException e) {
8206            throw PackageManagerException.from(e);
8207        } finally {
8208            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8209        }
8210
8211        // Static shared libraries have synthetic package names
8212        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8213            renameStaticSharedLibraryPackage(pkg);
8214        }
8215
8216        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8217    }
8218
8219    /**
8220     *  Scans a package and returns the newly parsed package.
8221     *  @throws PackageManagerException on a parse error.
8222     */
8223    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8224            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8225            throws PackageManagerException {
8226        // If the package has children and this is the first dive in the function
8227        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8228        // packages (parent and children) would be successfully scanned before the
8229        // actual scan since scanning mutates internal state and we want to atomically
8230        // install the package and its children.
8231        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8232            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8233                scanFlags |= SCAN_CHECK_ONLY;
8234            }
8235        } else {
8236            scanFlags &= ~SCAN_CHECK_ONLY;
8237        }
8238
8239        // Scan the parent
8240        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8241                scanFlags, currentTime, user);
8242
8243        // Scan the children
8244        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8245        for (int i = 0; i < childCount; i++) {
8246            PackageParser.Package childPackage = pkg.childPackages.get(i);
8247            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8248                    currentTime, user);
8249        }
8250
8251
8252        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8253            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8254        }
8255
8256        return scannedPkg;
8257    }
8258
8259    /**
8260     *  Scans a package and returns the newly parsed package.
8261     *  @throws PackageManagerException on a parse error.
8262     */
8263    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8264            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8265            throws PackageManagerException {
8266        PackageSetting ps = null;
8267        PackageSetting updatedPkg;
8268        // reader
8269        synchronized (mPackages) {
8270            // Look to see if we already know about this package.
8271            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8272            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8273                // This package has been renamed to its original name.  Let's
8274                // use that.
8275                ps = mSettings.getPackageLPr(oldName);
8276            }
8277            // If there was no original package, see one for the real package name.
8278            if (ps == null) {
8279                ps = mSettings.getPackageLPr(pkg.packageName);
8280            }
8281            // Check to see if this package could be hiding/updating a system
8282            // package.  Must look for it either under the original or real
8283            // package name depending on our state.
8284            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8285            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8286
8287            // If this is a package we don't know about on the system partition, we
8288            // may need to remove disabled child packages on the system partition
8289            // or may need to not add child packages if the parent apk is updated
8290            // on the data partition and no longer defines this child package.
8291            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8292                // If this is a parent package for an updated system app and this system
8293                // app got an OTA update which no longer defines some of the child packages
8294                // we have to prune them from the disabled system packages.
8295                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8296                if (disabledPs != null) {
8297                    final int scannedChildCount = (pkg.childPackages != null)
8298                            ? pkg.childPackages.size() : 0;
8299                    final int disabledChildCount = disabledPs.childPackageNames != null
8300                            ? disabledPs.childPackageNames.size() : 0;
8301                    for (int i = 0; i < disabledChildCount; i++) {
8302                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8303                        boolean disabledPackageAvailable = false;
8304                        for (int j = 0; j < scannedChildCount; j++) {
8305                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8306                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8307                                disabledPackageAvailable = true;
8308                                break;
8309                            }
8310                         }
8311                         if (!disabledPackageAvailable) {
8312                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8313                         }
8314                    }
8315                }
8316            }
8317        }
8318
8319        boolean updatedPkgBetter = false;
8320        // First check if this is a system package that may involve an update
8321        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8322            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8323            // it needs to drop FLAG_PRIVILEGED.
8324            if (locationIsPrivileged(scanFile)) {
8325                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8326            } else {
8327                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8328            }
8329
8330            if (ps != null && !ps.codePath.equals(scanFile)) {
8331                // The path has changed from what was last scanned...  check the
8332                // version of the new path against what we have stored to determine
8333                // what to do.
8334                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8335                if (pkg.mVersionCode <= ps.versionCode) {
8336                    // The system package has been updated and the code path does not match
8337                    // Ignore entry. Skip it.
8338                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8339                            + " ignored: updated version " + ps.versionCode
8340                            + " better than this " + pkg.mVersionCode);
8341                    if (!updatedPkg.codePath.equals(scanFile)) {
8342                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8343                                + ps.name + " changing from " + updatedPkg.codePathString
8344                                + " to " + scanFile);
8345                        updatedPkg.codePath = scanFile;
8346                        updatedPkg.codePathString = scanFile.toString();
8347                        updatedPkg.resourcePath = scanFile;
8348                        updatedPkg.resourcePathString = scanFile.toString();
8349                    }
8350                    updatedPkg.pkg = pkg;
8351                    updatedPkg.versionCode = pkg.mVersionCode;
8352
8353                    // Update the disabled system child packages to point to the package too.
8354                    final int childCount = updatedPkg.childPackageNames != null
8355                            ? updatedPkg.childPackageNames.size() : 0;
8356                    for (int i = 0; i < childCount; i++) {
8357                        String childPackageName = updatedPkg.childPackageNames.get(i);
8358                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8359                                childPackageName);
8360                        if (updatedChildPkg != null) {
8361                            updatedChildPkg.pkg = pkg;
8362                            updatedChildPkg.versionCode = pkg.mVersionCode;
8363                        }
8364                    }
8365
8366                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8367                            + scanFile + " ignored: updated version " + ps.versionCode
8368                            + " better than this " + pkg.mVersionCode);
8369                } else {
8370                    // The current app on the system partition is better than
8371                    // what we have updated to on the data partition; switch
8372                    // back to the system partition version.
8373                    // At this point, its safely assumed that package installation for
8374                    // apps in system partition will go through. If not there won't be a working
8375                    // version of the app
8376                    // writer
8377                    synchronized (mPackages) {
8378                        // Just remove the loaded entries from package lists.
8379                        mPackages.remove(ps.name);
8380                    }
8381
8382                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8383                            + " reverting from " + ps.codePathString
8384                            + ": new version " + pkg.mVersionCode
8385                            + " better than installed " + ps.versionCode);
8386
8387                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8388                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8389                    synchronized (mInstallLock) {
8390                        args.cleanUpResourcesLI();
8391                    }
8392                    synchronized (mPackages) {
8393                        mSettings.enableSystemPackageLPw(ps.name);
8394                    }
8395                    updatedPkgBetter = true;
8396                }
8397            }
8398        }
8399
8400        if (updatedPkg != null) {
8401            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8402            // initially
8403            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8404
8405            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8406            // flag set initially
8407            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8408                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8409            }
8410        }
8411
8412        // Verify certificates against what was last scanned
8413        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8414
8415        /*
8416         * A new system app appeared, but we already had a non-system one of the
8417         * same name installed earlier.
8418         */
8419        boolean shouldHideSystemApp = false;
8420        if (updatedPkg == null && ps != null
8421                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8422            /*
8423             * Check to make sure the signatures match first. If they don't,
8424             * wipe the installed application and its data.
8425             */
8426            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
8427                    != PackageManager.SIGNATURE_MATCH) {
8428                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
8429                        + " signatures don't match existing userdata copy; removing");
8430                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8431                        "scanPackageInternalLI")) {
8432                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8433                }
8434                ps = null;
8435            } else {
8436                /*
8437                 * If the newly-added system app is an older version than the
8438                 * already installed version, hide it. It will be scanned later
8439                 * and re-added like an update.
8440                 */
8441                if (pkg.mVersionCode <= ps.versionCode) {
8442                    shouldHideSystemApp = true;
8443                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8444                            + " but new version " + pkg.mVersionCode + " better than installed "
8445                            + ps.versionCode + "; hiding system");
8446                } else {
8447                    /*
8448                     * The newly found system app is a newer version that the
8449                     * one previously installed. Simply remove the
8450                     * already-installed application and replace it with our own
8451                     * while keeping the application data.
8452                     */
8453                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8454                            + " reverting from " + ps.codePathString + ": new version "
8455                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8456                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8457                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8458                    synchronized (mInstallLock) {
8459                        args.cleanUpResourcesLI();
8460                    }
8461                }
8462            }
8463        }
8464
8465        // The apk is forward locked (not public) if its code and resources
8466        // are kept in different files. (except for app in either system or
8467        // vendor path).
8468        // TODO grab this value from PackageSettings
8469        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8470            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8471                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8472            }
8473        }
8474
8475        // TODO: extend to support forward-locked splits
8476        String resourcePath = null;
8477        String baseResourcePath = null;
8478        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
8479            if (ps != null && ps.resourcePathString != null) {
8480                resourcePath = ps.resourcePathString;
8481                baseResourcePath = ps.resourcePathString;
8482            } else {
8483                // Should not happen at all. Just log an error.
8484                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8485            }
8486        } else {
8487            resourcePath = pkg.codePath;
8488            baseResourcePath = pkg.baseCodePath;
8489        }
8490
8491        // Set application objects path explicitly.
8492        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8493        pkg.setApplicationInfoCodePath(pkg.codePath);
8494        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8495        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8496        pkg.setApplicationInfoResourcePath(resourcePath);
8497        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8498        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8499
8500        final int userId = ((user == null) ? 0 : user.getIdentifier());
8501        if (ps != null && ps.getInstantApp(userId)) {
8502            scanFlags |= SCAN_AS_INSTANT_APP;
8503        }
8504
8505        // Note that we invoke the following method only if we are about to unpack an application
8506        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8507                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8508
8509        /*
8510         * If the system app should be overridden by a previously installed
8511         * data, hide the system app now and let the /data/app scan pick it up
8512         * again.
8513         */
8514        if (shouldHideSystemApp) {
8515            synchronized (mPackages) {
8516                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8517            }
8518        }
8519
8520        return scannedPkg;
8521    }
8522
8523    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8524        // Derive the new package synthetic package name
8525        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8526                + pkg.staticSharedLibVersion);
8527    }
8528
8529    private static String fixProcessName(String defProcessName,
8530            String processName) {
8531        if (processName == null) {
8532            return defProcessName;
8533        }
8534        return processName;
8535    }
8536
8537    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8538            throws PackageManagerException {
8539        if (pkgSetting.signatures.mSignatures != null) {
8540            // Already existing package. Make sure signatures match
8541            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8542                    == PackageManager.SIGNATURE_MATCH;
8543            if (!match) {
8544                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8545                        == PackageManager.SIGNATURE_MATCH;
8546            }
8547            if (!match) {
8548                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8549                        == PackageManager.SIGNATURE_MATCH;
8550            }
8551            if (!match) {
8552                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8553                        + pkg.packageName + " signatures do not match the "
8554                        + "previously installed version; ignoring!");
8555            }
8556        }
8557
8558        // Check for shared user signatures
8559        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8560            // Already existing package. Make sure signatures match
8561            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8562                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8563            if (!match) {
8564                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8565                        == PackageManager.SIGNATURE_MATCH;
8566            }
8567            if (!match) {
8568                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8569                        == PackageManager.SIGNATURE_MATCH;
8570            }
8571            if (!match) {
8572                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8573                        "Package " + pkg.packageName
8574                        + " has no signatures that match those in shared user "
8575                        + pkgSetting.sharedUser.name + "; ignoring!");
8576            }
8577        }
8578    }
8579
8580    /**
8581     * Enforces that only the system UID or root's UID can call a method exposed
8582     * via Binder.
8583     *
8584     * @param message used as message if SecurityException is thrown
8585     * @throws SecurityException if the caller is not system or root
8586     */
8587    private static final void enforceSystemOrRoot(String message) {
8588        final int uid = Binder.getCallingUid();
8589        if (uid != Process.SYSTEM_UID && uid != 0) {
8590            throw new SecurityException(message);
8591        }
8592    }
8593
8594    @Override
8595    public void performFstrimIfNeeded() {
8596        enforceSystemOrRoot("Only the system can request fstrim");
8597
8598        // Before everything else, see whether we need to fstrim.
8599        try {
8600            IStorageManager sm = PackageHelper.getStorageManager();
8601            if (sm != null) {
8602                boolean doTrim = false;
8603                final long interval = android.provider.Settings.Global.getLong(
8604                        mContext.getContentResolver(),
8605                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8606                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8607                if (interval > 0) {
8608                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8609                    if (timeSinceLast > interval) {
8610                        doTrim = true;
8611                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8612                                + "; running immediately");
8613                    }
8614                }
8615                if (doTrim) {
8616                    final boolean dexOptDialogShown;
8617                    synchronized (mPackages) {
8618                        dexOptDialogShown = mDexOptDialogShown;
8619                    }
8620                    if (!isFirstBoot() && dexOptDialogShown) {
8621                        try {
8622                            ActivityManager.getService().showBootMessage(
8623                                    mContext.getResources().getString(
8624                                            R.string.android_upgrading_fstrim), true);
8625                        } catch (RemoteException e) {
8626                        }
8627                    }
8628                    sm.runMaintenance();
8629                }
8630            } else {
8631                Slog.e(TAG, "storageManager service unavailable!");
8632            }
8633        } catch (RemoteException e) {
8634            // Can't happen; StorageManagerService is local
8635        }
8636    }
8637
8638    @Override
8639    public void updatePackagesIfNeeded() {
8640        enforceSystemOrRoot("Only the system can request package update");
8641
8642        // We need to re-extract after an OTA.
8643        boolean causeUpgrade = isUpgrade();
8644
8645        // First boot or factory reset.
8646        // Note: we also handle devices that are upgrading to N right now as if it is their
8647        //       first boot, as they do not have profile data.
8648        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8649
8650        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8651        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8652
8653        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8654            return;
8655        }
8656
8657        List<PackageParser.Package> pkgs;
8658        synchronized (mPackages) {
8659            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8660        }
8661
8662        final long startTime = System.nanoTime();
8663        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8664                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8665
8666        final int elapsedTimeSeconds =
8667                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8668
8669        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8670        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8671        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8672        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8673        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8674    }
8675
8676    /**
8677     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8678     * containing statistics about the invocation. The array consists of three elements,
8679     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8680     * and {@code numberOfPackagesFailed}.
8681     */
8682    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8683            String compilerFilter) {
8684
8685        int numberOfPackagesVisited = 0;
8686        int numberOfPackagesOptimized = 0;
8687        int numberOfPackagesSkipped = 0;
8688        int numberOfPackagesFailed = 0;
8689        final int numberOfPackagesToDexopt = pkgs.size();
8690
8691        for (PackageParser.Package pkg : pkgs) {
8692            numberOfPackagesVisited++;
8693
8694            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8695                if (DEBUG_DEXOPT) {
8696                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8697                }
8698                numberOfPackagesSkipped++;
8699                continue;
8700            }
8701
8702            if (DEBUG_DEXOPT) {
8703                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8704                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8705            }
8706
8707            if (showDialog) {
8708                try {
8709                    ActivityManager.getService().showBootMessage(
8710                            mContext.getResources().getString(R.string.android_upgrading_apk,
8711                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8712                } catch (RemoteException e) {
8713                }
8714                synchronized (mPackages) {
8715                    mDexOptDialogShown = true;
8716                }
8717            }
8718
8719            // If the OTA updates a system app which was previously preopted to a non-preopted state
8720            // the app might end up being verified at runtime. That's because by default the apps
8721            // are verify-profile but for preopted apps there's no profile.
8722            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8723            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8724            // filter (by default 'quicken').
8725            // Note that at this stage unused apps are already filtered.
8726            if (isSystemApp(pkg) &&
8727                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8728                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8729                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8730            }
8731
8732            // checkProfiles is false to avoid merging profiles during boot which
8733            // might interfere with background compilation (b/28612421).
8734            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8735            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8736            // trade-off worth doing to save boot time work.
8737            int dexOptStatus = performDexOptTraced(pkg.packageName,
8738                    false /* checkProfiles */,
8739                    compilerFilter,
8740                    false /* force */);
8741            switch (dexOptStatus) {
8742                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8743                    numberOfPackagesOptimized++;
8744                    break;
8745                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8746                    numberOfPackagesSkipped++;
8747                    break;
8748                case PackageDexOptimizer.DEX_OPT_FAILED:
8749                    numberOfPackagesFailed++;
8750                    break;
8751                default:
8752                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8753                    break;
8754            }
8755        }
8756
8757        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8758                numberOfPackagesFailed };
8759    }
8760
8761    @Override
8762    public void notifyPackageUse(String packageName, int reason) {
8763        synchronized (mPackages) {
8764            PackageParser.Package p = mPackages.get(packageName);
8765            if (p == null) {
8766                return;
8767            }
8768            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8769        }
8770    }
8771
8772    @Override
8773    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8774        int userId = UserHandle.getCallingUserId();
8775        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8776        if (ai == null) {
8777            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8778                + loadingPackageName + ", user=" + userId);
8779            return;
8780        }
8781        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8782    }
8783
8784    @Override
8785    public boolean performDexOpt(String packageName,
8786            boolean checkProfiles, int compileReason, boolean force) {
8787        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8788                getCompilerFilterForReason(compileReason), force);
8789        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8790    }
8791
8792    @Override
8793    public boolean performDexOptMode(String packageName,
8794            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8795        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8796                targetCompilerFilter, force);
8797        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8798    }
8799
8800    private int performDexOptTraced(String packageName,
8801                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8802        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8803        try {
8804            return performDexOptInternal(packageName, checkProfiles,
8805                    targetCompilerFilter, force);
8806        } finally {
8807            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8808        }
8809    }
8810
8811    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8812    // if the package can now be considered up to date for the given filter.
8813    private int performDexOptInternal(String packageName,
8814                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8815        PackageParser.Package p;
8816        synchronized (mPackages) {
8817            p = mPackages.get(packageName);
8818            if (p == null) {
8819                // Package could not be found. Report failure.
8820                return PackageDexOptimizer.DEX_OPT_FAILED;
8821            }
8822            mPackageUsage.maybeWriteAsync(mPackages);
8823            mCompilerStats.maybeWriteAsync();
8824        }
8825        long callingId = Binder.clearCallingIdentity();
8826        try {
8827            synchronized (mInstallLock) {
8828                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8829                        targetCompilerFilter, force);
8830            }
8831        } finally {
8832            Binder.restoreCallingIdentity(callingId);
8833        }
8834    }
8835
8836    public ArraySet<String> getOptimizablePackages() {
8837        ArraySet<String> pkgs = new ArraySet<String>();
8838        synchronized (mPackages) {
8839            for (PackageParser.Package p : mPackages.values()) {
8840                if (PackageDexOptimizer.canOptimizePackage(p)) {
8841                    pkgs.add(p.packageName);
8842                }
8843            }
8844        }
8845        return pkgs;
8846    }
8847
8848    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8849            boolean checkProfiles, String targetCompilerFilter,
8850            boolean force) {
8851        // Select the dex optimizer based on the force parameter.
8852        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8853        //       allocate an object here.
8854        PackageDexOptimizer pdo = force
8855                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8856                : mPackageDexOptimizer;
8857
8858        // Dexopt all dependencies first. Note: we ignore the return value and march on
8859        // on errors.
8860        // Note that we are going to call performDexOpt on those libraries as many times as
8861        // they are referenced in packages. When we do a batch of performDexOpt (for example
8862        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
8863        // and the first package that uses the library will dexopt it. The
8864        // others will see that the compiled code for the library is up to date.
8865        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8866        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8867        if (!deps.isEmpty()) {
8868            for (PackageParser.Package depPackage : deps) {
8869                // TODO: Analyze and investigate if we (should) profile libraries.
8870                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8871                        false /* checkProfiles */,
8872                        targetCompilerFilter,
8873                        getOrCreateCompilerPackageStats(depPackage),
8874                        true /* isUsedByOtherApps */);
8875            }
8876        }
8877        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8878                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
8879                mDexManager.isUsedByOtherApps(p.packageName));
8880    }
8881
8882    // Performs dexopt on the used secondary dex files belonging to the given package.
8883    // Returns true if all dex files were process successfully (which could mean either dexopt or
8884    // skip). Returns false if any of the files caused errors.
8885    @Override
8886    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8887            boolean force) {
8888        mDexManager.reconcileSecondaryDexFiles(packageName);
8889        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8890    }
8891
8892    public boolean performDexOptSecondary(String packageName, int compileReason,
8893            boolean force) {
8894        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
8895    }
8896
8897    /**
8898     * Reconcile the information we have about the secondary dex files belonging to
8899     * {@code packagName} and the actual dex files. For all dex files that were
8900     * deleted, update the internal records and delete the generated oat files.
8901     */
8902    @Override
8903    public void reconcileSecondaryDexFiles(String packageName) {
8904        mDexManager.reconcileSecondaryDexFiles(packageName);
8905    }
8906
8907    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8908    // a reference there.
8909    /*package*/ DexManager getDexManager() {
8910        return mDexManager;
8911    }
8912
8913    /**
8914     * Execute the background dexopt job immediately.
8915     */
8916    @Override
8917    public boolean runBackgroundDexoptJob() {
8918        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8919    }
8920
8921    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8922        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8923                || p.usesStaticLibraries != null) {
8924            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8925            Set<String> collectedNames = new HashSet<>();
8926            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8927
8928            retValue.remove(p);
8929
8930            return retValue;
8931        } else {
8932            return Collections.emptyList();
8933        }
8934    }
8935
8936    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8937            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8938        if (!collectedNames.contains(p.packageName)) {
8939            collectedNames.add(p.packageName);
8940            collected.add(p);
8941
8942            if (p.usesLibraries != null) {
8943                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8944                        null, collected, collectedNames);
8945            }
8946            if (p.usesOptionalLibraries != null) {
8947                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8948                        null, collected, collectedNames);
8949            }
8950            if (p.usesStaticLibraries != null) {
8951                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8952                        p.usesStaticLibrariesVersions, collected, collectedNames);
8953            }
8954        }
8955    }
8956
8957    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8958            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8959        final int libNameCount = libs.size();
8960        for (int i = 0; i < libNameCount; i++) {
8961            String libName = libs.get(i);
8962            int version = (versions != null && versions.length == libNameCount)
8963                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8964            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8965            if (libPkg != null) {
8966                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8967            }
8968        }
8969    }
8970
8971    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8972        synchronized (mPackages) {
8973            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8974            if (libEntry != null) {
8975                return mPackages.get(libEntry.apk);
8976            }
8977            return null;
8978        }
8979    }
8980
8981    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8982        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8983        if (versionedLib == null) {
8984            return null;
8985        }
8986        return versionedLib.get(version);
8987    }
8988
8989    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
8990        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
8991                pkg.staticSharedLibName);
8992        if (versionedLib == null) {
8993            return null;
8994        }
8995        int previousLibVersion = -1;
8996        final int versionCount = versionedLib.size();
8997        for (int i = 0; i < versionCount; i++) {
8998            final int libVersion = versionedLib.keyAt(i);
8999            if (libVersion < pkg.staticSharedLibVersion) {
9000                previousLibVersion = Math.max(previousLibVersion, libVersion);
9001            }
9002        }
9003        if (previousLibVersion >= 0) {
9004            return versionedLib.get(previousLibVersion);
9005        }
9006        return null;
9007    }
9008
9009    public void shutdown() {
9010        mPackageUsage.writeNow(mPackages);
9011        mCompilerStats.writeNow();
9012    }
9013
9014    @Override
9015    public void dumpProfiles(String packageName) {
9016        PackageParser.Package pkg;
9017        synchronized (mPackages) {
9018            pkg = mPackages.get(packageName);
9019            if (pkg == null) {
9020                throw new IllegalArgumentException("Unknown package: " + packageName);
9021            }
9022        }
9023        /* Only the shell, root, or the app user should be able to dump profiles. */
9024        int callingUid = Binder.getCallingUid();
9025        if (callingUid != Process.SHELL_UID &&
9026            callingUid != Process.ROOT_UID &&
9027            callingUid != pkg.applicationInfo.uid) {
9028            throw new SecurityException("dumpProfiles");
9029        }
9030
9031        synchronized (mInstallLock) {
9032            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9033            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9034            try {
9035                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9036                String codePaths = TextUtils.join(";", allCodePaths);
9037                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9038            } catch (InstallerException e) {
9039                Slog.w(TAG, "Failed to dump profiles", e);
9040            }
9041            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9042        }
9043    }
9044
9045    @Override
9046    public void forceDexOpt(String packageName) {
9047        enforceSystemOrRoot("forceDexOpt");
9048
9049        PackageParser.Package pkg;
9050        synchronized (mPackages) {
9051            pkg = mPackages.get(packageName);
9052            if (pkg == null) {
9053                throw new IllegalArgumentException("Unknown package: " + packageName);
9054            }
9055        }
9056
9057        synchronized (mInstallLock) {
9058            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9059
9060            // Whoever is calling forceDexOpt wants a compiled package.
9061            // Don't use profiles since that may cause compilation to be skipped.
9062            final int res = performDexOptInternalWithDependenciesLI(pkg,
9063                    false /* checkProfiles */, getDefaultCompilerFilter(),
9064                    true /* force */);
9065
9066            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9067            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9068                throw new IllegalStateException("Failed to dexopt: " + res);
9069            }
9070        }
9071    }
9072
9073    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9074        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9075            Slog.w(TAG, "Unable to update from " + oldPkg.name
9076                    + " to " + newPkg.packageName
9077                    + ": old package not in system partition");
9078            return false;
9079        } else if (mPackages.get(oldPkg.name) != null) {
9080            Slog.w(TAG, "Unable to update from " + oldPkg.name
9081                    + " to " + newPkg.packageName
9082                    + ": old package still exists");
9083            return false;
9084        }
9085        return true;
9086    }
9087
9088    void removeCodePathLI(File codePath) {
9089        if (codePath.isDirectory()) {
9090            try {
9091                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9092            } catch (InstallerException e) {
9093                Slog.w(TAG, "Failed to remove code path", e);
9094            }
9095        } else {
9096            codePath.delete();
9097        }
9098    }
9099
9100    private int[] resolveUserIds(int userId) {
9101        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9102    }
9103
9104    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9105        if (pkg == null) {
9106            Slog.wtf(TAG, "Package was null!", new Throwable());
9107            return;
9108        }
9109        clearAppDataLeafLIF(pkg, userId, flags);
9110        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9111        for (int i = 0; i < childCount; i++) {
9112            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9113        }
9114    }
9115
9116    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9117        final PackageSetting ps;
9118        synchronized (mPackages) {
9119            ps = mSettings.mPackages.get(pkg.packageName);
9120        }
9121        for (int realUserId : resolveUserIds(userId)) {
9122            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9123            try {
9124                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9125                        ceDataInode);
9126            } catch (InstallerException e) {
9127                Slog.w(TAG, String.valueOf(e));
9128            }
9129        }
9130    }
9131
9132    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9133        if (pkg == null) {
9134            Slog.wtf(TAG, "Package was null!", new Throwable());
9135            return;
9136        }
9137        destroyAppDataLeafLIF(pkg, userId, flags);
9138        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9139        for (int i = 0; i < childCount; i++) {
9140            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9141        }
9142    }
9143
9144    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9145        final PackageSetting ps;
9146        synchronized (mPackages) {
9147            ps = mSettings.mPackages.get(pkg.packageName);
9148        }
9149        for (int realUserId : resolveUserIds(userId)) {
9150            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9151            try {
9152                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9153                        ceDataInode);
9154            } catch (InstallerException e) {
9155                Slog.w(TAG, String.valueOf(e));
9156            }
9157            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9158        }
9159    }
9160
9161    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9162        if (pkg == null) {
9163            Slog.wtf(TAG, "Package was null!", new Throwable());
9164            return;
9165        }
9166        destroyAppProfilesLeafLIF(pkg);
9167        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9168        for (int i = 0; i < childCount; i++) {
9169            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9170        }
9171    }
9172
9173    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9174        try {
9175            mInstaller.destroyAppProfiles(pkg.packageName);
9176        } catch (InstallerException e) {
9177            Slog.w(TAG, String.valueOf(e));
9178        }
9179    }
9180
9181    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9182        if (pkg == null) {
9183            Slog.wtf(TAG, "Package was null!", new Throwable());
9184            return;
9185        }
9186        clearAppProfilesLeafLIF(pkg);
9187        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9188        for (int i = 0; i < childCount; i++) {
9189            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9190        }
9191    }
9192
9193    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9194        try {
9195            mInstaller.clearAppProfiles(pkg.packageName);
9196        } catch (InstallerException e) {
9197            Slog.w(TAG, String.valueOf(e));
9198        }
9199    }
9200
9201    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9202            long lastUpdateTime) {
9203        // Set parent install/update time
9204        PackageSetting ps = (PackageSetting) pkg.mExtras;
9205        if (ps != null) {
9206            ps.firstInstallTime = firstInstallTime;
9207            ps.lastUpdateTime = lastUpdateTime;
9208        }
9209        // Set children install/update time
9210        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9211        for (int i = 0; i < childCount; i++) {
9212            PackageParser.Package childPkg = pkg.childPackages.get(i);
9213            ps = (PackageSetting) childPkg.mExtras;
9214            if (ps != null) {
9215                ps.firstInstallTime = firstInstallTime;
9216                ps.lastUpdateTime = lastUpdateTime;
9217            }
9218        }
9219    }
9220
9221    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9222            PackageParser.Package changingLib) {
9223        if (file.path != null) {
9224            usesLibraryFiles.add(file.path);
9225            return;
9226        }
9227        PackageParser.Package p = mPackages.get(file.apk);
9228        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9229            // If we are doing this while in the middle of updating a library apk,
9230            // then we need to make sure to use that new apk for determining the
9231            // dependencies here.  (We haven't yet finished committing the new apk
9232            // to the package manager state.)
9233            if (p == null || p.packageName.equals(changingLib.packageName)) {
9234                p = changingLib;
9235            }
9236        }
9237        if (p != null) {
9238            usesLibraryFiles.addAll(p.getAllCodePaths());
9239        }
9240    }
9241
9242    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9243            PackageParser.Package changingLib) throws PackageManagerException {
9244        if (pkg == null) {
9245            return;
9246        }
9247        ArraySet<String> usesLibraryFiles = null;
9248        if (pkg.usesLibraries != null) {
9249            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9250                    null, null, pkg.packageName, changingLib, true, null);
9251        }
9252        if (pkg.usesStaticLibraries != null) {
9253            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9254                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9255                    pkg.packageName, changingLib, true, usesLibraryFiles);
9256        }
9257        if (pkg.usesOptionalLibraries != null) {
9258            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9259                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
9260        }
9261        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9262            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9263        } else {
9264            pkg.usesLibraryFiles = null;
9265        }
9266    }
9267
9268    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9269            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
9270            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9271            boolean required, @Nullable ArraySet<String> outUsedLibraries)
9272            throws PackageManagerException {
9273        final int libCount = requestedLibraries.size();
9274        for (int i = 0; i < libCount; i++) {
9275            final String libName = requestedLibraries.get(i);
9276            final int libVersion = requiredVersions != null ? requiredVersions[i]
9277                    : SharedLibraryInfo.VERSION_UNDEFINED;
9278            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9279            if (libEntry == null) {
9280                if (required) {
9281                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9282                            "Package " + packageName + " requires unavailable shared library "
9283                                    + libName + "; failing!");
9284                } else {
9285                    Slog.w(TAG, "Package " + packageName
9286                            + " desires unavailable shared library "
9287                            + libName + "; ignoring!");
9288                }
9289            } else {
9290                if (requiredVersions != null && requiredCertDigests != null) {
9291                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9292                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9293                            "Package " + packageName + " requires unavailable static shared"
9294                                    + " library " + libName + " version "
9295                                    + libEntry.info.getVersion() + "; failing!");
9296                    }
9297
9298                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9299                    if (libPkg == null) {
9300                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9301                                "Package " + packageName + " requires unavailable static shared"
9302                                        + " library; failing!");
9303                    }
9304
9305                    String expectedCertDigest = requiredCertDigests[i];
9306                    String libCertDigest = PackageUtils.computeCertSha256Digest(
9307                                libPkg.mSignatures[0]);
9308                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
9309                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9310                                "Package " + packageName + " requires differently signed" +
9311                                        " static shared library; failing!");
9312                    }
9313                }
9314
9315                if (outUsedLibraries == null) {
9316                    outUsedLibraries = new ArraySet<>();
9317                }
9318                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9319            }
9320        }
9321        return outUsedLibraries;
9322    }
9323
9324    private static boolean hasString(List<String> list, List<String> which) {
9325        if (list == null) {
9326            return false;
9327        }
9328        for (int i=list.size()-1; i>=0; i--) {
9329            for (int j=which.size()-1; j>=0; j--) {
9330                if (which.get(j).equals(list.get(i))) {
9331                    return true;
9332                }
9333            }
9334        }
9335        return false;
9336    }
9337
9338    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9339            PackageParser.Package changingPkg) {
9340        ArrayList<PackageParser.Package> res = null;
9341        for (PackageParser.Package pkg : mPackages.values()) {
9342            if (changingPkg != null
9343                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9344                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9345                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9346                            changingPkg.staticSharedLibName)) {
9347                return null;
9348            }
9349            if (res == null) {
9350                res = new ArrayList<>();
9351            }
9352            res.add(pkg);
9353            try {
9354                updateSharedLibrariesLPr(pkg, changingPkg);
9355            } catch (PackageManagerException e) {
9356                // If a system app update or an app and a required lib missing we
9357                // delete the package and for updated system apps keep the data as
9358                // it is better for the user to reinstall than to be in an limbo
9359                // state. Also libs disappearing under an app should never happen
9360                // - just in case.
9361                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
9362                    final int flags = pkg.isUpdatedSystemApp()
9363                            ? PackageManager.DELETE_KEEP_DATA : 0;
9364                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9365                            flags , null, true, null);
9366                }
9367                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9368            }
9369        }
9370        return res;
9371    }
9372
9373    /**
9374     * Derive the value of the {@code cpuAbiOverride} based on the provided
9375     * value and an optional stored value from the package settings.
9376     */
9377    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
9378        String cpuAbiOverride = null;
9379
9380        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
9381            cpuAbiOverride = null;
9382        } else if (abiOverride != null) {
9383            cpuAbiOverride = abiOverride;
9384        } else if (settings != null) {
9385            cpuAbiOverride = settings.cpuAbiOverrideString;
9386        }
9387
9388        return cpuAbiOverride;
9389    }
9390
9391    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9392            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9393                    throws PackageManagerException {
9394        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9395        // If the package has children and this is the first dive in the function
9396        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9397        // whether all packages (parent and children) would be successfully scanned
9398        // before the actual scan since scanning mutates internal state and we want
9399        // to atomically install the package and its children.
9400        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9401            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9402                scanFlags |= SCAN_CHECK_ONLY;
9403            }
9404        } else {
9405            scanFlags &= ~SCAN_CHECK_ONLY;
9406        }
9407
9408        final PackageParser.Package scannedPkg;
9409        try {
9410            // Scan the parent
9411            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
9412            // Scan the children
9413            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9414            for (int i = 0; i < childCount; i++) {
9415                PackageParser.Package childPkg = pkg.childPackages.get(i);
9416                scanPackageLI(childPkg, policyFlags,
9417                        scanFlags, currentTime, user);
9418            }
9419        } finally {
9420            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9421        }
9422
9423        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9424            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
9425        }
9426
9427        return scannedPkg;
9428    }
9429
9430    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
9431            int scanFlags, long currentTime, @Nullable UserHandle user)
9432                    throws PackageManagerException {
9433        boolean success = false;
9434        try {
9435            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9436                    currentTime, user);
9437            success = true;
9438            return res;
9439        } finally {
9440            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9441                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9442                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9443                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9444                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9445            }
9446        }
9447    }
9448
9449    /**
9450     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9451     */
9452    private static boolean apkHasCode(String fileName) {
9453        StrictJarFile jarFile = null;
9454        try {
9455            jarFile = new StrictJarFile(fileName,
9456                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9457            return jarFile.findEntry("classes.dex") != null;
9458        } catch (IOException ignore) {
9459        } finally {
9460            try {
9461                if (jarFile != null) {
9462                    jarFile.close();
9463                }
9464            } catch (IOException ignore) {}
9465        }
9466        return false;
9467    }
9468
9469    /**
9470     * Enforces code policy for the package. This ensures that if an APK has
9471     * declared hasCode="true" in its manifest that the APK actually contains
9472     * code.
9473     *
9474     * @throws PackageManagerException If bytecode could not be found when it should exist
9475     */
9476    private static void assertCodePolicy(PackageParser.Package pkg)
9477            throws PackageManagerException {
9478        final boolean shouldHaveCode =
9479                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9480        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9481            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9482                    "Package " + pkg.baseCodePath + " code is missing");
9483        }
9484
9485        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9486            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9487                final boolean splitShouldHaveCode =
9488                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9489                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9490                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9491                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9492                }
9493            }
9494        }
9495    }
9496
9497    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9498            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
9499                    throws PackageManagerException {
9500        if (DEBUG_PACKAGE_SCANNING) {
9501            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9502                Log.d(TAG, "Scanning package " + pkg.packageName);
9503        }
9504
9505        applyPolicy(pkg, policyFlags);
9506
9507        assertPackageIsValid(pkg, policyFlags, scanFlags);
9508
9509        // Initialize package source and resource directories
9510        final File scanFile = new File(pkg.codePath);
9511        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9512        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9513
9514        SharedUserSetting suid = null;
9515        PackageSetting pkgSetting = null;
9516
9517        // Getting the package setting may have a side-effect, so if we
9518        // are only checking if scan would succeed, stash a copy of the
9519        // old setting to restore at the end.
9520        PackageSetting nonMutatedPs = null;
9521
9522        // We keep references to the derived CPU Abis from settings in oder to reuse
9523        // them in the case where we're not upgrading or booting for the first time.
9524        String primaryCpuAbiFromSettings = null;
9525        String secondaryCpuAbiFromSettings = null;
9526
9527        // writer
9528        synchronized (mPackages) {
9529            if (pkg.mSharedUserId != null) {
9530                // SIDE EFFECTS; may potentially allocate a new shared user
9531                suid = mSettings.getSharedUserLPw(
9532                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9533                if (DEBUG_PACKAGE_SCANNING) {
9534                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9535                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9536                                + "): packages=" + suid.packages);
9537                }
9538            }
9539
9540            // Check if we are renaming from an original package name.
9541            PackageSetting origPackage = null;
9542            String realName = null;
9543            if (pkg.mOriginalPackages != null) {
9544                // This package may need to be renamed to a previously
9545                // installed name.  Let's check on that...
9546                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9547                if (pkg.mOriginalPackages.contains(renamed)) {
9548                    // This package had originally been installed as the
9549                    // original name, and we have already taken care of
9550                    // transitioning to the new one.  Just update the new
9551                    // one to continue using the old name.
9552                    realName = pkg.mRealPackage;
9553                    if (!pkg.packageName.equals(renamed)) {
9554                        // Callers into this function may have already taken
9555                        // care of renaming the package; only do it here if
9556                        // it is not already done.
9557                        pkg.setPackageName(renamed);
9558                    }
9559                } else {
9560                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9561                        if ((origPackage = mSettings.getPackageLPr(
9562                                pkg.mOriginalPackages.get(i))) != null) {
9563                            // We do have the package already installed under its
9564                            // original name...  should we use it?
9565                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9566                                // New package is not compatible with original.
9567                                origPackage = null;
9568                                continue;
9569                            } else if (origPackage.sharedUser != null) {
9570                                // Make sure uid is compatible between packages.
9571                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9572                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9573                                            + " to " + pkg.packageName + ": old uid "
9574                                            + origPackage.sharedUser.name
9575                                            + " differs from " + pkg.mSharedUserId);
9576                                    origPackage = null;
9577                                    continue;
9578                                }
9579                                // TODO: Add case when shared user id is added [b/28144775]
9580                            } else {
9581                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9582                                        + pkg.packageName + " to old name " + origPackage.name);
9583                            }
9584                            break;
9585                        }
9586                    }
9587                }
9588            }
9589
9590            if (mTransferedPackages.contains(pkg.packageName)) {
9591                Slog.w(TAG, "Package " + pkg.packageName
9592                        + " was transferred to another, but its .apk remains");
9593            }
9594
9595            // See comments in nonMutatedPs declaration
9596            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9597                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9598                if (foundPs != null) {
9599                    nonMutatedPs = new PackageSetting(foundPs);
9600                }
9601            }
9602
9603            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9604                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9605                if (foundPs != null) {
9606                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9607                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9608                }
9609            }
9610
9611            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9612            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9613                PackageManagerService.reportSettingsProblem(Log.WARN,
9614                        "Package " + pkg.packageName + " shared user changed from "
9615                                + (pkgSetting.sharedUser != null
9616                                        ? pkgSetting.sharedUser.name : "<nothing>")
9617                                + " to "
9618                                + (suid != null ? suid.name : "<nothing>")
9619                                + "; replacing with new");
9620                pkgSetting = null;
9621            }
9622            final PackageSetting oldPkgSetting =
9623                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9624            final PackageSetting disabledPkgSetting =
9625                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9626
9627            String[] usesStaticLibraries = null;
9628            if (pkg.usesStaticLibraries != null) {
9629                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9630                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9631            }
9632
9633            if (pkgSetting == null) {
9634                final String parentPackageName = (pkg.parentPackage != null)
9635                        ? pkg.parentPackage.packageName : null;
9636                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9637                // REMOVE SharedUserSetting from method; update in a separate call
9638                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9639                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9640                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9641                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9642                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9643                        true /*allowInstall*/, instantApp, parentPackageName,
9644                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
9645                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
9646                // SIDE EFFECTS; updates system state; move elsewhere
9647                if (origPackage != null) {
9648                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9649                }
9650                mSettings.addUserToSettingLPw(pkgSetting);
9651            } else {
9652                // REMOVE SharedUserSetting from method; update in a separate call.
9653                //
9654                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9655                // secondaryCpuAbi are not known at this point so we always update them
9656                // to null here, only to reset them at a later point.
9657                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9658                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9659                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9660                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9661                        UserManagerService.getInstance(), usesStaticLibraries,
9662                        pkg.usesStaticLibrariesVersions);
9663            }
9664            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9665            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9666
9667            // SIDE EFFECTS; modifies system state; move elsewhere
9668            if (pkgSetting.origPackage != null) {
9669                // If we are first transitioning from an original package,
9670                // fix up the new package's name now.  We need to do this after
9671                // looking up the package under its new name, so getPackageLP
9672                // can take care of fiddling things correctly.
9673                pkg.setPackageName(origPackage.name);
9674
9675                // File a report about this.
9676                String msg = "New package " + pkgSetting.realName
9677                        + " renamed to replace old package " + pkgSetting.name;
9678                reportSettingsProblem(Log.WARN, msg);
9679
9680                // Make a note of it.
9681                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9682                    mTransferedPackages.add(origPackage.name);
9683                }
9684
9685                // No longer need to retain this.
9686                pkgSetting.origPackage = null;
9687            }
9688
9689            // SIDE EFFECTS; modifies system state; move elsewhere
9690            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9691                // Make a note of it.
9692                mTransferedPackages.add(pkg.packageName);
9693            }
9694
9695            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9696                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9697            }
9698
9699            if ((scanFlags & SCAN_BOOTING) == 0
9700                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9701                // Check all shared libraries and map to their actual file path.
9702                // We only do this here for apps not on a system dir, because those
9703                // are the only ones that can fail an install due to this.  We
9704                // will take care of the system apps by updating all of their
9705                // library paths after the scan is done. Also during the initial
9706                // scan don't update any libs as we do this wholesale after all
9707                // apps are scanned to avoid dependency based scanning.
9708                updateSharedLibrariesLPr(pkg, null);
9709            }
9710
9711            if (mFoundPolicyFile) {
9712                SELinuxMMAC.assignSeInfoValue(pkg);
9713            }
9714            pkg.applicationInfo.uid = pkgSetting.appId;
9715            pkg.mExtras = pkgSetting;
9716
9717
9718            // Static shared libs have same package with different versions where
9719            // we internally use a synthetic package name to allow multiple versions
9720            // of the same package, therefore we need to compare signatures against
9721            // the package setting for the latest library version.
9722            PackageSetting signatureCheckPs = pkgSetting;
9723            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9724                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9725                if (libraryEntry != null) {
9726                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9727                }
9728            }
9729
9730            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9731                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9732                    // We just determined the app is signed correctly, so bring
9733                    // over the latest parsed certs.
9734                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9735                } else {
9736                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9737                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9738                                "Package " + pkg.packageName + " upgrade keys do not match the "
9739                                + "previously installed version");
9740                    } else {
9741                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9742                        String msg = "System package " + pkg.packageName
9743                                + " signature changed; retaining data.";
9744                        reportSettingsProblem(Log.WARN, msg);
9745                    }
9746                }
9747            } else {
9748                try {
9749                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9750                    verifySignaturesLP(signatureCheckPs, pkg);
9751                    // We just determined the app is signed correctly, so bring
9752                    // over the latest parsed certs.
9753                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9754                } catch (PackageManagerException e) {
9755                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9756                        throw e;
9757                    }
9758                    // The signature has changed, but this package is in the system
9759                    // image...  let's recover!
9760                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9761                    // However...  if this package is part of a shared user, but it
9762                    // doesn't match the signature of the shared user, let's fail.
9763                    // What this means is that you can't change the signatures
9764                    // associated with an overall shared user, which doesn't seem all
9765                    // that unreasonable.
9766                    if (signatureCheckPs.sharedUser != null) {
9767                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9768                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9769                            throw new PackageManagerException(
9770                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9771                                    "Signature mismatch for shared user: "
9772                                            + pkgSetting.sharedUser);
9773                        }
9774                    }
9775                    // File a report about this.
9776                    String msg = "System package " + pkg.packageName
9777                            + " signature changed; retaining data.";
9778                    reportSettingsProblem(Log.WARN, msg);
9779                }
9780            }
9781
9782            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9783                // This package wants to adopt ownership of permissions from
9784                // another package.
9785                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9786                    final String origName = pkg.mAdoptPermissions.get(i);
9787                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9788                    if (orig != null) {
9789                        if (verifyPackageUpdateLPr(orig, pkg)) {
9790                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9791                                    + pkg.packageName);
9792                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9793                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9794                        }
9795                    }
9796                }
9797            }
9798        }
9799
9800        pkg.applicationInfo.processName = fixProcessName(
9801                pkg.applicationInfo.packageName,
9802                pkg.applicationInfo.processName);
9803
9804        if (pkg != mPlatformPackage) {
9805            // Get all of our default paths setup
9806            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9807        }
9808
9809        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9810
9811        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9812            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9813                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9814                derivePackageAbi(
9815                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9816                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9817
9818                // Some system apps still use directory structure for native libraries
9819                // in which case we might end up not detecting abi solely based on apk
9820                // structure. Try to detect abi based on directory structure.
9821                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9822                        pkg.applicationInfo.primaryCpuAbi == null) {
9823                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9824                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9825                }
9826            } else {
9827                // This is not a first boot or an upgrade, don't bother deriving the
9828                // ABI during the scan. Instead, trust the value that was stored in the
9829                // package setting.
9830                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9831                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9832
9833                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9834
9835                if (DEBUG_ABI_SELECTION) {
9836                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9837                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9838                        pkg.applicationInfo.secondaryCpuAbi);
9839                }
9840            }
9841        } else {
9842            if ((scanFlags & SCAN_MOVE) != 0) {
9843                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9844                // but we already have this packages package info in the PackageSetting. We just
9845                // use that and derive the native library path based on the new codepath.
9846                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9847                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9848            }
9849
9850            // Set native library paths again. For moves, the path will be updated based on the
9851            // ABIs we've determined above. For non-moves, the path will be updated based on the
9852            // ABIs we determined during compilation, but the path will depend on the final
9853            // package path (after the rename away from the stage path).
9854            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9855        }
9856
9857        // This is a special case for the "system" package, where the ABI is
9858        // dictated by the zygote configuration (and init.rc). We should keep track
9859        // of this ABI so that we can deal with "normal" applications that run under
9860        // the same UID correctly.
9861        if (mPlatformPackage == pkg) {
9862            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9863                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9864        }
9865
9866        // If there's a mismatch between the abi-override in the package setting
9867        // and the abiOverride specified for the install. Warn about this because we
9868        // would've already compiled the app without taking the package setting into
9869        // account.
9870        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9871            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9872                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9873                        " for package " + pkg.packageName);
9874            }
9875        }
9876
9877        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9878        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9879        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9880
9881        // Copy the derived override back to the parsed package, so that we can
9882        // update the package settings accordingly.
9883        pkg.cpuAbiOverride = cpuAbiOverride;
9884
9885        if (DEBUG_ABI_SELECTION) {
9886            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9887                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9888                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9889        }
9890
9891        // Push the derived path down into PackageSettings so we know what to
9892        // clean up at uninstall time.
9893        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9894
9895        if (DEBUG_ABI_SELECTION) {
9896            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9897                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9898                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9899        }
9900
9901        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9902        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9903            // We don't do this here during boot because we can do it all
9904            // at once after scanning all existing packages.
9905            //
9906            // We also do this *before* we perform dexopt on this package, so that
9907            // we can avoid redundant dexopts, and also to make sure we've got the
9908            // code and package path correct.
9909            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9910        }
9911
9912        if (mFactoryTest && pkg.requestedPermissions.contains(
9913                android.Manifest.permission.FACTORY_TEST)) {
9914            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9915        }
9916
9917        if (isSystemApp(pkg)) {
9918            pkgSetting.isOrphaned = true;
9919        }
9920
9921        // Take care of first install / last update times.
9922        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9923        if (currentTime != 0) {
9924            if (pkgSetting.firstInstallTime == 0) {
9925                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9926            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9927                pkgSetting.lastUpdateTime = currentTime;
9928            }
9929        } else if (pkgSetting.firstInstallTime == 0) {
9930            // We need *something*.  Take time time stamp of the file.
9931            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9932        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9933            if (scanFileTime != pkgSetting.timeStamp) {
9934                // A package on the system image has changed; consider this
9935                // to be an update.
9936                pkgSetting.lastUpdateTime = scanFileTime;
9937            }
9938        }
9939        pkgSetting.setTimeStamp(scanFileTime);
9940
9941        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9942            if (nonMutatedPs != null) {
9943                synchronized (mPackages) {
9944                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9945                }
9946            }
9947        } else {
9948            final int userId = user == null ? 0 : user.getIdentifier();
9949            // Modify state for the given package setting
9950            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9951                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9952            if (pkgSetting.getInstantApp(userId)) {
9953                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9954            }
9955        }
9956        return pkg;
9957    }
9958
9959    /**
9960     * Applies policy to the parsed package based upon the given policy flags.
9961     * Ensures the package is in a good state.
9962     * <p>
9963     * Implementation detail: This method must NOT have any side effect. It would
9964     * ideally be static, but, it requires locks to read system state.
9965     */
9966    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9967        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9968            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9969            if (pkg.applicationInfo.isDirectBootAware()) {
9970                // we're direct boot aware; set for all components
9971                for (PackageParser.Service s : pkg.services) {
9972                    s.info.encryptionAware = s.info.directBootAware = true;
9973                }
9974                for (PackageParser.Provider p : pkg.providers) {
9975                    p.info.encryptionAware = p.info.directBootAware = true;
9976                }
9977                for (PackageParser.Activity a : pkg.activities) {
9978                    a.info.encryptionAware = a.info.directBootAware = true;
9979                }
9980                for (PackageParser.Activity r : pkg.receivers) {
9981                    r.info.encryptionAware = r.info.directBootAware = true;
9982                }
9983            }
9984        } else {
9985            // Only allow system apps to be flagged as core apps.
9986            pkg.coreApp = false;
9987            // clear flags not applicable to regular apps
9988            pkg.applicationInfo.privateFlags &=
9989                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
9990            pkg.applicationInfo.privateFlags &=
9991                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
9992        }
9993        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
9994
9995        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
9996            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9997        }
9998
9999        if (!isSystemApp(pkg)) {
10000            // Only system apps can use these features.
10001            pkg.mOriginalPackages = null;
10002            pkg.mRealPackage = null;
10003            pkg.mAdoptPermissions = null;
10004        }
10005    }
10006
10007    /**
10008     * Asserts the parsed package is valid according to the given policy. If the
10009     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10010     * <p>
10011     * Implementation detail: This method must NOT have any side effects. It would
10012     * ideally be static, but, it requires locks to read system state.
10013     *
10014     * @throws PackageManagerException If the package fails any of the validation checks
10015     */
10016    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10017            throws PackageManagerException {
10018        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10019            assertCodePolicy(pkg);
10020        }
10021
10022        if (pkg.applicationInfo.getCodePath() == null ||
10023                pkg.applicationInfo.getResourcePath() == null) {
10024            // Bail out. The resource and code paths haven't been set.
10025            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10026                    "Code and resource paths haven't been set correctly");
10027        }
10028
10029        // Make sure we're not adding any bogus keyset info
10030        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10031        ksms.assertScannedPackageValid(pkg);
10032
10033        synchronized (mPackages) {
10034            // The special "android" package can only be defined once
10035            if (pkg.packageName.equals("android")) {
10036                if (mAndroidApplication != null) {
10037                    Slog.w(TAG, "*************************************************");
10038                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10039                    Slog.w(TAG, " codePath=" + pkg.codePath);
10040                    Slog.w(TAG, "*************************************************");
10041                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10042                            "Core android package being redefined.  Skipping.");
10043                }
10044            }
10045
10046            // A package name must be unique; don't allow duplicates
10047            if (mPackages.containsKey(pkg.packageName)) {
10048                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10049                        "Application package " + pkg.packageName
10050                        + " already installed.  Skipping duplicate.");
10051            }
10052
10053            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10054                // Static libs have a synthetic package name containing the version
10055                // but we still want the base name to be unique.
10056                if (mPackages.containsKey(pkg.manifestPackageName)) {
10057                    throw new PackageManagerException(
10058                            "Duplicate static shared lib provider package");
10059                }
10060
10061                // Static shared libraries should have at least O target SDK
10062                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10063                    throw new PackageManagerException(
10064                            "Packages declaring static-shared libs must target O SDK or higher");
10065                }
10066
10067                // Package declaring static a shared lib cannot be instant apps
10068                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10069                    throw new PackageManagerException(
10070                            "Packages declaring static-shared libs cannot be instant apps");
10071                }
10072
10073                // Package declaring static a shared lib cannot be renamed since the package
10074                // name is synthetic and apps can't code around package manager internals.
10075                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10076                    throw new PackageManagerException(
10077                            "Packages declaring static-shared libs cannot be renamed");
10078                }
10079
10080                // Package declaring static a shared lib cannot declare child packages
10081                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10082                    throw new PackageManagerException(
10083                            "Packages declaring static-shared libs cannot have child packages");
10084                }
10085
10086                // Package declaring static a shared lib cannot declare dynamic libs
10087                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10088                    throw new PackageManagerException(
10089                            "Packages declaring static-shared libs cannot declare dynamic libs");
10090                }
10091
10092                // Package declaring static a shared lib cannot declare shared users
10093                if (pkg.mSharedUserId != null) {
10094                    throw new PackageManagerException(
10095                            "Packages declaring static-shared libs cannot declare shared users");
10096                }
10097
10098                // Static shared libs cannot declare activities
10099                if (!pkg.activities.isEmpty()) {
10100                    throw new PackageManagerException(
10101                            "Static shared libs cannot declare activities");
10102                }
10103
10104                // Static shared libs cannot declare services
10105                if (!pkg.services.isEmpty()) {
10106                    throw new PackageManagerException(
10107                            "Static shared libs cannot declare services");
10108                }
10109
10110                // Static shared libs cannot declare providers
10111                if (!pkg.providers.isEmpty()) {
10112                    throw new PackageManagerException(
10113                            "Static shared libs cannot declare content providers");
10114                }
10115
10116                // Static shared libs cannot declare receivers
10117                if (!pkg.receivers.isEmpty()) {
10118                    throw new PackageManagerException(
10119                            "Static shared libs cannot declare broadcast receivers");
10120                }
10121
10122                // Static shared libs cannot declare permission groups
10123                if (!pkg.permissionGroups.isEmpty()) {
10124                    throw new PackageManagerException(
10125                            "Static shared libs cannot declare permission groups");
10126                }
10127
10128                // Static shared libs cannot declare permissions
10129                if (!pkg.permissions.isEmpty()) {
10130                    throw new PackageManagerException(
10131                            "Static shared libs cannot declare permissions");
10132                }
10133
10134                // Static shared libs cannot declare protected broadcasts
10135                if (pkg.protectedBroadcasts != null) {
10136                    throw new PackageManagerException(
10137                            "Static shared libs cannot declare protected broadcasts");
10138                }
10139
10140                // Static shared libs cannot be overlay targets
10141                if (pkg.mOverlayTarget != null) {
10142                    throw new PackageManagerException(
10143                            "Static shared libs cannot be overlay targets");
10144                }
10145
10146                // The version codes must be ordered as lib versions
10147                int minVersionCode = Integer.MIN_VALUE;
10148                int maxVersionCode = Integer.MAX_VALUE;
10149
10150                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10151                        pkg.staticSharedLibName);
10152                if (versionedLib != null) {
10153                    final int versionCount = versionedLib.size();
10154                    for (int i = 0; i < versionCount; i++) {
10155                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10156                        // TODO: We will change version code to long, so in the new API it is long
10157                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
10158                                .getVersionCode();
10159                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10160                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10161                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10162                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10163                        } else {
10164                            minVersionCode = maxVersionCode = libVersionCode;
10165                            break;
10166                        }
10167                    }
10168                }
10169                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10170                    throw new PackageManagerException("Static shared"
10171                            + " lib version codes must be ordered as lib versions");
10172                }
10173            }
10174
10175            // Only privileged apps and updated privileged apps can add child packages.
10176            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10177                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10178                    throw new PackageManagerException("Only privileged apps can add child "
10179                            + "packages. Ignoring package " + pkg.packageName);
10180                }
10181                final int childCount = pkg.childPackages.size();
10182                for (int i = 0; i < childCount; i++) {
10183                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10184                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10185                            childPkg.packageName)) {
10186                        throw new PackageManagerException("Can't override child of "
10187                                + "another disabled app. Ignoring package " + pkg.packageName);
10188                    }
10189                }
10190            }
10191
10192            // If we're only installing presumed-existing packages, require that the
10193            // scanned APK is both already known and at the path previously established
10194            // for it.  Previously unknown packages we pick up normally, but if we have an
10195            // a priori expectation about this package's install presence, enforce it.
10196            // With a singular exception for new system packages. When an OTA contains
10197            // a new system package, we allow the codepath to change from a system location
10198            // to the user-installed location. If we don't allow this change, any newer,
10199            // user-installed version of the application will be ignored.
10200            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10201                if (mExpectingBetter.containsKey(pkg.packageName)) {
10202                    logCriticalInfo(Log.WARN,
10203                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10204                } else {
10205                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10206                    if (known != null) {
10207                        if (DEBUG_PACKAGE_SCANNING) {
10208                            Log.d(TAG, "Examining " + pkg.codePath
10209                                    + " and requiring known paths " + known.codePathString
10210                                    + " & " + known.resourcePathString);
10211                        }
10212                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10213                                || !pkg.applicationInfo.getResourcePath().equals(
10214                                        known.resourcePathString)) {
10215                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10216                                    "Application package " + pkg.packageName
10217                                    + " found at " + pkg.applicationInfo.getCodePath()
10218                                    + " but expected at " + known.codePathString
10219                                    + "; ignoring.");
10220                        }
10221                    }
10222                }
10223            }
10224
10225            // Verify that this new package doesn't have any content providers
10226            // that conflict with existing packages.  Only do this if the
10227            // package isn't already installed, since we don't want to break
10228            // things that are installed.
10229            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10230                final int N = pkg.providers.size();
10231                int i;
10232                for (i=0; i<N; i++) {
10233                    PackageParser.Provider p = pkg.providers.get(i);
10234                    if (p.info.authority != null) {
10235                        String names[] = p.info.authority.split(";");
10236                        for (int j = 0; j < names.length; j++) {
10237                            if (mProvidersByAuthority.containsKey(names[j])) {
10238                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10239                                final String otherPackageName =
10240                                        ((other != null && other.getComponentName() != null) ?
10241                                                other.getComponentName().getPackageName() : "?");
10242                                throw new PackageManagerException(
10243                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10244                                        "Can't install because provider name " + names[j]
10245                                                + " (in package " + pkg.applicationInfo.packageName
10246                                                + ") is already used by " + otherPackageName);
10247                            }
10248                        }
10249                    }
10250                }
10251            }
10252        }
10253    }
10254
10255    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10256            int type, String declaringPackageName, int declaringVersionCode) {
10257        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10258        if (versionedLib == null) {
10259            versionedLib = new SparseArray<>();
10260            mSharedLibraries.put(name, versionedLib);
10261            if (type == SharedLibraryInfo.TYPE_STATIC) {
10262                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10263            }
10264        } else if (versionedLib.indexOfKey(version) >= 0) {
10265            return false;
10266        }
10267        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10268                version, type, declaringPackageName, declaringVersionCode);
10269        versionedLib.put(version, libEntry);
10270        return true;
10271    }
10272
10273    private boolean removeSharedLibraryLPw(String name, int version) {
10274        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10275        if (versionedLib == null) {
10276            return false;
10277        }
10278        final int libIdx = versionedLib.indexOfKey(version);
10279        if (libIdx < 0) {
10280            return false;
10281        }
10282        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10283        versionedLib.remove(version);
10284        if (versionedLib.size() <= 0) {
10285            mSharedLibraries.remove(name);
10286            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10287                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10288                        .getPackageName());
10289            }
10290        }
10291        return true;
10292    }
10293
10294    /**
10295     * Adds a scanned package to the system. When this method is finished, the package will
10296     * be available for query, resolution, etc...
10297     */
10298    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10299            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
10300        final String pkgName = pkg.packageName;
10301        if (mCustomResolverComponentName != null &&
10302                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10303            setUpCustomResolverActivity(pkg);
10304        }
10305
10306        if (pkg.packageName.equals("android")) {
10307            synchronized (mPackages) {
10308                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10309                    // Set up information for our fall-back user intent resolution activity.
10310                    mPlatformPackage = pkg;
10311                    pkg.mVersionCode = mSdkVersion;
10312                    mAndroidApplication = pkg.applicationInfo;
10313                    if (!mResolverReplaced) {
10314                        mResolveActivity.applicationInfo = mAndroidApplication;
10315                        mResolveActivity.name = ResolverActivity.class.getName();
10316                        mResolveActivity.packageName = mAndroidApplication.packageName;
10317                        mResolveActivity.processName = "system:ui";
10318                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10319                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10320                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10321                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10322                        mResolveActivity.exported = true;
10323                        mResolveActivity.enabled = true;
10324                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10325                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10326                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10327                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10328                                | ActivityInfo.CONFIG_ORIENTATION
10329                                | ActivityInfo.CONFIG_KEYBOARD
10330                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10331                        mResolveInfo.activityInfo = mResolveActivity;
10332                        mResolveInfo.priority = 0;
10333                        mResolveInfo.preferredOrder = 0;
10334                        mResolveInfo.match = 0;
10335                        mResolveComponentName = new ComponentName(
10336                                mAndroidApplication.packageName, mResolveActivity.name);
10337                    }
10338                }
10339            }
10340        }
10341
10342        ArrayList<PackageParser.Package> clientLibPkgs = null;
10343        // writer
10344        synchronized (mPackages) {
10345            boolean hasStaticSharedLibs = false;
10346
10347            // Any app can add new static shared libraries
10348            if (pkg.staticSharedLibName != null) {
10349                // Static shared libs don't allow renaming as they have synthetic package
10350                // names to allow install of multiple versions, so use name from manifest.
10351                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10352                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10353                        pkg.manifestPackageName, pkg.mVersionCode)) {
10354                    hasStaticSharedLibs = true;
10355                } else {
10356                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10357                                + pkg.staticSharedLibName + " already exists; skipping");
10358                }
10359                // Static shared libs cannot be updated once installed since they
10360                // use synthetic package name which includes the version code, so
10361                // not need to update other packages's shared lib dependencies.
10362            }
10363
10364            if (!hasStaticSharedLibs
10365                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10366                // Only system apps can add new dynamic shared libraries.
10367                if (pkg.libraryNames != null) {
10368                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10369                        String name = pkg.libraryNames.get(i);
10370                        boolean allowed = false;
10371                        if (pkg.isUpdatedSystemApp()) {
10372                            // New library entries can only be added through the
10373                            // system image.  This is important to get rid of a lot
10374                            // of nasty edge cases: for example if we allowed a non-
10375                            // system update of the app to add a library, then uninstalling
10376                            // the update would make the library go away, and assumptions
10377                            // we made such as through app install filtering would now
10378                            // have allowed apps on the device which aren't compatible
10379                            // with it.  Better to just have the restriction here, be
10380                            // conservative, and create many fewer cases that can negatively
10381                            // impact the user experience.
10382                            final PackageSetting sysPs = mSettings
10383                                    .getDisabledSystemPkgLPr(pkg.packageName);
10384                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
10385                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
10386                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
10387                                        allowed = true;
10388                                        break;
10389                                    }
10390                                }
10391                            }
10392                        } else {
10393                            allowed = true;
10394                        }
10395                        if (allowed) {
10396                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10397                                    SharedLibraryInfo.VERSION_UNDEFINED,
10398                                    SharedLibraryInfo.TYPE_DYNAMIC,
10399                                    pkg.packageName, pkg.mVersionCode)) {
10400                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10401                                        + name + " already exists; skipping");
10402                            }
10403                        } else {
10404                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10405                                    + name + " that is not declared on system image; skipping");
10406                        }
10407                    }
10408
10409                    if ((scanFlags & SCAN_BOOTING) == 0) {
10410                        // If we are not booting, we need to update any applications
10411                        // that are clients of our shared library.  If we are booting,
10412                        // this will all be done once the scan is complete.
10413                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10414                    }
10415                }
10416            }
10417        }
10418
10419        if ((scanFlags & SCAN_BOOTING) != 0) {
10420            // No apps can run during boot scan, so they don't need to be frozen
10421        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10422            // Caller asked to not kill app, so it's probably not frozen
10423        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10424            // Caller asked us to ignore frozen check for some reason; they
10425            // probably didn't know the package name
10426        } else {
10427            // We're doing major surgery on this package, so it better be frozen
10428            // right now to keep it from launching
10429            checkPackageFrozen(pkgName);
10430        }
10431
10432        // Also need to kill any apps that are dependent on the library.
10433        if (clientLibPkgs != null) {
10434            for (int i=0; i<clientLibPkgs.size(); i++) {
10435                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10436                killApplication(clientPkg.applicationInfo.packageName,
10437                        clientPkg.applicationInfo.uid, "update lib");
10438            }
10439        }
10440
10441        // writer
10442        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10443
10444        synchronized (mPackages) {
10445            // We don't expect installation to fail beyond this point
10446
10447            // Add the new setting to mSettings
10448            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10449            // Add the new setting to mPackages
10450            mPackages.put(pkg.applicationInfo.packageName, pkg);
10451            // Make sure we don't accidentally delete its data.
10452            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10453            while (iter.hasNext()) {
10454                PackageCleanItem item = iter.next();
10455                if (pkgName.equals(item.packageName)) {
10456                    iter.remove();
10457                }
10458            }
10459
10460            // Add the package's KeySets to the global KeySetManagerService
10461            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10462            ksms.addScannedPackageLPw(pkg);
10463
10464            int N = pkg.providers.size();
10465            StringBuilder r = null;
10466            int i;
10467            for (i=0; i<N; i++) {
10468                PackageParser.Provider p = pkg.providers.get(i);
10469                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10470                        p.info.processName);
10471                mProviders.addProvider(p);
10472                p.syncable = p.info.isSyncable;
10473                if (p.info.authority != null) {
10474                    String names[] = p.info.authority.split(";");
10475                    p.info.authority = null;
10476                    for (int j = 0; j < names.length; j++) {
10477                        if (j == 1 && p.syncable) {
10478                            // We only want the first authority for a provider to possibly be
10479                            // syncable, so if we already added this provider using a different
10480                            // authority clear the syncable flag. We copy the provider before
10481                            // changing it because the mProviders object contains a reference
10482                            // to a provider that we don't want to change.
10483                            // Only do this for the second authority since the resulting provider
10484                            // object can be the same for all future authorities for this provider.
10485                            p = new PackageParser.Provider(p);
10486                            p.syncable = false;
10487                        }
10488                        if (!mProvidersByAuthority.containsKey(names[j])) {
10489                            mProvidersByAuthority.put(names[j], p);
10490                            if (p.info.authority == null) {
10491                                p.info.authority = names[j];
10492                            } else {
10493                                p.info.authority = p.info.authority + ";" + names[j];
10494                            }
10495                            if (DEBUG_PACKAGE_SCANNING) {
10496                                if (chatty)
10497                                    Log.d(TAG, "Registered content provider: " + names[j]
10498                                            + ", className = " + p.info.name + ", isSyncable = "
10499                                            + p.info.isSyncable);
10500                            }
10501                        } else {
10502                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10503                            Slog.w(TAG, "Skipping provider name " + names[j] +
10504                                    " (in package " + pkg.applicationInfo.packageName +
10505                                    "): name already used by "
10506                                    + ((other != null && other.getComponentName() != null)
10507                                            ? other.getComponentName().getPackageName() : "?"));
10508                        }
10509                    }
10510                }
10511                if (chatty) {
10512                    if (r == null) {
10513                        r = new StringBuilder(256);
10514                    } else {
10515                        r.append(' ');
10516                    }
10517                    r.append(p.info.name);
10518                }
10519            }
10520            if (r != null) {
10521                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10522            }
10523
10524            N = pkg.services.size();
10525            r = null;
10526            for (i=0; i<N; i++) {
10527                PackageParser.Service s = pkg.services.get(i);
10528                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10529                        s.info.processName);
10530                mServices.addService(s);
10531                if (chatty) {
10532                    if (r == null) {
10533                        r = new StringBuilder(256);
10534                    } else {
10535                        r.append(' ');
10536                    }
10537                    r.append(s.info.name);
10538                }
10539            }
10540            if (r != null) {
10541                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10542            }
10543
10544            N = pkg.receivers.size();
10545            r = null;
10546            for (i=0; i<N; i++) {
10547                PackageParser.Activity a = pkg.receivers.get(i);
10548                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10549                        a.info.processName);
10550                mReceivers.addActivity(a, "receiver");
10551                if (chatty) {
10552                    if (r == null) {
10553                        r = new StringBuilder(256);
10554                    } else {
10555                        r.append(' ');
10556                    }
10557                    r.append(a.info.name);
10558                }
10559            }
10560            if (r != null) {
10561                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10562            }
10563
10564            N = pkg.activities.size();
10565            r = null;
10566            for (i=0; i<N; i++) {
10567                PackageParser.Activity a = pkg.activities.get(i);
10568                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10569                        a.info.processName);
10570                mActivities.addActivity(a, "activity");
10571                if (chatty) {
10572                    if (r == null) {
10573                        r = new StringBuilder(256);
10574                    } else {
10575                        r.append(' ');
10576                    }
10577                    r.append(a.info.name);
10578                }
10579            }
10580            if (r != null) {
10581                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10582            }
10583
10584            N = pkg.permissionGroups.size();
10585            r = null;
10586            for (i=0; i<N; i++) {
10587                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10588                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10589                final String curPackageName = cur == null ? null : cur.info.packageName;
10590                // Dont allow ephemeral apps to define new permission groups.
10591                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10592                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10593                            + pg.info.packageName
10594                            + " ignored: instant apps cannot define new permission groups.");
10595                    continue;
10596                }
10597                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10598                if (cur == null || isPackageUpdate) {
10599                    mPermissionGroups.put(pg.info.name, pg);
10600                    if (chatty) {
10601                        if (r == null) {
10602                            r = new StringBuilder(256);
10603                        } else {
10604                            r.append(' ');
10605                        }
10606                        if (isPackageUpdate) {
10607                            r.append("UPD:");
10608                        }
10609                        r.append(pg.info.name);
10610                    }
10611                } else {
10612                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10613                            + pg.info.packageName + " ignored: original from "
10614                            + cur.info.packageName);
10615                    if (chatty) {
10616                        if (r == null) {
10617                            r = new StringBuilder(256);
10618                        } else {
10619                            r.append(' ');
10620                        }
10621                        r.append("DUP:");
10622                        r.append(pg.info.name);
10623                    }
10624                }
10625            }
10626            if (r != null) {
10627                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10628            }
10629
10630            N = pkg.permissions.size();
10631            r = null;
10632            for (i=0; i<N; i++) {
10633                PackageParser.Permission p = pkg.permissions.get(i);
10634
10635                // Dont allow ephemeral apps to define new permissions.
10636                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10637                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10638                            + p.info.packageName
10639                            + " ignored: instant apps cannot define new permissions.");
10640                    continue;
10641                }
10642
10643                // Assume by default that we did not install this permission into the system.
10644                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10645
10646                // Now that permission groups have a special meaning, we ignore permission
10647                // groups for legacy apps to prevent unexpected behavior. In particular,
10648                // permissions for one app being granted to someone just becase they happen
10649                // to be in a group defined by another app (before this had no implications).
10650                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10651                    p.group = mPermissionGroups.get(p.info.group);
10652                    // Warn for a permission in an unknown group.
10653                    if (p.info.group != null && p.group == null) {
10654                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10655                                + p.info.packageName + " in an unknown group " + p.info.group);
10656                    }
10657                }
10658
10659                ArrayMap<String, BasePermission> permissionMap =
10660                        p.tree ? mSettings.mPermissionTrees
10661                                : mSettings.mPermissions;
10662                BasePermission bp = permissionMap.get(p.info.name);
10663
10664                // Allow system apps to redefine non-system permissions
10665                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10666                    final boolean currentOwnerIsSystem = (bp.perm != null
10667                            && isSystemApp(bp.perm.owner));
10668                    if (isSystemApp(p.owner)) {
10669                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10670                            // It's a built-in permission and no owner, take ownership now
10671                            bp.packageSetting = pkgSetting;
10672                            bp.perm = p;
10673                            bp.uid = pkg.applicationInfo.uid;
10674                            bp.sourcePackage = p.info.packageName;
10675                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10676                        } else if (!currentOwnerIsSystem) {
10677                            String msg = "New decl " + p.owner + " of permission  "
10678                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10679                            reportSettingsProblem(Log.WARN, msg);
10680                            bp = null;
10681                        }
10682                    }
10683                }
10684
10685                if (bp == null) {
10686                    bp = new BasePermission(p.info.name, p.info.packageName,
10687                            BasePermission.TYPE_NORMAL);
10688                    permissionMap.put(p.info.name, bp);
10689                }
10690
10691                if (bp.perm == null) {
10692                    if (bp.sourcePackage == null
10693                            || bp.sourcePackage.equals(p.info.packageName)) {
10694                        BasePermission tree = findPermissionTreeLP(p.info.name);
10695                        if (tree == null
10696                                || tree.sourcePackage.equals(p.info.packageName)) {
10697                            bp.packageSetting = pkgSetting;
10698                            bp.perm = p;
10699                            bp.uid = pkg.applicationInfo.uid;
10700                            bp.sourcePackage = p.info.packageName;
10701                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10702                            if (chatty) {
10703                                if (r == null) {
10704                                    r = new StringBuilder(256);
10705                                } else {
10706                                    r.append(' ');
10707                                }
10708                                r.append(p.info.name);
10709                            }
10710                        } else {
10711                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10712                                    + p.info.packageName + " ignored: base tree "
10713                                    + tree.name + " is from package "
10714                                    + tree.sourcePackage);
10715                        }
10716                    } else {
10717                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10718                                + p.info.packageName + " ignored: original from "
10719                                + bp.sourcePackage);
10720                    }
10721                } else if (chatty) {
10722                    if (r == null) {
10723                        r = new StringBuilder(256);
10724                    } else {
10725                        r.append(' ');
10726                    }
10727                    r.append("DUP:");
10728                    r.append(p.info.name);
10729                }
10730                if (bp.perm == p) {
10731                    bp.protectionLevel = p.info.protectionLevel;
10732                }
10733            }
10734
10735            if (r != null) {
10736                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10737            }
10738
10739            N = pkg.instrumentation.size();
10740            r = null;
10741            for (i=0; i<N; i++) {
10742                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10743                a.info.packageName = pkg.applicationInfo.packageName;
10744                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10745                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10746                a.info.splitNames = pkg.splitNames;
10747                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10748                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10749                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10750                a.info.dataDir = pkg.applicationInfo.dataDir;
10751                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10752                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10753                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10754                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10755                mInstrumentation.put(a.getComponentName(), a);
10756                if (chatty) {
10757                    if (r == null) {
10758                        r = new StringBuilder(256);
10759                    } else {
10760                        r.append(' ');
10761                    }
10762                    r.append(a.info.name);
10763                }
10764            }
10765            if (r != null) {
10766                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10767            }
10768
10769            if (pkg.protectedBroadcasts != null) {
10770                N = pkg.protectedBroadcasts.size();
10771                for (i=0; i<N; i++) {
10772                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10773                }
10774            }
10775        }
10776
10777        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10778    }
10779
10780    /**
10781     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10782     * is derived purely on the basis of the contents of {@code scanFile} and
10783     * {@code cpuAbiOverride}.
10784     *
10785     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10786     */
10787    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10788                                 String cpuAbiOverride, boolean extractLibs,
10789                                 File appLib32InstallDir)
10790            throws PackageManagerException {
10791        // Give ourselves some initial paths; we'll come back for another
10792        // pass once we've determined ABI below.
10793        setNativeLibraryPaths(pkg, appLib32InstallDir);
10794
10795        // We would never need to extract libs for forward-locked and external packages,
10796        // since the container service will do it for us. We shouldn't attempt to
10797        // extract libs from system app when it was not updated.
10798        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10799                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10800            extractLibs = false;
10801        }
10802
10803        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10804        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10805
10806        NativeLibraryHelper.Handle handle = null;
10807        try {
10808            handle = NativeLibraryHelper.Handle.create(pkg);
10809            // TODO(multiArch): This can be null for apps that didn't go through the
10810            // usual installation process. We can calculate it again, like we
10811            // do during install time.
10812            //
10813            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10814            // unnecessary.
10815            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10816
10817            // Null out the abis so that they can be recalculated.
10818            pkg.applicationInfo.primaryCpuAbi = null;
10819            pkg.applicationInfo.secondaryCpuAbi = null;
10820            if (isMultiArch(pkg.applicationInfo)) {
10821                // Warn if we've set an abiOverride for multi-lib packages..
10822                // By definition, we need to copy both 32 and 64 bit libraries for
10823                // such packages.
10824                if (pkg.cpuAbiOverride != null
10825                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10826                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10827                }
10828
10829                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10830                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10831                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10832                    if (extractLibs) {
10833                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10834                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10835                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10836                                useIsaSpecificSubdirs);
10837                    } else {
10838                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10839                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10840                    }
10841                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10842                }
10843
10844                maybeThrowExceptionForMultiArchCopy(
10845                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10846
10847                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10848                    if (extractLibs) {
10849                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10850                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10851                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10852                                useIsaSpecificSubdirs);
10853                    } else {
10854                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10855                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10856                    }
10857                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10858                }
10859
10860                maybeThrowExceptionForMultiArchCopy(
10861                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10862
10863                if (abi64 >= 0) {
10864                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10865                }
10866
10867                if (abi32 >= 0) {
10868                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10869                    if (abi64 >= 0) {
10870                        if (pkg.use32bitAbi) {
10871                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10872                            pkg.applicationInfo.primaryCpuAbi = abi;
10873                        } else {
10874                            pkg.applicationInfo.secondaryCpuAbi = abi;
10875                        }
10876                    } else {
10877                        pkg.applicationInfo.primaryCpuAbi = abi;
10878                    }
10879                }
10880
10881            } else {
10882                String[] abiList = (cpuAbiOverride != null) ?
10883                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10884
10885                // Enable gross and lame hacks for apps that are built with old
10886                // SDK tools. We must scan their APKs for renderscript bitcode and
10887                // not launch them if it's present. Don't bother checking on devices
10888                // that don't have 64 bit support.
10889                boolean needsRenderScriptOverride = false;
10890                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10891                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10892                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10893                    needsRenderScriptOverride = true;
10894                }
10895
10896                final int copyRet;
10897                if (extractLibs) {
10898                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10899                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10900                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10901                } else {
10902                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10903                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10904                }
10905                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10906
10907                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10908                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10909                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10910                }
10911
10912                if (copyRet >= 0) {
10913                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10914                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10915                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10916                } else if (needsRenderScriptOverride) {
10917                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10918                }
10919            }
10920        } catch (IOException ioe) {
10921            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10922        } finally {
10923            IoUtils.closeQuietly(handle);
10924        }
10925
10926        // Now that we've calculated the ABIs and determined if it's an internal app,
10927        // we will go ahead and populate the nativeLibraryPath.
10928        setNativeLibraryPaths(pkg, appLib32InstallDir);
10929    }
10930
10931    /**
10932     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10933     * i.e, so that all packages can be run inside a single process if required.
10934     *
10935     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10936     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10937     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10938     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10939     * updating a package that belongs to a shared user.
10940     *
10941     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10942     * adds unnecessary complexity.
10943     */
10944    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10945            PackageParser.Package scannedPackage) {
10946        String requiredInstructionSet = null;
10947        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10948            requiredInstructionSet = VMRuntime.getInstructionSet(
10949                     scannedPackage.applicationInfo.primaryCpuAbi);
10950        }
10951
10952        PackageSetting requirer = null;
10953        for (PackageSetting ps : packagesForUser) {
10954            // If packagesForUser contains scannedPackage, we skip it. This will happen
10955            // when scannedPackage is an update of an existing package. Without this check,
10956            // we will never be able to change the ABI of any package belonging to a shared
10957            // user, even if it's compatible with other packages.
10958            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10959                if (ps.primaryCpuAbiString == null) {
10960                    continue;
10961                }
10962
10963                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10964                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10965                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10966                    // this but there's not much we can do.
10967                    String errorMessage = "Instruction set mismatch, "
10968                            + ((requirer == null) ? "[caller]" : requirer)
10969                            + " requires " + requiredInstructionSet + " whereas " + ps
10970                            + " requires " + instructionSet;
10971                    Slog.w(TAG, errorMessage);
10972                }
10973
10974                if (requiredInstructionSet == null) {
10975                    requiredInstructionSet = instructionSet;
10976                    requirer = ps;
10977                }
10978            }
10979        }
10980
10981        if (requiredInstructionSet != null) {
10982            String adjustedAbi;
10983            if (requirer != null) {
10984                // requirer != null implies that either scannedPackage was null or that scannedPackage
10985                // did not require an ABI, in which case we have to adjust scannedPackage to match
10986                // the ABI of the set (which is the same as requirer's ABI)
10987                adjustedAbi = requirer.primaryCpuAbiString;
10988                if (scannedPackage != null) {
10989                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10990                }
10991            } else {
10992                // requirer == null implies that we're updating all ABIs in the set to
10993                // match scannedPackage.
10994                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10995            }
10996
10997            for (PackageSetting ps : packagesForUser) {
10998                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10999                    if (ps.primaryCpuAbiString != null) {
11000                        continue;
11001                    }
11002
11003                    ps.primaryCpuAbiString = adjustedAbi;
11004                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11005                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11006                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11007                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11008                                + " (requirer="
11009                                + (requirer != null ? requirer.pkg : "null")
11010                                + ", scannedPackage="
11011                                + (scannedPackage != null ? scannedPackage : "null")
11012                                + ")");
11013                        try {
11014                            mInstaller.rmdex(ps.codePathString,
11015                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11016                        } catch (InstallerException ignored) {
11017                        }
11018                    }
11019                }
11020            }
11021        }
11022    }
11023
11024    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11025        synchronized (mPackages) {
11026            mResolverReplaced = true;
11027            // Set up information for custom user intent resolution activity.
11028            mResolveActivity.applicationInfo = pkg.applicationInfo;
11029            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11030            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11031            mResolveActivity.processName = pkg.applicationInfo.packageName;
11032            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11033            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11034                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11035            mResolveActivity.theme = 0;
11036            mResolveActivity.exported = true;
11037            mResolveActivity.enabled = true;
11038            mResolveInfo.activityInfo = mResolveActivity;
11039            mResolveInfo.priority = 0;
11040            mResolveInfo.preferredOrder = 0;
11041            mResolveInfo.match = 0;
11042            mResolveComponentName = mCustomResolverComponentName;
11043            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11044                    mResolveComponentName);
11045        }
11046    }
11047
11048    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11049        if (installerActivity == null) {
11050            if (DEBUG_EPHEMERAL) {
11051                Slog.d(TAG, "Clear ephemeral installer activity");
11052            }
11053            mInstantAppInstallerActivity = null;
11054            return;
11055        }
11056
11057        if (DEBUG_EPHEMERAL) {
11058            Slog.d(TAG, "Set ephemeral installer activity: "
11059                    + installerActivity.getComponentName());
11060        }
11061        // Set up information for ephemeral installer activity
11062        mInstantAppInstallerActivity = installerActivity;
11063        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11064                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11065        mInstantAppInstallerActivity.exported = true;
11066        mInstantAppInstallerActivity.enabled = true;
11067        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11068        mInstantAppInstallerInfo.priority = 0;
11069        mInstantAppInstallerInfo.preferredOrder = 1;
11070        mInstantAppInstallerInfo.isDefault = true;
11071        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11072                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11073    }
11074
11075    private static String calculateBundledApkRoot(final String codePathString) {
11076        final File codePath = new File(codePathString);
11077        final File codeRoot;
11078        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11079            codeRoot = Environment.getRootDirectory();
11080        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11081            codeRoot = Environment.getOemDirectory();
11082        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11083            codeRoot = Environment.getVendorDirectory();
11084        } else {
11085            // Unrecognized code path; take its top real segment as the apk root:
11086            // e.g. /something/app/blah.apk => /something
11087            try {
11088                File f = codePath.getCanonicalFile();
11089                File parent = f.getParentFile();    // non-null because codePath is a file
11090                File tmp;
11091                while ((tmp = parent.getParentFile()) != null) {
11092                    f = parent;
11093                    parent = tmp;
11094                }
11095                codeRoot = f;
11096                Slog.w(TAG, "Unrecognized code path "
11097                        + codePath + " - using " + codeRoot);
11098            } catch (IOException e) {
11099                // Can't canonicalize the code path -- shenanigans?
11100                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11101                return Environment.getRootDirectory().getPath();
11102            }
11103        }
11104        return codeRoot.getPath();
11105    }
11106
11107    /**
11108     * Derive and set the location of native libraries for the given package,
11109     * which varies depending on where and how the package was installed.
11110     */
11111    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11112        final ApplicationInfo info = pkg.applicationInfo;
11113        final String codePath = pkg.codePath;
11114        final File codeFile = new File(codePath);
11115        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11116        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11117
11118        info.nativeLibraryRootDir = null;
11119        info.nativeLibraryRootRequiresIsa = false;
11120        info.nativeLibraryDir = null;
11121        info.secondaryNativeLibraryDir = null;
11122
11123        if (isApkFile(codeFile)) {
11124            // Monolithic install
11125            if (bundledApp) {
11126                // If "/system/lib64/apkname" exists, assume that is the per-package
11127                // native library directory to use; otherwise use "/system/lib/apkname".
11128                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11129                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11130                        getPrimaryInstructionSet(info));
11131
11132                // This is a bundled system app so choose the path based on the ABI.
11133                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11134                // is just the default path.
11135                final String apkName = deriveCodePathName(codePath);
11136                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11137                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11138                        apkName).getAbsolutePath();
11139
11140                if (info.secondaryCpuAbi != null) {
11141                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11142                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11143                            secondaryLibDir, apkName).getAbsolutePath();
11144                }
11145            } else if (asecApp) {
11146                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11147                        .getAbsolutePath();
11148            } else {
11149                final String apkName = deriveCodePathName(codePath);
11150                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11151                        .getAbsolutePath();
11152            }
11153
11154            info.nativeLibraryRootRequiresIsa = false;
11155            info.nativeLibraryDir = info.nativeLibraryRootDir;
11156        } else {
11157            // Cluster install
11158            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11159            info.nativeLibraryRootRequiresIsa = true;
11160
11161            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11162                    getPrimaryInstructionSet(info)).getAbsolutePath();
11163
11164            if (info.secondaryCpuAbi != null) {
11165                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11166                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11167            }
11168        }
11169    }
11170
11171    /**
11172     * Calculate the abis and roots for a bundled app. These can uniquely
11173     * be determined from the contents of the system partition, i.e whether
11174     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11175     * of this information, and instead assume that the system was built
11176     * sensibly.
11177     */
11178    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11179                                           PackageSetting pkgSetting) {
11180        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11181
11182        // If "/system/lib64/apkname" exists, assume that is the per-package
11183        // native library directory to use; otherwise use "/system/lib/apkname".
11184        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11185        setBundledAppAbi(pkg, apkRoot, apkName);
11186        // pkgSetting might be null during rescan following uninstall of updates
11187        // to a bundled app, so accommodate that possibility.  The settings in
11188        // that case will be established later from the parsed package.
11189        //
11190        // If the settings aren't null, sync them up with what we've just derived.
11191        // note that apkRoot isn't stored in the package settings.
11192        if (pkgSetting != null) {
11193            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11194            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11195        }
11196    }
11197
11198    /**
11199     * Deduces the ABI of a bundled app and sets the relevant fields on the
11200     * parsed pkg object.
11201     *
11202     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11203     *        under which system libraries are installed.
11204     * @param apkName the name of the installed package.
11205     */
11206    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11207        final File codeFile = new File(pkg.codePath);
11208
11209        final boolean has64BitLibs;
11210        final boolean has32BitLibs;
11211        if (isApkFile(codeFile)) {
11212            // Monolithic install
11213            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11214            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11215        } else {
11216            // Cluster install
11217            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11218            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11219                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11220                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11221                has64BitLibs = (new File(rootDir, isa)).exists();
11222            } else {
11223                has64BitLibs = false;
11224            }
11225            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11226                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11227                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11228                has32BitLibs = (new File(rootDir, isa)).exists();
11229            } else {
11230                has32BitLibs = false;
11231            }
11232        }
11233
11234        if (has64BitLibs && !has32BitLibs) {
11235            // The package has 64 bit libs, but not 32 bit libs. Its primary
11236            // ABI should be 64 bit. We can safely assume here that the bundled
11237            // native libraries correspond to the most preferred ABI in the list.
11238
11239            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11240            pkg.applicationInfo.secondaryCpuAbi = null;
11241        } else if (has32BitLibs && !has64BitLibs) {
11242            // The package has 32 bit libs but not 64 bit libs. Its primary
11243            // ABI should be 32 bit.
11244
11245            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11246            pkg.applicationInfo.secondaryCpuAbi = null;
11247        } else if (has32BitLibs && has64BitLibs) {
11248            // The application has both 64 and 32 bit bundled libraries. We check
11249            // here that the app declares multiArch support, and warn if it doesn't.
11250            //
11251            // We will be lenient here and record both ABIs. The primary will be the
11252            // ABI that's higher on the list, i.e, a device that's configured to prefer
11253            // 64 bit apps will see a 64 bit primary ABI,
11254
11255            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11256                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11257            }
11258
11259            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11260                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11261                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11262            } else {
11263                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11264                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11265            }
11266        } else {
11267            pkg.applicationInfo.primaryCpuAbi = null;
11268            pkg.applicationInfo.secondaryCpuAbi = null;
11269        }
11270    }
11271
11272    private void killApplication(String pkgName, int appId, String reason) {
11273        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11274    }
11275
11276    private void killApplication(String pkgName, int appId, int userId, String reason) {
11277        // Request the ActivityManager to kill the process(only for existing packages)
11278        // so that we do not end up in a confused state while the user is still using the older
11279        // version of the application while the new one gets installed.
11280        final long token = Binder.clearCallingIdentity();
11281        try {
11282            IActivityManager am = ActivityManager.getService();
11283            if (am != null) {
11284                try {
11285                    am.killApplication(pkgName, appId, userId, reason);
11286                } catch (RemoteException e) {
11287                }
11288            }
11289        } finally {
11290            Binder.restoreCallingIdentity(token);
11291        }
11292    }
11293
11294    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11295        // Remove the parent package setting
11296        PackageSetting ps = (PackageSetting) pkg.mExtras;
11297        if (ps != null) {
11298            removePackageLI(ps, chatty);
11299        }
11300        // Remove the child package setting
11301        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11302        for (int i = 0; i < childCount; i++) {
11303            PackageParser.Package childPkg = pkg.childPackages.get(i);
11304            ps = (PackageSetting) childPkg.mExtras;
11305            if (ps != null) {
11306                removePackageLI(ps, chatty);
11307            }
11308        }
11309    }
11310
11311    void removePackageLI(PackageSetting ps, boolean chatty) {
11312        if (DEBUG_INSTALL) {
11313            if (chatty)
11314                Log.d(TAG, "Removing package " + ps.name);
11315        }
11316
11317        // writer
11318        synchronized (mPackages) {
11319            mPackages.remove(ps.name);
11320            final PackageParser.Package pkg = ps.pkg;
11321            if (pkg != null) {
11322                cleanPackageDataStructuresLILPw(pkg, chatty);
11323            }
11324        }
11325    }
11326
11327    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11328        if (DEBUG_INSTALL) {
11329            if (chatty)
11330                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11331        }
11332
11333        // writer
11334        synchronized (mPackages) {
11335            // Remove the parent package
11336            mPackages.remove(pkg.applicationInfo.packageName);
11337            cleanPackageDataStructuresLILPw(pkg, chatty);
11338
11339            // Remove the child packages
11340            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11341            for (int i = 0; i < childCount; i++) {
11342                PackageParser.Package childPkg = pkg.childPackages.get(i);
11343                mPackages.remove(childPkg.applicationInfo.packageName);
11344                cleanPackageDataStructuresLILPw(childPkg, chatty);
11345            }
11346        }
11347    }
11348
11349    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11350        int N = pkg.providers.size();
11351        StringBuilder r = null;
11352        int i;
11353        for (i=0; i<N; i++) {
11354            PackageParser.Provider p = pkg.providers.get(i);
11355            mProviders.removeProvider(p);
11356            if (p.info.authority == null) {
11357
11358                /* There was another ContentProvider with this authority when
11359                 * this app was installed so this authority is null,
11360                 * Ignore it as we don't have to unregister the provider.
11361                 */
11362                continue;
11363            }
11364            String names[] = p.info.authority.split(";");
11365            for (int j = 0; j < names.length; j++) {
11366                if (mProvidersByAuthority.get(names[j]) == p) {
11367                    mProvidersByAuthority.remove(names[j]);
11368                    if (DEBUG_REMOVE) {
11369                        if (chatty)
11370                            Log.d(TAG, "Unregistered content provider: " + names[j]
11371                                    + ", className = " + p.info.name + ", isSyncable = "
11372                                    + p.info.isSyncable);
11373                    }
11374                }
11375            }
11376            if (DEBUG_REMOVE && chatty) {
11377                if (r == null) {
11378                    r = new StringBuilder(256);
11379                } else {
11380                    r.append(' ');
11381                }
11382                r.append(p.info.name);
11383            }
11384        }
11385        if (r != null) {
11386            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11387        }
11388
11389        N = pkg.services.size();
11390        r = null;
11391        for (i=0; i<N; i++) {
11392            PackageParser.Service s = pkg.services.get(i);
11393            mServices.removeService(s);
11394            if (chatty) {
11395                if (r == null) {
11396                    r = new StringBuilder(256);
11397                } else {
11398                    r.append(' ');
11399                }
11400                r.append(s.info.name);
11401            }
11402        }
11403        if (r != null) {
11404            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11405        }
11406
11407        N = pkg.receivers.size();
11408        r = null;
11409        for (i=0; i<N; i++) {
11410            PackageParser.Activity a = pkg.receivers.get(i);
11411            mReceivers.removeActivity(a, "receiver");
11412            if (DEBUG_REMOVE && chatty) {
11413                if (r == null) {
11414                    r = new StringBuilder(256);
11415                } else {
11416                    r.append(' ');
11417                }
11418                r.append(a.info.name);
11419            }
11420        }
11421        if (r != null) {
11422            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11423        }
11424
11425        N = pkg.activities.size();
11426        r = null;
11427        for (i=0; i<N; i++) {
11428            PackageParser.Activity a = pkg.activities.get(i);
11429            mActivities.removeActivity(a, "activity");
11430            if (DEBUG_REMOVE && chatty) {
11431                if (r == null) {
11432                    r = new StringBuilder(256);
11433                } else {
11434                    r.append(' ');
11435                }
11436                r.append(a.info.name);
11437            }
11438        }
11439        if (r != null) {
11440            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11441        }
11442
11443        N = pkg.permissions.size();
11444        r = null;
11445        for (i=0; i<N; i++) {
11446            PackageParser.Permission p = pkg.permissions.get(i);
11447            BasePermission bp = mSettings.mPermissions.get(p.info.name);
11448            if (bp == null) {
11449                bp = mSettings.mPermissionTrees.get(p.info.name);
11450            }
11451            if (bp != null && bp.perm == p) {
11452                bp.perm = null;
11453                if (DEBUG_REMOVE && chatty) {
11454                    if (r == null) {
11455                        r = new StringBuilder(256);
11456                    } else {
11457                        r.append(' ');
11458                    }
11459                    r.append(p.info.name);
11460                }
11461            }
11462            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11463                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11464                if (appOpPkgs != null) {
11465                    appOpPkgs.remove(pkg.packageName);
11466                }
11467            }
11468        }
11469        if (r != null) {
11470            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11471        }
11472
11473        N = pkg.requestedPermissions.size();
11474        r = null;
11475        for (i=0; i<N; i++) {
11476            String perm = pkg.requestedPermissions.get(i);
11477            BasePermission bp = mSettings.mPermissions.get(perm);
11478            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11479                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11480                if (appOpPkgs != null) {
11481                    appOpPkgs.remove(pkg.packageName);
11482                    if (appOpPkgs.isEmpty()) {
11483                        mAppOpPermissionPackages.remove(perm);
11484                    }
11485                }
11486            }
11487        }
11488        if (r != null) {
11489            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11490        }
11491
11492        N = pkg.instrumentation.size();
11493        r = null;
11494        for (i=0; i<N; i++) {
11495            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11496            mInstrumentation.remove(a.getComponentName());
11497            if (DEBUG_REMOVE && chatty) {
11498                if (r == null) {
11499                    r = new StringBuilder(256);
11500                } else {
11501                    r.append(' ');
11502                }
11503                r.append(a.info.name);
11504            }
11505        }
11506        if (r != null) {
11507            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11508        }
11509
11510        r = null;
11511        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11512            // Only system apps can hold shared libraries.
11513            if (pkg.libraryNames != null) {
11514                for (i = 0; i < pkg.libraryNames.size(); i++) {
11515                    String name = pkg.libraryNames.get(i);
11516                    if (removeSharedLibraryLPw(name, 0)) {
11517                        if (DEBUG_REMOVE && chatty) {
11518                            if (r == null) {
11519                                r = new StringBuilder(256);
11520                            } else {
11521                                r.append(' ');
11522                            }
11523                            r.append(name);
11524                        }
11525                    }
11526                }
11527            }
11528        }
11529
11530        r = null;
11531
11532        // Any package can hold static shared libraries.
11533        if (pkg.staticSharedLibName != null) {
11534            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11535                if (DEBUG_REMOVE && chatty) {
11536                    if (r == null) {
11537                        r = new StringBuilder(256);
11538                    } else {
11539                        r.append(' ');
11540                    }
11541                    r.append(pkg.staticSharedLibName);
11542                }
11543            }
11544        }
11545
11546        if (r != null) {
11547            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11548        }
11549    }
11550
11551    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11552        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11553            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11554                return true;
11555            }
11556        }
11557        return false;
11558    }
11559
11560    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11561    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11562    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11563
11564    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11565        // Update the parent permissions
11566        updatePermissionsLPw(pkg.packageName, pkg, flags);
11567        // Update the child permissions
11568        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11569        for (int i = 0; i < childCount; i++) {
11570            PackageParser.Package childPkg = pkg.childPackages.get(i);
11571            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11572        }
11573    }
11574
11575    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11576            int flags) {
11577        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11578        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11579    }
11580
11581    private void updatePermissionsLPw(String changingPkg,
11582            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11583        // Make sure there are no dangling permission trees.
11584        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11585        while (it.hasNext()) {
11586            final BasePermission bp = it.next();
11587            if (bp.packageSetting == null) {
11588                // We may not yet have parsed the package, so just see if
11589                // we still know about its settings.
11590                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11591            }
11592            if (bp.packageSetting == null) {
11593                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11594                        + " from package " + bp.sourcePackage);
11595                it.remove();
11596            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11597                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11598                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11599                            + " from package " + bp.sourcePackage);
11600                    flags |= UPDATE_PERMISSIONS_ALL;
11601                    it.remove();
11602                }
11603            }
11604        }
11605
11606        // Make sure all dynamic permissions have been assigned to a package,
11607        // and make sure there are no dangling permissions.
11608        it = mSettings.mPermissions.values().iterator();
11609        while (it.hasNext()) {
11610            final BasePermission bp = it.next();
11611            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11612                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11613                        + bp.name + " pkg=" + bp.sourcePackage
11614                        + " info=" + bp.pendingInfo);
11615                if (bp.packageSetting == null && bp.pendingInfo != null) {
11616                    final BasePermission tree = findPermissionTreeLP(bp.name);
11617                    if (tree != null && tree.perm != null) {
11618                        bp.packageSetting = tree.packageSetting;
11619                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11620                                new PermissionInfo(bp.pendingInfo));
11621                        bp.perm.info.packageName = tree.perm.info.packageName;
11622                        bp.perm.info.name = bp.name;
11623                        bp.uid = tree.uid;
11624                    }
11625                }
11626            }
11627            if (bp.packageSetting == null) {
11628                // We may not yet have parsed the package, so just see if
11629                // we still know about its settings.
11630                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11631            }
11632            if (bp.packageSetting == null) {
11633                Slog.w(TAG, "Removing dangling permission: " + bp.name
11634                        + " from package " + bp.sourcePackage);
11635                it.remove();
11636            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11637                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11638                    Slog.i(TAG, "Removing old permission: " + bp.name
11639                            + " from package " + bp.sourcePackage);
11640                    flags |= UPDATE_PERMISSIONS_ALL;
11641                    it.remove();
11642                }
11643            }
11644        }
11645
11646        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11647        // Now update the permissions for all packages, in particular
11648        // replace the granted permissions of the system packages.
11649        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11650            for (PackageParser.Package pkg : mPackages.values()) {
11651                if (pkg != pkgInfo) {
11652                    // Only replace for packages on requested volume
11653                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11654                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11655                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11656                    grantPermissionsLPw(pkg, replace, changingPkg);
11657                }
11658            }
11659        }
11660
11661        if (pkgInfo != null) {
11662            // Only replace for packages on requested volume
11663            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11664            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11665                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11666            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11667        }
11668        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11669    }
11670
11671    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11672            String packageOfInterest) {
11673        // IMPORTANT: There are two types of permissions: install and runtime.
11674        // Install time permissions are granted when the app is installed to
11675        // all device users and users added in the future. Runtime permissions
11676        // are granted at runtime explicitly to specific users. Normal and signature
11677        // protected permissions are install time permissions. Dangerous permissions
11678        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11679        // otherwise they are runtime permissions. This function does not manage
11680        // runtime permissions except for the case an app targeting Lollipop MR1
11681        // being upgraded to target a newer SDK, in which case dangerous permissions
11682        // are transformed from install time to runtime ones.
11683
11684        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11685        if (ps == null) {
11686            return;
11687        }
11688
11689        PermissionsState permissionsState = ps.getPermissionsState();
11690        PermissionsState origPermissions = permissionsState;
11691
11692        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11693
11694        boolean runtimePermissionsRevoked = false;
11695        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11696
11697        boolean changedInstallPermission = false;
11698
11699        if (replace) {
11700            ps.installPermissionsFixed = false;
11701            if (!ps.isSharedUser()) {
11702                origPermissions = new PermissionsState(permissionsState);
11703                permissionsState.reset();
11704            } else {
11705                // We need to know only about runtime permission changes since the
11706                // calling code always writes the install permissions state but
11707                // the runtime ones are written only if changed. The only cases of
11708                // changed runtime permissions here are promotion of an install to
11709                // runtime and revocation of a runtime from a shared user.
11710                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11711                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11712                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11713                    runtimePermissionsRevoked = true;
11714                }
11715            }
11716        }
11717
11718        permissionsState.setGlobalGids(mGlobalGids);
11719
11720        final int N = pkg.requestedPermissions.size();
11721        for (int i=0; i<N; i++) {
11722            final String name = pkg.requestedPermissions.get(i);
11723            final BasePermission bp = mSettings.mPermissions.get(name);
11724            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11725                    >= Build.VERSION_CODES.M;
11726
11727            if (DEBUG_INSTALL) {
11728                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11729            }
11730
11731            if (bp == null || bp.packageSetting == null) {
11732                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11733                    Slog.w(TAG, "Unknown permission " + name
11734                            + " in package " + pkg.packageName);
11735                }
11736                continue;
11737            }
11738
11739
11740            // Limit ephemeral apps to ephemeral allowed permissions.
11741            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11742                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11743                        + pkg.packageName);
11744                continue;
11745            }
11746
11747            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
11748                Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
11749                        + pkg.packageName);
11750                continue;
11751            }
11752
11753            final String perm = bp.name;
11754            boolean allowedSig = false;
11755            int grant = GRANT_DENIED;
11756
11757            // Keep track of app op permissions.
11758            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11759                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11760                if (pkgs == null) {
11761                    pkgs = new ArraySet<>();
11762                    mAppOpPermissionPackages.put(bp.name, pkgs);
11763                }
11764                pkgs.add(pkg.packageName);
11765            }
11766
11767            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11768            switch (level) {
11769                case PermissionInfo.PROTECTION_NORMAL: {
11770                    // For all apps normal permissions are install time ones.
11771                    grant = GRANT_INSTALL;
11772                } break;
11773
11774                case PermissionInfo.PROTECTION_DANGEROUS: {
11775                    // If a permission review is required for legacy apps we represent
11776                    // their permissions as always granted runtime ones since we need
11777                    // to keep the review required permission flag per user while an
11778                    // install permission's state is shared across all users.
11779                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11780                        // For legacy apps dangerous permissions are install time ones.
11781                        grant = GRANT_INSTALL;
11782                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11783                        // For legacy apps that became modern, install becomes runtime.
11784                        grant = GRANT_UPGRADE;
11785                    } else if (mPromoteSystemApps
11786                            && isSystemApp(ps)
11787                            && mExistingSystemPackages.contains(ps.name)) {
11788                        // For legacy system apps, install becomes runtime.
11789                        // We cannot check hasInstallPermission() for system apps since those
11790                        // permissions were granted implicitly and not persisted pre-M.
11791                        grant = GRANT_UPGRADE;
11792                    } else {
11793                        // For modern apps keep runtime permissions unchanged.
11794                        grant = GRANT_RUNTIME;
11795                    }
11796                } break;
11797
11798                case PermissionInfo.PROTECTION_SIGNATURE: {
11799                    // For all apps signature permissions are install time ones.
11800                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11801                    if (allowedSig) {
11802                        grant = GRANT_INSTALL;
11803                    }
11804                } break;
11805            }
11806
11807            if (DEBUG_INSTALL) {
11808                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11809            }
11810
11811            if (grant != GRANT_DENIED) {
11812                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11813                    // If this is an existing, non-system package, then
11814                    // we can't add any new permissions to it.
11815                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11816                        // Except...  if this is a permission that was added
11817                        // to the platform (note: need to only do this when
11818                        // updating the platform).
11819                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11820                            grant = GRANT_DENIED;
11821                        }
11822                    }
11823                }
11824
11825                switch (grant) {
11826                    case GRANT_INSTALL: {
11827                        // Revoke this as runtime permission to handle the case of
11828                        // a runtime permission being downgraded to an install one.
11829                        // Also in permission review mode we keep dangerous permissions
11830                        // for legacy apps
11831                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11832                            if (origPermissions.getRuntimePermissionState(
11833                                    bp.name, userId) != null) {
11834                                // Revoke the runtime permission and clear the flags.
11835                                origPermissions.revokeRuntimePermission(bp, userId);
11836                                origPermissions.updatePermissionFlags(bp, userId,
11837                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11838                                // If we revoked a permission permission, we have to write.
11839                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11840                                        changedRuntimePermissionUserIds, userId);
11841                            }
11842                        }
11843                        // Grant an install permission.
11844                        if (permissionsState.grantInstallPermission(bp) !=
11845                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11846                            changedInstallPermission = true;
11847                        }
11848                    } break;
11849
11850                    case GRANT_RUNTIME: {
11851                        // Grant previously granted runtime permissions.
11852                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11853                            PermissionState permissionState = origPermissions
11854                                    .getRuntimePermissionState(bp.name, userId);
11855                            int flags = permissionState != null
11856                                    ? permissionState.getFlags() : 0;
11857                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11858                                // Don't propagate the permission in a permission review mode if
11859                                // the former was revoked, i.e. marked to not propagate on upgrade.
11860                                // Note that in a permission review mode install permissions are
11861                                // represented as constantly granted runtime ones since we need to
11862                                // keep a per user state associated with the permission. Also the
11863                                // revoke on upgrade flag is no longer applicable and is reset.
11864                                final boolean revokeOnUpgrade = (flags & PackageManager
11865                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11866                                if (revokeOnUpgrade) {
11867                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11868                                    // Since we changed the flags, we have to write.
11869                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11870                                            changedRuntimePermissionUserIds, userId);
11871                                }
11872                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11873                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11874                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11875                                        // If we cannot put the permission as it was,
11876                                        // we have to write.
11877                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11878                                                changedRuntimePermissionUserIds, userId);
11879                                    }
11880                                }
11881
11882                                // If the app supports runtime permissions no need for a review.
11883                                if (mPermissionReviewRequired
11884                                        && appSupportsRuntimePermissions
11885                                        && (flags & PackageManager
11886                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11887                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11888                                    // Since we changed the flags, we have to write.
11889                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11890                                            changedRuntimePermissionUserIds, userId);
11891                                }
11892                            } else if (mPermissionReviewRequired
11893                                    && !appSupportsRuntimePermissions) {
11894                                // For legacy apps that need a permission review, every new
11895                                // runtime permission is granted but it is pending a review.
11896                                // We also need to review only platform defined runtime
11897                                // permissions as these are the only ones the platform knows
11898                                // how to disable the API to simulate revocation as legacy
11899                                // apps don't expect to run with revoked permissions.
11900                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11901                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11902                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11903                                        // We changed the flags, hence have to write.
11904                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11905                                                changedRuntimePermissionUserIds, userId);
11906                                    }
11907                                }
11908                                if (permissionsState.grantRuntimePermission(bp, userId)
11909                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11910                                    // We changed the permission, hence have to write.
11911                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11912                                            changedRuntimePermissionUserIds, userId);
11913                                }
11914                            }
11915                            // Propagate the permission flags.
11916                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11917                        }
11918                    } break;
11919
11920                    case GRANT_UPGRADE: {
11921                        // Grant runtime permissions for a previously held install permission.
11922                        PermissionState permissionState = origPermissions
11923                                .getInstallPermissionState(bp.name);
11924                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11925
11926                        if (origPermissions.revokeInstallPermission(bp)
11927                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11928                            // We will be transferring the permission flags, so clear them.
11929                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11930                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11931                            changedInstallPermission = true;
11932                        }
11933
11934                        // If the permission is not to be promoted to runtime we ignore it and
11935                        // also its other flags as they are not applicable to install permissions.
11936                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11937                            for (int userId : currentUserIds) {
11938                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11939                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11940                                    // Transfer the permission flags.
11941                                    permissionsState.updatePermissionFlags(bp, userId,
11942                                            flags, flags);
11943                                    // If we granted the permission, we have to write.
11944                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11945                                            changedRuntimePermissionUserIds, userId);
11946                                }
11947                            }
11948                        }
11949                    } break;
11950
11951                    default: {
11952                        if (packageOfInterest == null
11953                                || packageOfInterest.equals(pkg.packageName)) {
11954                            Slog.w(TAG, "Not granting permission " + perm
11955                                    + " to package " + pkg.packageName
11956                                    + " because it was previously installed without");
11957                        }
11958                    } break;
11959                }
11960            } else {
11961                if (permissionsState.revokeInstallPermission(bp) !=
11962                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11963                    // Also drop the permission flags.
11964                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11965                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11966                    changedInstallPermission = true;
11967                    Slog.i(TAG, "Un-granting permission " + perm
11968                            + " from package " + pkg.packageName
11969                            + " (protectionLevel=" + bp.protectionLevel
11970                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11971                            + ")");
11972                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11973                    // Don't print warning for app op permissions, since it is fine for them
11974                    // not to be granted, there is a UI for the user to decide.
11975                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11976                        Slog.w(TAG, "Not granting permission " + perm
11977                                + " to package " + pkg.packageName
11978                                + " (protectionLevel=" + bp.protectionLevel
11979                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11980                                + ")");
11981                    }
11982                }
11983            }
11984        }
11985
11986        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11987                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11988            // This is the first that we have heard about this package, so the
11989            // permissions we have now selected are fixed until explicitly
11990            // changed.
11991            ps.installPermissionsFixed = true;
11992        }
11993
11994        // Persist the runtime permissions state for users with changes. If permissions
11995        // were revoked because no app in the shared user declares them we have to
11996        // write synchronously to avoid losing runtime permissions state.
11997        for (int userId : changedRuntimePermissionUserIds) {
11998            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11999        }
12000    }
12001
12002    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12003        boolean allowed = false;
12004        final int NP = PackageParser.NEW_PERMISSIONS.length;
12005        for (int ip=0; ip<NP; ip++) {
12006            final PackageParser.NewPermissionInfo npi
12007                    = PackageParser.NEW_PERMISSIONS[ip];
12008            if (npi.name.equals(perm)
12009                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12010                allowed = true;
12011                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12012                        + pkg.packageName);
12013                break;
12014            }
12015        }
12016        return allowed;
12017    }
12018
12019    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12020            BasePermission bp, PermissionsState origPermissions) {
12021        boolean privilegedPermission = (bp.protectionLevel
12022                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12023        boolean privappPermissionsDisable =
12024                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12025        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12026        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12027        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12028                && !platformPackage && platformPermission) {
12029            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12030                    .getPrivAppPermissions(pkg.packageName);
12031            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12032            if (!whitelisted) {
12033                Slog.w(TAG, "Privileged permission " + perm + " for package "
12034                        + pkg.packageName + " - not in privapp-permissions whitelist");
12035                // Only report violations for apps on system image
12036                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12037                    if (mPrivappPermissionsViolations == null) {
12038                        mPrivappPermissionsViolations = new ArraySet<>();
12039                    }
12040                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12041                }
12042                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12043                    return false;
12044                }
12045            }
12046        }
12047        boolean allowed = (compareSignatures(
12048                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12049                        == PackageManager.SIGNATURE_MATCH)
12050                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12051                        == PackageManager.SIGNATURE_MATCH);
12052        if (!allowed && privilegedPermission) {
12053            if (isSystemApp(pkg)) {
12054                // For updated system applications, a system permission
12055                // is granted only if it had been defined by the original application.
12056                if (pkg.isUpdatedSystemApp()) {
12057                    final PackageSetting sysPs = mSettings
12058                            .getDisabledSystemPkgLPr(pkg.packageName);
12059                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12060                        // If the original was granted this permission, we take
12061                        // that grant decision as read and propagate it to the
12062                        // update.
12063                        if (sysPs.isPrivileged()) {
12064                            allowed = true;
12065                        }
12066                    } else {
12067                        // The system apk may have been updated with an older
12068                        // version of the one on the data partition, but which
12069                        // granted a new system permission that it didn't have
12070                        // before.  In this case we do want to allow the app to
12071                        // now get the new permission if the ancestral apk is
12072                        // privileged to get it.
12073                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12074                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12075                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12076                                    allowed = true;
12077                                    break;
12078                                }
12079                            }
12080                        }
12081                        // Also if a privileged parent package on the system image or any of
12082                        // its children requested a privileged permission, the updated child
12083                        // packages can also get the permission.
12084                        if (pkg.parentPackage != null) {
12085                            final PackageSetting disabledSysParentPs = mSettings
12086                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12087                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12088                                    && disabledSysParentPs.isPrivileged()) {
12089                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12090                                    allowed = true;
12091                                } else if (disabledSysParentPs.pkg.childPackages != null) {
12092                                    final int count = disabledSysParentPs.pkg.childPackages.size();
12093                                    for (int i = 0; i < count; i++) {
12094                                        PackageParser.Package disabledSysChildPkg =
12095                                                disabledSysParentPs.pkg.childPackages.get(i);
12096                                        if (isPackageRequestingPermission(disabledSysChildPkg,
12097                                                perm)) {
12098                                            allowed = true;
12099                                            break;
12100                                        }
12101                                    }
12102                                }
12103                            }
12104                        }
12105                    }
12106                } else {
12107                    allowed = isPrivilegedApp(pkg);
12108                }
12109            }
12110        }
12111        if (!allowed) {
12112            if (!allowed && (bp.protectionLevel
12113                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12114                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12115                // If this was a previously normal/dangerous permission that got moved
12116                // to a system permission as part of the runtime permission redesign, then
12117                // we still want to blindly grant it to old apps.
12118                allowed = true;
12119            }
12120            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12121                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12122                // If this permission is to be granted to the system installer and
12123                // this app is an installer, then it gets the permission.
12124                allowed = true;
12125            }
12126            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12127                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12128                // If this permission is to be granted to the system verifier and
12129                // this app is a verifier, then it gets the permission.
12130                allowed = true;
12131            }
12132            if (!allowed && (bp.protectionLevel
12133                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12134                    && isSystemApp(pkg)) {
12135                // Any pre-installed system app is allowed to get this permission.
12136                allowed = true;
12137            }
12138            if (!allowed && (bp.protectionLevel
12139                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12140                // For development permissions, a development permission
12141                // is granted only if it was already granted.
12142                allowed = origPermissions.hasInstallPermission(perm);
12143            }
12144            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12145                    && pkg.packageName.equals(mSetupWizardPackage)) {
12146                // If this permission is to be granted to the system setup wizard and
12147                // this app is a setup wizard, then it gets the permission.
12148                allowed = true;
12149            }
12150        }
12151        return allowed;
12152    }
12153
12154    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12155        final int permCount = pkg.requestedPermissions.size();
12156        for (int j = 0; j < permCount; j++) {
12157            String requestedPermission = pkg.requestedPermissions.get(j);
12158            if (permission.equals(requestedPermission)) {
12159                return true;
12160            }
12161        }
12162        return false;
12163    }
12164
12165    final class ActivityIntentResolver
12166            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12167        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12168                boolean defaultOnly, int userId) {
12169            if (!sUserManager.exists(userId)) return null;
12170            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12171            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12172        }
12173
12174        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12175                int userId) {
12176            if (!sUserManager.exists(userId)) return null;
12177            mFlags = flags;
12178            return super.queryIntent(intent, resolvedType,
12179                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12180                    userId);
12181        }
12182
12183        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12184                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12185            if (!sUserManager.exists(userId)) return null;
12186            if (packageActivities == null) {
12187                return null;
12188            }
12189            mFlags = flags;
12190            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12191            final int N = packageActivities.size();
12192            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12193                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12194
12195            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12196            for (int i = 0; i < N; ++i) {
12197                intentFilters = packageActivities.get(i).intents;
12198                if (intentFilters != null && intentFilters.size() > 0) {
12199                    PackageParser.ActivityIntentInfo[] array =
12200                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12201                    intentFilters.toArray(array);
12202                    listCut.add(array);
12203                }
12204            }
12205            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12206        }
12207
12208        /**
12209         * Finds a privileged activity that matches the specified activity names.
12210         */
12211        private PackageParser.Activity findMatchingActivity(
12212                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12213            for (PackageParser.Activity sysActivity : activityList) {
12214                if (sysActivity.info.name.equals(activityInfo.name)) {
12215                    return sysActivity;
12216                }
12217                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12218                    return sysActivity;
12219                }
12220                if (sysActivity.info.targetActivity != null) {
12221                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12222                        return sysActivity;
12223                    }
12224                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12225                        return sysActivity;
12226                    }
12227                }
12228            }
12229            return null;
12230        }
12231
12232        public class IterGenerator<E> {
12233            public Iterator<E> generate(ActivityIntentInfo info) {
12234                return null;
12235            }
12236        }
12237
12238        public class ActionIterGenerator extends IterGenerator<String> {
12239            @Override
12240            public Iterator<String> generate(ActivityIntentInfo info) {
12241                return info.actionsIterator();
12242            }
12243        }
12244
12245        public class CategoriesIterGenerator extends IterGenerator<String> {
12246            @Override
12247            public Iterator<String> generate(ActivityIntentInfo info) {
12248                return info.categoriesIterator();
12249            }
12250        }
12251
12252        public class SchemesIterGenerator extends IterGenerator<String> {
12253            @Override
12254            public Iterator<String> generate(ActivityIntentInfo info) {
12255                return info.schemesIterator();
12256            }
12257        }
12258
12259        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12260            @Override
12261            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12262                return info.authoritiesIterator();
12263            }
12264        }
12265
12266        /**
12267         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12268         * MODIFIED. Do not pass in a list that should not be changed.
12269         */
12270        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12271                IterGenerator<T> generator, Iterator<T> searchIterator) {
12272            // loop through the set of actions; every one must be found in the intent filter
12273            while (searchIterator.hasNext()) {
12274                // we must have at least one filter in the list to consider a match
12275                if (intentList.size() == 0) {
12276                    break;
12277                }
12278
12279                final T searchAction = searchIterator.next();
12280
12281                // loop through the set of intent filters
12282                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12283                while (intentIter.hasNext()) {
12284                    final ActivityIntentInfo intentInfo = intentIter.next();
12285                    boolean selectionFound = false;
12286
12287                    // loop through the intent filter's selection criteria; at least one
12288                    // of them must match the searched criteria
12289                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12290                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12291                        final T intentSelection = intentSelectionIter.next();
12292                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12293                            selectionFound = true;
12294                            break;
12295                        }
12296                    }
12297
12298                    // the selection criteria wasn't found in this filter's set; this filter
12299                    // is not a potential match
12300                    if (!selectionFound) {
12301                        intentIter.remove();
12302                    }
12303                }
12304            }
12305        }
12306
12307        private boolean isProtectedAction(ActivityIntentInfo filter) {
12308            final Iterator<String> actionsIter = filter.actionsIterator();
12309            while (actionsIter != null && actionsIter.hasNext()) {
12310                final String filterAction = actionsIter.next();
12311                if (PROTECTED_ACTIONS.contains(filterAction)) {
12312                    return true;
12313                }
12314            }
12315            return false;
12316        }
12317
12318        /**
12319         * Adjusts the priority of the given intent filter according to policy.
12320         * <p>
12321         * <ul>
12322         * <li>The priority for non privileged applications is capped to '0'</li>
12323         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12324         * <li>The priority for unbundled updates to privileged applications is capped to the
12325         *      priority defined on the system partition</li>
12326         * </ul>
12327         * <p>
12328         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12329         * allowed to obtain any priority on any action.
12330         */
12331        private void adjustPriority(
12332                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12333            // nothing to do; priority is fine as-is
12334            if (intent.getPriority() <= 0) {
12335                return;
12336            }
12337
12338            final ActivityInfo activityInfo = intent.activity.info;
12339            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12340
12341            final boolean privilegedApp =
12342                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12343            if (!privilegedApp) {
12344                // non-privileged applications can never define a priority >0
12345                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
12346                        + " package: " + applicationInfo.packageName
12347                        + " activity: " + intent.activity.className
12348                        + " origPrio: " + intent.getPriority());
12349                intent.setPriority(0);
12350                return;
12351            }
12352
12353            if (systemActivities == null) {
12354                // the system package is not disabled; we're parsing the system partition
12355                if (isProtectedAction(intent)) {
12356                    if (mDeferProtectedFilters) {
12357                        // We can't deal with these just yet. No component should ever obtain a
12358                        // >0 priority for a protected actions, with ONE exception -- the setup
12359                        // wizard. The setup wizard, however, cannot be known until we're able to
12360                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12361                        // until all intent filters have been processed. Chicken, meet egg.
12362                        // Let the filter temporarily have a high priority and rectify the
12363                        // priorities after all system packages have been scanned.
12364                        mProtectedFilters.add(intent);
12365                        if (DEBUG_FILTERS) {
12366                            Slog.i(TAG, "Protected action; save for later;"
12367                                    + " package: " + applicationInfo.packageName
12368                                    + " activity: " + intent.activity.className
12369                                    + " origPrio: " + intent.getPriority());
12370                        }
12371                        return;
12372                    } else {
12373                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12374                            Slog.i(TAG, "No setup wizard;"
12375                                + " All protected intents capped to priority 0");
12376                        }
12377                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12378                            if (DEBUG_FILTERS) {
12379                                Slog.i(TAG, "Found setup wizard;"
12380                                    + " allow priority " + intent.getPriority() + ";"
12381                                    + " package: " + intent.activity.info.packageName
12382                                    + " activity: " + intent.activity.className
12383                                    + " priority: " + intent.getPriority());
12384                            }
12385                            // setup wizard gets whatever it wants
12386                            return;
12387                        }
12388                        Slog.w(TAG, "Protected action; cap priority to 0;"
12389                                + " package: " + intent.activity.info.packageName
12390                                + " activity: " + intent.activity.className
12391                                + " origPrio: " + intent.getPriority());
12392                        intent.setPriority(0);
12393                        return;
12394                    }
12395                }
12396                // privileged apps on the system image get whatever priority they request
12397                return;
12398            }
12399
12400            // privileged app unbundled update ... try to find the same activity
12401            final PackageParser.Activity foundActivity =
12402                    findMatchingActivity(systemActivities, activityInfo);
12403            if (foundActivity == null) {
12404                // this is a new activity; it cannot obtain >0 priority
12405                if (DEBUG_FILTERS) {
12406                    Slog.i(TAG, "New activity; cap priority to 0;"
12407                            + " package: " + applicationInfo.packageName
12408                            + " activity: " + intent.activity.className
12409                            + " origPrio: " + intent.getPriority());
12410                }
12411                intent.setPriority(0);
12412                return;
12413            }
12414
12415            // found activity, now check for filter equivalence
12416
12417            // a shallow copy is enough; we modify the list, not its contents
12418            final List<ActivityIntentInfo> intentListCopy =
12419                    new ArrayList<>(foundActivity.intents);
12420            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12421
12422            // find matching action subsets
12423            final Iterator<String> actionsIterator = intent.actionsIterator();
12424            if (actionsIterator != null) {
12425                getIntentListSubset(
12426                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12427                if (intentListCopy.size() == 0) {
12428                    // no more intents to match; we're not equivalent
12429                    if (DEBUG_FILTERS) {
12430                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12431                                + " package: " + applicationInfo.packageName
12432                                + " activity: " + intent.activity.className
12433                                + " origPrio: " + intent.getPriority());
12434                    }
12435                    intent.setPriority(0);
12436                    return;
12437                }
12438            }
12439
12440            // find matching category subsets
12441            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12442            if (categoriesIterator != null) {
12443                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12444                        categoriesIterator);
12445                if (intentListCopy.size() == 0) {
12446                    // no more intents to match; we're not equivalent
12447                    if (DEBUG_FILTERS) {
12448                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12449                                + " package: " + applicationInfo.packageName
12450                                + " activity: " + intent.activity.className
12451                                + " origPrio: " + intent.getPriority());
12452                    }
12453                    intent.setPriority(0);
12454                    return;
12455                }
12456            }
12457
12458            // find matching schemes subsets
12459            final Iterator<String> schemesIterator = intent.schemesIterator();
12460            if (schemesIterator != null) {
12461                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12462                        schemesIterator);
12463                if (intentListCopy.size() == 0) {
12464                    // no more intents to match; we're not equivalent
12465                    if (DEBUG_FILTERS) {
12466                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12467                                + " package: " + applicationInfo.packageName
12468                                + " activity: " + intent.activity.className
12469                                + " origPrio: " + intent.getPriority());
12470                    }
12471                    intent.setPriority(0);
12472                    return;
12473                }
12474            }
12475
12476            // find matching authorities subsets
12477            final Iterator<IntentFilter.AuthorityEntry>
12478                    authoritiesIterator = intent.authoritiesIterator();
12479            if (authoritiesIterator != null) {
12480                getIntentListSubset(intentListCopy,
12481                        new AuthoritiesIterGenerator(),
12482                        authoritiesIterator);
12483                if (intentListCopy.size() == 0) {
12484                    // no more intents to match; we're not equivalent
12485                    if (DEBUG_FILTERS) {
12486                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12487                                + " package: " + applicationInfo.packageName
12488                                + " activity: " + intent.activity.className
12489                                + " origPrio: " + intent.getPriority());
12490                    }
12491                    intent.setPriority(0);
12492                    return;
12493                }
12494            }
12495
12496            // we found matching filter(s); app gets the max priority of all intents
12497            int cappedPriority = 0;
12498            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12499                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12500            }
12501            if (intent.getPriority() > cappedPriority) {
12502                if (DEBUG_FILTERS) {
12503                    Slog.i(TAG, "Found matching filter(s);"
12504                            + " cap priority to " + cappedPriority + ";"
12505                            + " package: " + applicationInfo.packageName
12506                            + " activity: " + intent.activity.className
12507                            + " origPrio: " + intent.getPriority());
12508                }
12509                intent.setPriority(cappedPriority);
12510                return;
12511            }
12512            // all this for nothing; the requested priority was <= what was on the system
12513        }
12514
12515        public final void addActivity(PackageParser.Activity a, String type) {
12516            mActivities.put(a.getComponentName(), a);
12517            if (DEBUG_SHOW_INFO)
12518                Log.v(
12519                TAG, "  " + type + " " +
12520                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12521            if (DEBUG_SHOW_INFO)
12522                Log.v(TAG, "    Class=" + a.info.name);
12523            final int NI = a.intents.size();
12524            for (int j=0; j<NI; j++) {
12525                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12526                if ("activity".equals(type)) {
12527                    final PackageSetting ps =
12528                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12529                    final List<PackageParser.Activity> systemActivities =
12530                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12531                    adjustPriority(systemActivities, intent);
12532                }
12533                if (DEBUG_SHOW_INFO) {
12534                    Log.v(TAG, "    IntentFilter:");
12535                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12536                }
12537                if (!intent.debugCheck()) {
12538                    Log.w(TAG, "==> For Activity " + a.info.name);
12539                }
12540                addFilter(intent);
12541            }
12542        }
12543
12544        public final void removeActivity(PackageParser.Activity a, String type) {
12545            mActivities.remove(a.getComponentName());
12546            if (DEBUG_SHOW_INFO) {
12547                Log.v(TAG, "  " + type + " "
12548                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12549                                : a.info.name) + ":");
12550                Log.v(TAG, "    Class=" + a.info.name);
12551            }
12552            final int NI = a.intents.size();
12553            for (int j=0; j<NI; j++) {
12554                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12555                if (DEBUG_SHOW_INFO) {
12556                    Log.v(TAG, "    IntentFilter:");
12557                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12558                }
12559                removeFilter(intent);
12560            }
12561        }
12562
12563        @Override
12564        protected boolean allowFilterResult(
12565                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12566            ActivityInfo filterAi = filter.activity.info;
12567            for (int i=dest.size()-1; i>=0; i--) {
12568                ActivityInfo destAi = dest.get(i).activityInfo;
12569                if (destAi.name == filterAi.name
12570                        && destAi.packageName == filterAi.packageName) {
12571                    return false;
12572                }
12573            }
12574            return true;
12575        }
12576
12577        @Override
12578        protected ActivityIntentInfo[] newArray(int size) {
12579            return new ActivityIntentInfo[size];
12580        }
12581
12582        @Override
12583        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12584            if (!sUserManager.exists(userId)) return true;
12585            PackageParser.Package p = filter.activity.owner;
12586            if (p != null) {
12587                PackageSetting ps = (PackageSetting)p.mExtras;
12588                if (ps != null) {
12589                    // System apps are never considered stopped for purposes of
12590                    // filtering, because there may be no way for the user to
12591                    // actually re-launch them.
12592                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12593                            && ps.getStopped(userId);
12594                }
12595            }
12596            return false;
12597        }
12598
12599        @Override
12600        protected boolean isPackageForFilter(String packageName,
12601                PackageParser.ActivityIntentInfo info) {
12602            return packageName.equals(info.activity.owner.packageName);
12603        }
12604
12605        @Override
12606        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12607                int match, int userId) {
12608            if (!sUserManager.exists(userId)) return null;
12609            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12610                return null;
12611            }
12612            final PackageParser.Activity activity = info.activity;
12613            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12614            if (ps == null) {
12615                return null;
12616            }
12617            final PackageUserState userState = ps.readUserState(userId);
12618            ActivityInfo ai = generateActivityInfo(activity, mFlags, userState, userId);
12619            if (ai == null) {
12620                return null;
12621            }
12622            final boolean matchExplicitlyVisibleOnly =
12623                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12624            final boolean matchVisibleToInstantApp =
12625                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12626            final boolean componentVisible =
12627                    matchVisibleToInstantApp
12628                    && info.isVisibleToInstantApp()
12629                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12630            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12631            // throw out filters that aren't visible to ephemeral apps
12632            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12633                return null;
12634            }
12635            // throw out instant app filters if we're not explicitly requesting them
12636            if (!matchInstantApp && userState.instantApp) {
12637                return null;
12638            }
12639            // throw out instant app filters if updates are available; will trigger
12640            // instant app resolution
12641            if (userState.instantApp && ps.isUpdateAvailable()) {
12642                return null;
12643            }
12644            final ResolveInfo res = new ResolveInfo();
12645            res.activityInfo = ai;
12646            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12647                res.filter = info;
12648            }
12649            if (info != null) {
12650                res.handleAllWebDataURI = info.handleAllWebDataURI();
12651            }
12652            res.priority = info.getPriority();
12653            res.preferredOrder = activity.owner.mPreferredOrder;
12654            //System.out.println("Result: " + res.activityInfo.className +
12655            //                   " = " + res.priority);
12656            res.match = match;
12657            res.isDefault = info.hasDefault;
12658            res.labelRes = info.labelRes;
12659            res.nonLocalizedLabel = info.nonLocalizedLabel;
12660            if (userNeedsBadging(userId)) {
12661                res.noResourceId = true;
12662            } else {
12663                res.icon = info.icon;
12664            }
12665            res.iconResourceId = info.icon;
12666            res.system = res.activityInfo.applicationInfo.isSystemApp();
12667            res.isInstantAppAvailable = userState.instantApp;
12668            return res;
12669        }
12670
12671        @Override
12672        protected void sortResults(List<ResolveInfo> results) {
12673            Collections.sort(results, mResolvePrioritySorter);
12674        }
12675
12676        @Override
12677        protected void dumpFilter(PrintWriter out, String prefix,
12678                PackageParser.ActivityIntentInfo filter) {
12679            out.print(prefix); out.print(
12680                    Integer.toHexString(System.identityHashCode(filter.activity)));
12681                    out.print(' ');
12682                    filter.activity.printComponentShortName(out);
12683                    out.print(" filter ");
12684                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12685        }
12686
12687        @Override
12688        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12689            return filter.activity;
12690        }
12691
12692        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12693            PackageParser.Activity activity = (PackageParser.Activity)label;
12694            out.print(prefix); out.print(
12695                    Integer.toHexString(System.identityHashCode(activity)));
12696                    out.print(' ');
12697                    activity.printComponentShortName(out);
12698            if (count > 1) {
12699                out.print(" ("); out.print(count); out.print(" filters)");
12700            }
12701            out.println();
12702        }
12703
12704        // Keys are String (activity class name), values are Activity.
12705        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12706                = new ArrayMap<ComponentName, PackageParser.Activity>();
12707        private int mFlags;
12708    }
12709
12710    private final class ServiceIntentResolver
12711            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12712        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12713                boolean defaultOnly, int userId) {
12714            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12715            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12716        }
12717
12718        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12719                int userId) {
12720            if (!sUserManager.exists(userId)) return null;
12721            mFlags = flags;
12722            return super.queryIntent(intent, resolvedType,
12723                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12724                    userId);
12725        }
12726
12727        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12728                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12729            if (!sUserManager.exists(userId)) return null;
12730            if (packageServices == null) {
12731                return null;
12732            }
12733            mFlags = flags;
12734            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12735            final int N = packageServices.size();
12736            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12737                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12738
12739            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12740            for (int i = 0; i < N; ++i) {
12741                intentFilters = packageServices.get(i).intents;
12742                if (intentFilters != null && intentFilters.size() > 0) {
12743                    PackageParser.ServiceIntentInfo[] array =
12744                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12745                    intentFilters.toArray(array);
12746                    listCut.add(array);
12747                }
12748            }
12749            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12750        }
12751
12752        public final void addService(PackageParser.Service s) {
12753            mServices.put(s.getComponentName(), s);
12754            if (DEBUG_SHOW_INFO) {
12755                Log.v(TAG, "  "
12756                        + (s.info.nonLocalizedLabel != null
12757                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12758                Log.v(TAG, "    Class=" + s.info.name);
12759            }
12760            final int NI = s.intents.size();
12761            int j;
12762            for (j=0; j<NI; j++) {
12763                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12764                if (DEBUG_SHOW_INFO) {
12765                    Log.v(TAG, "    IntentFilter:");
12766                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12767                }
12768                if (!intent.debugCheck()) {
12769                    Log.w(TAG, "==> For Service " + s.info.name);
12770                }
12771                addFilter(intent);
12772            }
12773        }
12774
12775        public final void removeService(PackageParser.Service s) {
12776            mServices.remove(s.getComponentName());
12777            if (DEBUG_SHOW_INFO) {
12778                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12779                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12780                Log.v(TAG, "    Class=" + s.info.name);
12781            }
12782            final int NI = s.intents.size();
12783            int j;
12784            for (j=0; j<NI; j++) {
12785                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12786                if (DEBUG_SHOW_INFO) {
12787                    Log.v(TAG, "    IntentFilter:");
12788                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12789                }
12790                removeFilter(intent);
12791            }
12792        }
12793
12794        @Override
12795        protected boolean allowFilterResult(
12796                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12797            ServiceInfo filterSi = filter.service.info;
12798            for (int i=dest.size()-1; i>=0; i--) {
12799                ServiceInfo destAi = dest.get(i).serviceInfo;
12800                if (destAi.name == filterSi.name
12801                        && destAi.packageName == filterSi.packageName) {
12802                    return false;
12803                }
12804            }
12805            return true;
12806        }
12807
12808        @Override
12809        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12810            return new PackageParser.ServiceIntentInfo[size];
12811        }
12812
12813        @Override
12814        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12815            if (!sUserManager.exists(userId)) return true;
12816            PackageParser.Package p = filter.service.owner;
12817            if (p != null) {
12818                PackageSetting ps = (PackageSetting)p.mExtras;
12819                if (ps != null) {
12820                    // System apps are never considered stopped for purposes of
12821                    // filtering, because there may be no way for the user to
12822                    // actually re-launch them.
12823                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12824                            && ps.getStopped(userId);
12825                }
12826            }
12827            return false;
12828        }
12829
12830        @Override
12831        protected boolean isPackageForFilter(String packageName,
12832                PackageParser.ServiceIntentInfo info) {
12833            return packageName.equals(info.service.owner.packageName);
12834        }
12835
12836        @Override
12837        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12838                int match, int userId) {
12839            if (!sUserManager.exists(userId)) return null;
12840            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12841            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12842                return null;
12843            }
12844            final PackageParser.Service service = info.service;
12845            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12846            if (ps == null) {
12847                return null;
12848            }
12849            final PackageUserState userState = ps.readUserState(userId);
12850            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12851                    userState, userId);
12852            if (si == null) {
12853                return null;
12854            }
12855            final boolean matchVisibleToInstantApp =
12856                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12857            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12858            // throw out filters that aren't visible to ephemeral apps
12859            if (matchVisibleToInstantApp
12860                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12861                return null;
12862            }
12863            // throw out ephemeral filters if we're not explicitly requesting them
12864            if (!isInstantApp && userState.instantApp) {
12865                return null;
12866            }
12867            // throw out instant app filters if updates are available; will trigger
12868            // instant app resolution
12869            if (userState.instantApp && ps.isUpdateAvailable()) {
12870                return null;
12871            }
12872            final ResolveInfo res = new ResolveInfo();
12873            res.serviceInfo = si;
12874            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12875                res.filter = filter;
12876            }
12877            res.priority = info.getPriority();
12878            res.preferredOrder = service.owner.mPreferredOrder;
12879            res.match = match;
12880            res.isDefault = info.hasDefault;
12881            res.labelRes = info.labelRes;
12882            res.nonLocalizedLabel = info.nonLocalizedLabel;
12883            res.icon = info.icon;
12884            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12885            return res;
12886        }
12887
12888        @Override
12889        protected void sortResults(List<ResolveInfo> results) {
12890            Collections.sort(results, mResolvePrioritySorter);
12891        }
12892
12893        @Override
12894        protected void dumpFilter(PrintWriter out, String prefix,
12895                PackageParser.ServiceIntentInfo filter) {
12896            out.print(prefix); out.print(
12897                    Integer.toHexString(System.identityHashCode(filter.service)));
12898                    out.print(' ');
12899                    filter.service.printComponentShortName(out);
12900                    out.print(" filter ");
12901                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12902        }
12903
12904        @Override
12905        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12906            return filter.service;
12907        }
12908
12909        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12910            PackageParser.Service service = (PackageParser.Service)label;
12911            out.print(prefix); out.print(
12912                    Integer.toHexString(System.identityHashCode(service)));
12913                    out.print(' ');
12914                    service.printComponentShortName(out);
12915            if (count > 1) {
12916                out.print(" ("); out.print(count); out.print(" filters)");
12917            }
12918            out.println();
12919        }
12920
12921//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12922//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12923//            final List<ResolveInfo> retList = Lists.newArrayList();
12924//            while (i.hasNext()) {
12925//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12926//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12927//                    retList.add(resolveInfo);
12928//                }
12929//            }
12930//            return retList;
12931//        }
12932
12933        // Keys are String (activity class name), values are Activity.
12934        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12935                = new ArrayMap<ComponentName, PackageParser.Service>();
12936        private int mFlags;
12937    }
12938
12939    private final class ProviderIntentResolver
12940            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12941        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12942                boolean defaultOnly, int userId) {
12943            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12944            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12945        }
12946
12947        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12948                int userId) {
12949            if (!sUserManager.exists(userId))
12950                return null;
12951            mFlags = flags;
12952            return super.queryIntent(intent, resolvedType,
12953                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12954                    userId);
12955        }
12956
12957        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12958                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12959            if (!sUserManager.exists(userId))
12960                return null;
12961            if (packageProviders == null) {
12962                return null;
12963            }
12964            mFlags = flags;
12965            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12966            final int N = packageProviders.size();
12967            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12968                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12969
12970            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12971            for (int i = 0; i < N; ++i) {
12972                intentFilters = packageProviders.get(i).intents;
12973                if (intentFilters != null && intentFilters.size() > 0) {
12974                    PackageParser.ProviderIntentInfo[] array =
12975                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12976                    intentFilters.toArray(array);
12977                    listCut.add(array);
12978                }
12979            }
12980            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12981        }
12982
12983        public final void addProvider(PackageParser.Provider p) {
12984            if (mProviders.containsKey(p.getComponentName())) {
12985                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12986                return;
12987            }
12988
12989            mProviders.put(p.getComponentName(), p);
12990            if (DEBUG_SHOW_INFO) {
12991                Log.v(TAG, "  "
12992                        + (p.info.nonLocalizedLabel != null
12993                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12994                Log.v(TAG, "    Class=" + p.info.name);
12995            }
12996            final int NI = p.intents.size();
12997            int j;
12998            for (j = 0; j < NI; j++) {
12999                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13000                if (DEBUG_SHOW_INFO) {
13001                    Log.v(TAG, "    IntentFilter:");
13002                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13003                }
13004                if (!intent.debugCheck()) {
13005                    Log.w(TAG, "==> For Provider " + p.info.name);
13006                }
13007                addFilter(intent);
13008            }
13009        }
13010
13011        public final void removeProvider(PackageParser.Provider p) {
13012            mProviders.remove(p.getComponentName());
13013            if (DEBUG_SHOW_INFO) {
13014                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13015                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13016                Log.v(TAG, "    Class=" + p.info.name);
13017            }
13018            final int NI = p.intents.size();
13019            int j;
13020            for (j = 0; j < NI; j++) {
13021                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13022                if (DEBUG_SHOW_INFO) {
13023                    Log.v(TAG, "    IntentFilter:");
13024                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13025                }
13026                removeFilter(intent);
13027            }
13028        }
13029
13030        @Override
13031        protected boolean allowFilterResult(
13032                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13033            ProviderInfo filterPi = filter.provider.info;
13034            for (int i = dest.size() - 1; i >= 0; i--) {
13035                ProviderInfo destPi = dest.get(i).providerInfo;
13036                if (destPi.name == filterPi.name
13037                        && destPi.packageName == filterPi.packageName) {
13038                    return false;
13039                }
13040            }
13041            return true;
13042        }
13043
13044        @Override
13045        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13046            return new PackageParser.ProviderIntentInfo[size];
13047        }
13048
13049        @Override
13050        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13051            if (!sUserManager.exists(userId))
13052                return true;
13053            PackageParser.Package p = filter.provider.owner;
13054            if (p != null) {
13055                PackageSetting ps = (PackageSetting) p.mExtras;
13056                if (ps != null) {
13057                    // System apps are never considered stopped for purposes of
13058                    // filtering, because there may be no way for the user to
13059                    // actually re-launch them.
13060                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13061                            && ps.getStopped(userId);
13062                }
13063            }
13064            return false;
13065        }
13066
13067        @Override
13068        protected boolean isPackageForFilter(String packageName,
13069                PackageParser.ProviderIntentInfo info) {
13070            return packageName.equals(info.provider.owner.packageName);
13071        }
13072
13073        @Override
13074        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13075                int match, int userId) {
13076            if (!sUserManager.exists(userId))
13077                return null;
13078            final PackageParser.ProviderIntentInfo info = filter;
13079            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13080                return null;
13081            }
13082            final PackageParser.Provider provider = info.provider;
13083            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13084            if (ps == null) {
13085                return null;
13086            }
13087            final PackageUserState userState = ps.readUserState(userId);
13088            final boolean matchVisibleToInstantApp =
13089                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13090            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13091            // throw out filters that aren't visible to instant applications
13092            if (matchVisibleToInstantApp
13093                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13094                return null;
13095            }
13096            // throw out instant application filters if we're not explicitly requesting them
13097            if (!isInstantApp && userState.instantApp) {
13098                return null;
13099            }
13100            // throw out instant application filters if updates are available; will trigger
13101            // instant application resolution
13102            if (userState.instantApp && ps.isUpdateAvailable()) {
13103                return null;
13104            }
13105            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13106                    userState, userId);
13107            if (pi == null) {
13108                return null;
13109            }
13110            final ResolveInfo res = new ResolveInfo();
13111            res.providerInfo = pi;
13112            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13113                res.filter = filter;
13114            }
13115            res.priority = info.getPriority();
13116            res.preferredOrder = provider.owner.mPreferredOrder;
13117            res.match = match;
13118            res.isDefault = info.hasDefault;
13119            res.labelRes = info.labelRes;
13120            res.nonLocalizedLabel = info.nonLocalizedLabel;
13121            res.icon = info.icon;
13122            res.system = res.providerInfo.applicationInfo.isSystemApp();
13123            return res;
13124        }
13125
13126        @Override
13127        protected void sortResults(List<ResolveInfo> results) {
13128            Collections.sort(results, mResolvePrioritySorter);
13129        }
13130
13131        @Override
13132        protected void dumpFilter(PrintWriter out, String prefix,
13133                PackageParser.ProviderIntentInfo filter) {
13134            out.print(prefix);
13135            out.print(
13136                    Integer.toHexString(System.identityHashCode(filter.provider)));
13137            out.print(' ');
13138            filter.provider.printComponentShortName(out);
13139            out.print(" filter ");
13140            out.println(Integer.toHexString(System.identityHashCode(filter)));
13141        }
13142
13143        @Override
13144        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13145            return filter.provider;
13146        }
13147
13148        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13149            PackageParser.Provider provider = (PackageParser.Provider)label;
13150            out.print(prefix); out.print(
13151                    Integer.toHexString(System.identityHashCode(provider)));
13152                    out.print(' ');
13153                    provider.printComponentShortName(out);
13154            if (count > 1) {
13155                out.print(" ("); out.print(count); out.print(" filters)");
13156            }
13157            out.println();
13158        }
13159
13160        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13161                = new ArrayMap<ComponentName, PackageParser.Provider>();
13162        private int mFlags;
13163    }
13164
13165    static final class EphemeralIntentResolver
13166            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13167        /**
13168         * The result that has the highest defined order. Ordering applies on a
13169         * per-package basis. Mapping is from package name to Pair of order and
13170         * EphemeralResolveInfo.
13171         * <p>
13172         * NOTE: This is implemented as a field variable for convenience and efficiency.
13173         * By having a field variable, we're able to track filter ordering as soon as
13174         * a non-zero order is defined. Otherwise, multiple loops across the result set
13175         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13176         * this needs to be contained entirely within {@link #filterResults}.
13177         */
13178        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13179
13180        @Override
13181        protected AuxiliaryResolveInfo[] newArray(int size) {
13182            return new AuxiliaryResolveInfo[size];
13183        }
13184
13185        @Override
13186        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13187            return true;
13188        }
13189
13190        @Override
13191        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13192                int userId) {
13193            if (!sUserManager.exists(userId)) {
13194                return null;
13195            }
13196            final String packageName = responseObj.resolveInfo.getPackageName();
13197            final Integer order = responseObj.getOrder();
13198            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13199                    mOrderResult.get(packageName);
13200            // ordering is enabled and this item's order isn't high enough
13201            if (lastOrderResult != null && lastOrderResult.first >= order) {
13202                return null;
13203            }
13204            final InstantAppResolveInfo res = responseObj.resolveInfo;
13205            if (order > 0) {
13206                // non-zero order, enable ordering
13207                mOrderResult.put(packageName, new Pair<>(order, res));
13208            }
13209            return responseObj;
13210        }
13211
13212        @Override
13213        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13214            // only do work if ordering is enabled [most of the time it won't be]
13215            if (mOrderResult.size() == 0) {
13216                return;
13217            }
13218            int resultSize = results.size();
13219            for (int i = 0; i < resultSize; i++) {
13220                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13221                final String packageName = info.getPackageName();
13222                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13223                if (savedInfo == null) {
13224                    // package doesn't having ordering
13225                    continue;
13226                }
13227                if (savedInfo.second == info) {
13228                    // circled back to the highest ordered item; remove from order list
13229                    mOrderResult.remove(savedInfo);
13230                    if (mOrderResult.size() == 0) {
13231                        // no more ordered items
13232                        break;
13233                    }
13234                    continue;
13235                }
13236                // item has a worse order, remove it from the result list
13237                results.remove(i);
13238                resultSize--;
13239                i--;
13240            }
13241        }
13242    }
13243
13244    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13245            new Comparator<ResolveInfo>() {
13246        public int compare(ResolveInfo r1, ResolveInfo r2) {
13247            int v1 = r1.priority;
13248            int v2 = r2.priority;
13249            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13250            if (v1 != v2) {
13251                return (v1 > v2) ? -1 : 1;
13252            }
13253            v1 = r1.preferredOrder;
13254            v2 = r2.preferredOrder;
13255            if (v1 != v2) {
13256                return (v1 > v2) ? -1 : 1;
13257            }
13258            if (r1.isDefault != r2.isDefault) {
13259                return r1.isDefault ? -1 : 1;
13260            }
13261            v1 = r1.match;
13262            v2 = r2.match;
13263            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13264            if (v1 != v2) {
13265                return (v1 > v2) ? -1 : 1;
13266            }
13267            if (r1.system != r2.system) {
13268                return r1.system ? -1 : 1;
13269            }
13270            if (r1.activityInfo != null) {
13271                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13272            }
13273            if (r1.serviceInfo != null) {
13274                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13275            }
13276            if (r1.providerInfo != null) {
13277                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13278            }
13279            return 0;
13280        }
13281    };
13282
13283    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13284            new Comparator<ProviderInfo>() {
13285        public int compare(ProviderInfo p1, ProviderInfo p2) {
13286            final int v1 = p1.initOrder;
13287            final int v2 = p2.initOrder;
13288            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13289        }
13290    };
13291
13292    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13293            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13294            final int[] userIds) {
13295        mHandler.post(new Runnable() {
13296            @Override
13297            public void run() {
13298                try {
13299                    final IActivityManager am = ActivityManager.getService();
13300                    if (am == null) return;
13301                    final int[] resolvedUserIds;
13302                    if (userIds == null) {
13303                        resolvedUserIds = am.getRunningUserIds();
13304                    } else {
13305                        resolvedUserIds = userIds;
13306                    }
13307                    for (int id : resolvedUserIds) {
13308                        final Intent intent = new Intent(action,
13309                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13310                        if (extras != null) {
13311                            intent.putExtras(extras);
13312                        }
13313                        if (targetPkg != null) {
13314                            intent.setPackage(targetPkg);
13315                        }
13316                        // Modify the UID when posting to other users
13317                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13318                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
13319                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13320                            intent.putExtra(Intent.EXTRA_UID, uid);
13321                        }
13322                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13323                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13324                        if (DEBUG_BROADCASTS) {
13325                            RuntimeException here = new RuntimeException("here");
13326                            here.fillInStackTrace();
13327                            Slog.d(TAG, "Sending to user " + id + ": "
13328                                    + intent.toShortString(false, true, false, false)
13329                                    + " " + intent.getExtras(), here);
13330                        }
13331                        am.broadcastIntent(null, intent, null, finishedReceiver,
13332                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
13333                                null, finishedReceiver != null, false, id);
13334                    }
13335                } catch (RemoteException ex) {
13336                }
13337            }
13338        });
13339    }
13340
13341    /**
13342     * Check if the external storage media is available. This is true if there
13343     * is a mounted external storage medium or if the external storage is
13344     * emulated.
13345     */
13346    private boolean isExternalMediaAvailable() {
13347        return mMediaMounted || Environment.isExternalStorageEmulated();
13348    }
13349
13350    @Override
13351    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13352        // writer
13353        synchronized (mPackages) {
13354            if (!isExternalMediaAvailable()) {
13355                // If the external storage is no longer mounted at this point,
13356                // the caller may not have been able to delete all of this
13357                // packages files and can not delete any more.  Bail.
13358                return null;
13359            }
13360            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13361            if (lastPackage != null) {
13362                pkgs.remove(lastPackage);
13363            }
13364            if (pkgs.size() > 0) {
13365                return pkgs.get(0);
13366            }
13367        }
13368        return null;
13369    }
13370
13371    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13372        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13373                userId, andCode ? 1 : 0, packageName);
13374        if (mSystemReady) {
13375            msg.sendToTarget();
13376        } else {
13377            if (mPostSystemReadyMessages == null) {
13378                mPostSystemReadyMessages = new ArrayList<>();
13379            }
13380            mPostSystemReadyMessages.add(msg);
13381        }
13382    }
13383
13384    void startCleaningPackages() {
13385        // reader
13386        if (!isExternalMediaAvailable()) {
13387            return;
13388        }
13389        synchronized (mPackages) {
13390            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13391                return;
13392            }
13393        }
13394        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13395        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13396        IActivityManager am = ActivityManager.getService();
13397        if (am != null) {
13398            int dcsUid = -1;
13399            synchronized (mPackages) {
13400                if (!mDefaultContainerWhitelisted) {
13401                    mDefaultContainerWhitelisted = true;
13402                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13403                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13404                }
13405            }
13406            try {
13407                if (dcsUid > 0) {
13408                    am.backgroundWhitelistUid(dcsUid);
13409                }
13410                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13411                        UserHandle.USER_SYSTEM);
13412            } catch (RemoteException e) {
13413            }
13414        }
13415    }
13416
13417    @Override
13418    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
13419            int installFlags, String installerPackageName, int userId) {
13420        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
13421
13422        final int callingUid = Binder.getCallingUid();
13423        enforceCrossUserPermission(callingUid, userId,
13424                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
13425
13426        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13427            try {
13428                if (observer != null) {
13429                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
13430                }
13431            } catch (RemoteException re) {
13432            }
13433            return;
13434        }
13435
13436        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
13437            installFlags |= PackageManager.INSTALL_FROM_ADB;
13438
13439        } else {
13440            // Caller holds INSTALL_PACKAGES permission, so we're less strict
13441            // about installerPackageName.
13442
13443            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
13444            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
13445        }
13446
13447        UserHandle user;
13448        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
13449            user = UserHandle.ALL;
13450        } else {
13451            user = new UserHandle(userId);
13452        }
13453
13454        // Only system components can circumvent runtime permissions when installing.
13455        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
13456                && mContext.checkCallingOrSelfPermission(Manifest.permission
13457                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
13458            throw new SecurityException("You need the "
13459                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
13460                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
13461        }
13462
13463        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
13464                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13465            throw new IllegalArgumentException(
13466                    "New installs into ASEC containers no longer supported");
13467        }
13468
13469        final File originFile = new File(originPath);
13470        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
13471
13472        final Message msg = mHandler.obtainMessage(INIT_COPY);
13473        final VerificationInfo verificationInfo = new VerificationInfo(
13474                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
13475        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
13476                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
13477                null /*packageAbiOverride*/, null /*grantedPermissions*/,
13478                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
13479        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
13480        msg.obj = params;
13481
13482        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
13483                System.identityHashCode(msg.obj));
13484        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13485                System.identityHashCode(msg.obj));
13486
13487        mHandler.sendMessage(msg);
13488    }
13489
13490
13491    /**
13492     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13493     * it is acting on behalf on an enterprise or the user).
13494     *
13495     * Note that the ordering of the conditionals in this method is important. The checks we perform
13496     * are as follows, in this order:
13497     *
13498     * 1) If the install is being performed by a system app, we can trust the app to have set the
13499     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13500     *    what it is.
13501     * 2) If the install is being performed by a device or profile owner app, the install reason
13502     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13503     *    set the install reason correctly. If the app targets an older SDK version where install
13504     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13505     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13506     * 3) In all other cases, the install is being performed by a regular app that is neither part
13507     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13508     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13509     *    set to enterprise policy and if so, change it to unknown instead.
13510     */
13511    private int fixUpInstallReason(String installerPackageName, int installerUid,
13512            int installReason) {
13513        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13514                == PERMISSION_GRANTED) {
13515            // If the install is being performed by a system app, we trust that app to have set the
13516            // install reason correctly.
13517            return installReason;
13518        }
13519
13520        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13521            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13522        if (dpm != null) {
13523            ComponentName owner = null;
13524            try {
13525                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13526                if (owner == null) {
13527                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13528                }
13529            } catch (RemoteException e) {
13530            }
13531            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13532                // If the install is being performed by a device or profile owner, the install
13533                // reason should be enterprise policy.
13534                return PackageManager.INSTALL_REASON_POLICY;
13535            }
13536        }
13537
13538        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13539            // If the install is being performed by a regular app (i.e. neither system app nor
13540            // device or profile owner), we have no reason to believe that the app is acting on
13541            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13542            // change it to unknown instead.
13543            return PackageManager.INSTALL_REASON_UNKNOWN;
13544        }
13545
13546        // If the install is being performed by a regular app and the install reason was set to any
13547        // value but enterprise policy, leave the install reason unchanged.
13548        return installReason;
13549    }
13550
13551    void installStage(String packageName, File stagedDir, String stagedCid,
13552            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13553            String installerPackageName, int installerUid, UserHandle user,
13554            Certificate[][] certificates) {
13555        if (DEBUG_EPHEMERAL) {
13556            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13557                Slog.d(TAG, "Ephemeral install of " + packageName);
13558            }
13559        }
13560        final VerificationInfo verificationInfo = new VerificationInfo(
13561                sessionParams.originatingUri, sessionParams.referrerUri,
13562                sessionParams.originatingUid, installerUid);
13563
13564        final OriginInfo origin;
13565        if (stagedDir != null) {
13566            origin = OriginInfo.fromStagedFile(stagedDir);
13567        } else {
13568            origin = OriginInfo.fromStagedContainer(stagedCid);
13569        }
13570
13571        final Message msg = mHandler.obtainMessage(INIT_COPY);
13572        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13573                sessionParams.installReason);
13574        final InstallParams params = new InstallParams(origin, null, observer,
13575                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13576                verificationInfo, user, sessionParams.abiOverride,
13577                sessionParams.grantedRuntimePermissions, certificates, installReason);
13578        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13579        msg.obj = params;
13580
13581        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13582                System.identityHashCode(msg.obj));
13583        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13584                System.identityHashCode(msg.obj));
13585
13586        mHandler.sendMessage(msg);
13587    }
13588
13589    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13590            int userId) {
13591        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13592        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13593    }
13594
13595    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
13596        if (ArrayUtils.isEmpty(userIds)) {
13597            return;
13598        }
13599        Bundle extras = new Bundle(1);
13600        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13601        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13602
13603        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13604                packageName, extras, 0, null, null, userIds);
13605        if (isSystem) {
13606            mHandler.post(() -> {
13607                        for (int userId : userIds) {
13608                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13609                        }
13610                    }
13611            );
13612        }
13613    }
13614
13615    /**
13616     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13617     * automatically without needing an explicit launch.
13618     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13619     */
13620    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13621        // If user is not running, the app didn't miss any broadcast
13622        if (!mUserManagerInternal.isUserRunning(userId)) {
13623            return;
13624        }
13625        final IActivityManager am = ActivityManager.getService();
13626        try {
13627            // Deliver LOCKED_BOOT_COMPLETED first
13628            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13629                    .setPackage(packageName);
13630            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13631            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13632                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13633
13634            // Deliver BOOT_COMPLETED only if user is unlocked
13635            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13636                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13637                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13638                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13639            }
13640        } catch (RemoteException e) {
13641            throw e.rethrowFromSystemServer();
13642        }
13643    }
13644
13645    @Override
13646    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13647            int userId) {
13648        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13649        PackageSetting pkgSetting;
13650        final int uid = Binder.getCallingUid();
13651        enforceCrossUserPermission(uid, userId,
13652                true /* requireFullPermission */, true /* checkShell */,
13653                "setApplicationHiddenSetting for user " + userId);
13654
13655        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13656            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13657            return false;
13658        }
13659
13660        long callingId = Binder.clearCallingIdentity();
13661        try {
13662            boolean sendAdded = false;
13663            boolean sendRemoved = false;
13664            // writer
13665            synchronized (mPackages) {
13666                pkgSetting = mSettings.mPackages.get(packageName);
13667                if (pkgSetting == null) {
13668                    return false;
13669                }
13670                // Do not allow "android" is being disabled
13671                if ("android".equals(packageName)) {
13672                    Slog.w(TAG, "Cannot hide package: android");
13673                    return false;
13674                }
13675                // Cannot hide static shared libs as they are considered
13676                // a part of the using app (emulating static linking). Also
13677                // static libs are installed always on internal storage.
13678                PackageParser.Package pkg = mPackages.get(packageName);
13679                if (pkg != null && pkg.staticSharedLibName != null) {
13680                    Slog.w(TAG, "Cannot hide package: " + packageName
13681                            + " providing static shared library: "
13682                            + pkg.staticSharedLibName);
13683                    return false;
13684                }
13685                // Only allow protected packages to hide themselves.
13686                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13687                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13688                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13689                    return false;
13690                }
13691
13692                if (pkgSetting.getHidden(userId) != hidden) {
13693                    pkgSetting.setHidden(hidden, userId);
13694                    mSettings.writePackageRestrictionsLPr(userId);
13695                    if (hidden) {
13696                        sendRemoved = true;
13697                    } else {
13698                        sendAdded = true;
13699                    }
13700                }
13701            }
13702            if (sendAdded) {
13703                sendPackageAddedForUser(packageName, pkgSetting, userId);
13704                return true;
13705            }
13706            if (sendRemoved) {
13707                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13708                        "hiding pkg");
13709                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13710                return true;
13711            }
13712        } finally {
13713            Binder.restoreCallingIdentity(callingId);
13714        }
13715        return false;
13716    }
13717
13718    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13719            int userId) {
13720        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13721        info.removedPackage = packageName;
13722        info.installerPackageName = pkgSetting.installerPackageName;
13723        info.removedUsers = new int[] {userId};
13724        info.broadcastUsers = new int[] {userId};
13725        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13726        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13727    }
13728
13729    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13730        if (pkgList.length > 0) {
13731            Bundle extras = new Bundle(1);
13732            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13733
13734            sendPackageBroadcast(
13735                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13736                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13737                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13738                    new int[] {userId});
13739        }
13740    }
13741
13742    /**
13743     * Returns true if application is not found or there was an error. Otherwise it returns
13744     * the hidden state of the package for the given user.
13745     */
13746    @Override
13747    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13748        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13749        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13750                true /* requireFullPermission */, false /* checkShell */,
13751                "getApplicationHidden for user " + userId);
13752        PackageSetting pkgSetting;
13753        long callingId = Binder.clearCallingIdentity();
13754        try {
13755            // writer
13756            synchronized (mPackages) {
13757                pkgSetting = mSettings.mPackages.get(packageName);
13758                if (pkgSetting == null) {
13759                    return true;
13760                }
13761                return pkgSetting.getHidden(userId);
13762            }
13763        } finally {
13764            Binder.restoreCallingIdentity(callingId);
13765        }
13766    }
13767
13768    /**
13769     * @hide
13770     */
13771    @Override
13772    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13773            int installReason) {
13774        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13775                null);
13776        PackageSetting pkgSetting;
13777        final int uid = Binder.getCallingUid();
13778        enforceCrossUserPermission(uid, userId,
13779                true /* requireFullPermission */, true /* checkShell */,
13780                "installExistingPackage for user " + userId);
13781        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13782            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13783        }
13784
13785        long callingId = Binder.clearCallingIdentity();
13786        try {
13787            boolean installed = false;
13788            final boolean instantApp =
13789                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13790            final boolean fullApp =
13791                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13792
13793            // writer
13794            synchronized (mPackages) {
13795                pkgSetting = mSettings.mPackages.get(packageName);
13796                if (pkgSetting == null) {
13797                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13798                }
13799                if (!pkgSetting.getInstalled(userId)) {
13800                    pkgSetting.setInstalled(true, userId);
13801                    pkgSetting.setHidden(false, userId);
13802                    pkgSetting.setInstallReason(installReason, userId);
13803                    mSettings.writePackageRestrictionsLPr(userId);
13804                    mSettings.writeKernelMappingLPr(pkgSetting);
13805                    installed = true;
13806                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13807                    // upgrade app from instant to full; we don't allow app downgrade
13808                    installed = true;
13809                }
13810                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13811            }
13812
13813            if (installed) {
13814                if (pkgSetting.pkg != null) {
13815                    synchronized (mInstallLock) {
13816                        // We don't need to freeze for a brand new install
13817                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13818                    }
13819                }
13820                sendPackageAddedForUser(packageName, pkgSetting, userId);
13821                synchronized (mPackages) {
13822                    updateSequenceNumberLP(packageName, new int[]{ userId });
13823                }
13824            }
13825        } finally {
13826            Binder.restoreCallingIdentity(callingId);
13827        }
13828
13829        return PackageManager.INSTALL_SUCCEEDED;
13830    }
13831
13832    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13833            boolean instantApp, boolean fullApp) {
13834        // no state specified; do nothing
13835        if (!instantApp && !fullApp) {
13836            return;
13837        }
13838        if (userId != UserHandle.USER_ALL) {
13839            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13840                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13841            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13842                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13843            }
13844        } else {
13845            for (int currentUserId : sUserManager.getUserIds()) {
13846                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13847                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13848                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13849                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13850                }
13851            }
13852        }
13853    }
13854
13855    boolean isUserRestricted(int userId, String restrictionKey) {
13856        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13857        if (restrictions.getBoolean(restrictionKey, false)) {
13858            Log.w(TAG, "User is restricted: " + restrictionKey);
13859            return true;
13860        }
13861        return false;
13862    }
13863
13864    @Override
13865    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13866            int userId) {
13867        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13868        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13869                true /* requireFullPermission */, true /* checkShell */,
13870                "setPackagesSuspended for user " + userId);
13871
13872        if (ArrayUtils.isEmpty(packageNames)) {
13873            return packageNames;
13874        }
13875
13876        // List of package names for whom the suspended state has changed.
13877        List<String> changedPackages = new ArrayList<>(packageNames.length);
13878        // List of package names for whom the suspended state is not set as requested in this
13879        // method.
13880        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13881        long callingId = Binder.clearCallingIdentity();
13882        try {
13883            for (int i = 0; i < packageNames.length; i++) {
13884                String packageName = packageNames[i];
13885                boolean changed = false;
13886                final int appId;
13887                synchronized (mPackages) {
13888                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13889                    if (pkgSetting == null) {
13890                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13891                                + "\". Skipping suspending/un-suspending.");
13892                        unactionedPackages.add(packageName);
13893                        continue;
13894                    }
13895                    appId = pkgSetting.appId;
13896                    if (pkgSetting.getSuspended(userId) != suspended) {
13897                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13898                            unactionedPackages.add(packageName);
13899                            continue;
13900                        }
13901                        pkgSetting.setSuspended(suspended, userId);
13902                        mSettings.writePackageRestrictionsLPr(userId);
13903                        changed = true;
13904                        changedPackages.add(packageName);
13905                    }
13906                }
13907
13908                if (changed && suspended) {
13909                    killApplication(packageName, UserHandle.getUid(userId, appId),
13910                            "suspending package");
13911                }
13912            }
13913        } finally {
13914            Binder.restoreCallingIdentity(callingId);
13915        }
13916
13917        if (!changedPackages.isEmpty()) {
13918            sendPackagesSuspendedForUser(changedPackages.toArray(
13919                    new String[changedPackages.size()]), userId, suspended);
13920        }
13921
13922        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13923    }
13924
13925    @Override
13926    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13927        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13928                true /* requireFullPermission */, false /* checkShell */,
13929                "isPackageSuspendedForUser for user " + userId);
13930        synchronized (mPackages) {
13931            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13932            if (pkgSetting == null) {
13933                throw new IllegalArgumentException("Unknown target package: " + packageName);
13934            }
13935            return pkgSetting.getSuspended(userId);
13936        }
13937    }
13938
13939    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13940        if (isPackageDeviceAdmin(packageName, userId)) {
13941            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13942                    + "\": has an active device admin");
13943            return false;
13944        }
13945
13946        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13947        if (packageName.equals(activeLauncherPackageName)) {
13948            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13949                    + "\": contains the active launcher");
13950            return false;
13951        }
13952
13953        if (packageName.equals(mRequiredInstallerPackage)) {
13954            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13955                    + "\": required for package installation");
13956            return false;
13957        }
13958
13959        if (packageName.equals(mRequiredUninstallerPackage)) {
13960            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13961                    + "\": required for package uninstallation");
13962            return false;
13963        }
13964
13965        if (packageName.equals(mRequiredVerifierPackage)) {
13966            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13967                    + "\": required for package verification");
13968            return false;
13969        }
13970
13971        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13972            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13973                    + "\": is the default dialer");
13974            return false;
13975        }
13976
13977        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13978            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13979                    + "\": protected package");
13980            return false;
13981        }
13982
13983        // Cannot suspend static shared libs as they are considered
13984        // a part of the using app (emulating static linking). Also
13985        // static libs are installed always on internal storage.
13986        PackageParser.Package pkg = mPackages.get(packageName);
13987        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13988            Slog.w(TAG, "Cannot suspend package: " + packageName
13989                    + " providing static shared library: "
13990                    + pkg.staticSharedLibName);
13991            return false;
13992        }
13993
13994        return true;
13995    }
13996
13997    private String getActiveLauncherPackageName(int userId) {
13998        Intent intent = new Intent(Intent.ACTION_MAIN);
13999        intent.addCategory(Intent.CATEGORY_HOME);
14000        ResolveInfo resolveInfo = resolveIntent(
14001                intent,
14002                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14003                PackageManager.MATCH_DEFAULT_ONLY,
14004                userId);
14005
14006        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14007    }
14008
14009    private String getDefaultDialerPackageName(int userId) {
14010        synchronized (mPackages) {
14011            return mSettings.getDefaultDialerPackageNameLPw(userId);
14012        }
14013    }
14014
14015    @Override
14016    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14017        mContext.enforceCallingOrSelfPermission(
14018                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14019                "Only package verification agents can verify applications");
14020
14021        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14022        final PackageVerificationResponse response = new PackageVerificationResponse(
14023                verificationCode, Binder.getCallingUid());
14024        msg.arg1 = id;
14025        msg.obj = response;
14026        mHandler.sendMessage(msg);
14027    }
14028
14029    @Override
14030    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14031            long millisecondsToDelay) {
14032        mContext.enforceCallingOrSelfPermission(
14033                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14034                "Only package verification agents can extend verification timeouts");
14035
14036        final PackageVerificationState state = mPendingVerification.get(id);
14037        final PackageVerificationResponse response = new PackageVerificationResponse(
14038                verificationCodeAtTimeout, Binder.getCallingUid());
14039
14040        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14041            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14042        }
14043        if (millisecondsToDelay < 0) {
14044            millisecondsToDelay = 0;
14045        }
14046        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14047                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14048            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14049        }
14050
14051        if ((state != null) && !state.timeoutExtended()) {
14052            state.extendTimeout();
14053
14054            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14055            msg.arg1 = id;
14056            msg.obj = response;
14057            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14058        }
14059    }
14060
14061    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14062            int verificationCode, UserHandle user) {
14063        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14064        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14065        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14066        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14067        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14068
14069        mContext.sendBroadcastAsUser(intent, user,
14070                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14071    }
14072
14073    private ComponentName matchComponentForVerifier(String packageName,
14074            List<ResolveInfo> receivers) {
14075        ActivityInfo targetReceiver = null;
14076
14077        final int NR = receivers.size();
14078        for (int i = 0; i < NR; i++) {
14079            final ResolveInfo info = receivers.get(i);
14080            if (info.activityInfo == null) {
14081                continue;
14082            }
14083
14084            if (packageName.equals(info.activityInfo.packageName)) {
14085                targetReceiver = info.activityInfo;
14086                break;
14087            }
14088        }
14089
14090        if (targetReceiver == null) {
14091            return null;
14092        }
14093
14094        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14095    }
14096
14097    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14098            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14099        if (pkgInfo.verifiers.length == 0) {
14100            return null;
14101        }
14102
14103        final int N = pkgInfo.verifiers.length;
14104        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14105        for (int i = 0; i < N; i++) {
14106            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14107
14108            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14109                    receivers);
14110            if (comp == null) {
14111                continue;
14112            }
14113
14114            final int verifierUid = getUidForVerifier(verifierInfo);
14115            if (verifierUid == -1) {
14116                continue;
14117            }
14118
14119            if (DEBUG_VERIFY) {
14120                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14121                        + " with the correct signature");
14122            }
14123            sufficientVerifiers.add(comp);
14124            verificationState.addSufficientVerifier(verifierUid);
14125        }
14126
14127        return sufficientVerifiers;
14128    }
14129
14130    private int getUidForVerifier(VerifierInfo verifierInfo) {
14131        synchronized (mPackages) {
14132            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14133            if (pkg == null) {
14134                return -1;
14135            } else if (pkg.mSignatures.length != 1) {
14136                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14137                        + " has more than one signature; ignoring");
14138                return -1;
14139            }
14140
14141            /*
14142             * If the public key of the package's signature does not match
14143             * our expected public key, then this is a different package and
14144             * we should skip.
14145             */
14146
14147            final byte[] expectedPublicKey;
14148            try {
14149                final Signature verifierSig = pkg.mSignatures[0];
14150                final PublicKey publicKey = verifierSig.getPublicKey();
14151                expectedPublicKey = publicKey.getEncoded();
14152            } catch (CertificateException e) {
14153                return -1;
14154            }
14155
14156            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14157
14158            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14159                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14160                        + " does not have the expected public key; ignoring");
14161                return -1;
14162            }
14163
14164            return pkg.applicationInfo.uid;
14165        }
14166    }
14167
14168    @Override
14169    public void finishPackageInstall(int token, boolean didLaunch) {
14170        enforceSystemOrRoot("Only the system is allowed to finish installs");
14171
14172        if (DEBUG_INSTALL) {
14173            Slog.v(TAG, "BM finishing package install for " + token);
14174        }
14175        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14176
14177        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14178        mHandler.sendMessage(msg);
14179    }
14180
14181    /**
14182     * Get the verification agent timeout.  Used for both the APK verifier and the
14183     * intent filter verifier.
14184     *
14185     * @return verification timeout in milliseconds
14186     */
14187    private long getVerificationTimeout() {
14188        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14189                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14190                DEFAULT_VERIFICATION_TIMEOUT);
14191    }
14192
14193    /**
14194     * Get the default verification agent response code.
14195     *
14196     * @return default verification response code
14197     */
14198    private int getDefaultVerificationResponse() {
14199        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14200                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14201                DEFAULT_VERIFICATION_RESPONSE);
14202    }
14203
14204    /**
14205     * Check whether or not package verification has been enabled.
14206     *
14207     * @return true if verification should be performed
14208     */
14209    private boolean isVerificationEnabled(int userId, int installFlags) {
14210        if (!DEFAULT_VERIFY_ENABLE) {
14211            return false;
14212        }
14213
14214        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14215
14216        // Check if installing from ADB
14217        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14218            // Do not run verification in a test harness environment
14219            if (ActivityManager.isRunningInTestHarness()) {
14220                return false;
14221            }
14222            if (ensureVerifyAppsEnabled) {
14223                return true;
14224            }
14225            // Check if the developer does not want package verification for ADB installs
14226            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14227                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14228                return false;
14229            }
14230        }
14231
14232        if (ensureVerifyAppsEnabled) {
14233            return true;
14234        }
14235
14236        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14237                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14238    }
14239
14240    @Override
14241    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14242            throws RemoteException {
14243        mContext.enforceCallingOrSelfPermission(
14244                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14245                "Only intentfilter verification agents can verify applications");
14246
14247        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14248        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14249                Binder.getCallingUid(), verificationCode, failedDomains);
14250        msg.arg1 = id;
14251        msg.obj = response;
14252        mHandler.sendMessage(msg);
14253    }
14254
14255    @Override
14256    public int getIntentVerificationStatus(String packageName, int userId) {
14257        synchronized (mPackages) {
14258            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14259        }
14260    }
14261
14262    @Override
14263    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14264        mContext.enforceCallingOrSelfPermission(
14265                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14266
14267        boolean result = false;
14268        synchronized (mPackages) {
14269            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14270        }
14271        if (result) {
14272            scheduleWritePackageRestrictionsLocked(userId);
14273        }
14274        return result;
14275    }
14276
14277    @Override
14278    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14279            String packageName) {
14280        synchronized (mPackages) {
14281            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14282        }
14283    }
14284
14285    @Override
14286    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14287        if (TextUtils.isEmpty(packageName)) {
14288            return ParceledListSlice.emptyList();
14289        }
14290        synchronized (mPackages) {
14291            PackageParser.Package pkg = mPackages.get(packageName);
14292            if (pkg == null || pkg.activities == null) {
14293                return ParceledListSlice.emptyList();
14294            }
14295            final int count = pkg.activities.size();
14296            ArrayList<IntentFilter> result = new ArrayList<>();
14297            for (int n=0; n<count; n++) {
14298                PackageParser.Activity activity = pkg.activities.get(n);
14299                if (activity.intents != null && activity.intents.size() > 0) {
14300                    result.addAll(activity.intents);
14301                }
14302            }
14303            return new ParceledListSlice<>(result);
14304        }
14305    }
14306
14307    @Override
14308    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14309        mContext.enforceCallingOrSelfPermission(
14310                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14311
14312        synchronized (mPackages) {
14313            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14314            if (packageName != null) {
14315                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
14316                        packageName, userId);
14317            }
14318            return result;
14319        }
14320    }
14321
14322    @Override
14323    public String getDefaultBrowserPackageName(int userId) {
14324        synchronized (mPackages) {
14325            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14326        }
14327    }
14328
14329    /**
14330     * Get the "allow unknown sources" setting.
14331     *
14332     * @return the current "allow unknown sources" setting
14333     */
14334    private int getUnknownSourcesSettings() {
14335        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14336                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14337                -1);
14338    }
14339
14340    @Override
14341    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14342        final int uid = Binder.getCallingUid();
14343        // writer
14344        synchronized (mPackages) {
14345            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14346            if (targetPackageSetting == null) {
14347                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14348            }
14349
14350            PackageSetting installerPackageSetting;
14351            if (installerPackageName != null) {
14352                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14353                if (installerPackageSetting == null) {
14354                    throw new IllegalArgumentException("Unknown installer package: "
14355                            + installerPackageName);
14356                }
14357            } else {
14358                installerPackageSetting = null;
14359            }
14360
14361            Signature[] callerSignature;
14362            Object obj = mSettings.getUserIdLPr(uid);
14363            if (obj != null) {
14364                if (obj instanceof SharedUserSetting) {
14365                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
14366                } else if (obj instanceof PackageSetting) {
14367                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
14368                } else {
14369                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
14370                }
14371            } else {
14372                throw new SecurityException("Unknown calling UID: " + uid);
14373            }
14374
14375            // Verify: can't set installerPackageName to a package that is
14376            // not signed with the same cert as the caller.
14377            if (installerPackageSetting != null) {
14378                if (compareSignatures(callerSignature,
14379                        installerPackageSetting.signatures.mSignatures)
14380                        != PackageManager.SIGNATURE_MATCH) {
14381                    throw new SecurityException(
14382                            "Caller does not have same cert as new installer package "
14383                            + installerPackageName);
14384                }
14385            }
14386
14387            // Verify: if target already has an installer package, it must
14388            // be signed with the same cert as the caller.
14389            if (targetPackageSetting.installerPackageName != null) {
14390                PackageSetting setting = mSettings.mPackages.get(
14391                        targetPackageSetting.installerPackageName);
14392                // If the currently set package isn't valid, then it's always
14393                // okay to change it.
14394                if (setting != null) {
14395                    if (compareSignatures(callerSignature,
14396                            setting.signatures.mSignatures)
14397                            != PackageManager.SIGNATURE_MATCH) {
14398                        throw new SecurityException(
14399                                "Caller does not have same cert as old installer package "
14400                                + targetPackageSetting.installerPackageName);
14401                    }
14402                }
14403            }
14404
14405            // Okay!
14406            targetPackageSetting.installerPackageName = installerPackageName;
14407            if (installerPackageName != null) {
14408                mSettings.mInstallerPackages.add(installerPackageName);
14409            }
14410            scheduleWriteSettingsLocked();
14411        }
14412    }
14413
14414    @Override
14415    public void setApplicationCategoryHint(String packageName, int categoryHint,
14416            String callerPackageName) {
14417        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14418                callerPackageName);
14419        synchronized (mPackages) {
14420            PackageSetting ps = mSettings.mPackages.get(packageName);
14421            if (ps == null) {
14422                throw new IllegalArgumentException("Unknown target package " + packageName);
14423            }
14424
14425            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14426                throw new IllegalArgumentException("Calling package " + callerPackageName
14427                        + " is not installer for " + packageName);
14428            }
14429
14430            if (ps.categoryHint != categoryHint) {
14431                ps.categoryHint = categoryHint;
14432                scheduleWriteSettingsLocked();
14433            }
14434        }
14435    }
14436
14437    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14438        // Queue up an async operation since the package installation may take a little while.
14439        mHandler.post(new Runnable() {
14440            public void run() {
14441                mHandler.removeCallbacks(this);
14442                 // Result object to be returned
14443                PackageInstalledInfo res = new PackageInstalledInfo();
14444                res.setReturnCode(currentStatus);
14445                res.uid = -1;
14446                res.pkg = null;
14447                res.removedInfo = null;
14448                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14449                    args.doPreInstall(res.returnCode);
14450                    synchronized (mInstallLock) {
14451                        installPackageTracedLI(args, res);
14452                    }
14453                    args.doPostInstall(res.returnCode, res.uid);
14454                }
14455
14456                // A restore should be performed at this point if (a) the install
14457                // succeeded, (b) the operation is not an update, and (c) the new
14458                // package has not opted out of backup participation.
14459                final boolean update = res.removedInfo != null
14460                        && res.removedInfo.removedPackage != null;
14461                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14462                boolean doRestore = !update
14463                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14464
14465                // Set up the post-install work request bookkeeping.  This will be used
14466                // and cleaned up by the post-install event handling regardless of whether
14467                // there's a restore pass performed.  Token values are >= 1.
14468                int token;
14469                if (mNextInstallToken < 0) mNextInstallToken = 1;
14470                token = mNextInstallToken++;
14471
14472                PostInstallData data = new PostInstallData(args, res);
14473                mRunningInstalls.put(token, data);
14474                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14475
14476                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14477                    // Pass responsibility to the Backup Manager.  It will perform a
14478                    // restore if appropriate, then pass responsibility back to the
14479                    // Package Manager to run the post-install observer callbacks
14480                    // and broadcasts.
14481                    IBackupManager bm = IBackupManager.Stub.asInterface(
14482                            ServiceManager.getService(Context.BACKUP_SERVICE));
14483                    if (bm != null) {
14484                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14485                                + " to BM for possible restore");
14486                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14487                        try {
14488                            // TODO: http://b/22388012
14489                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14490                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14491                            } else {
14492                                doRestore = false;
14493                            }
14494                        } catch (RemoteException e) {
14495                            // can't happen; the backup manager is local
14496                        } catch (Exception e) {
14497                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14498                            doRestore = false;
14499                        }
14500                    } else {
14501                        Slog.e(TAG, "Backup Manager not found!");
14502                        doRestore = false;
14503                    }
14504                }
14505
14506                if (!doRestore) {
14507                    // No restore possible, or the Backup Manager was mysteriously not
14508                    // available -- just fire the post-install work request directly.
14509                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14510
14511                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14512
14513                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14514                    mHandler.sendMessage(msg);
14515                }
14516            }
14517        });
14518    }
14519
14520    /**
14521     * Callback from PackageSettings whenever an app is first transitioned out of the
14522     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14523     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14524     * here whether the app is the target of an ongoing install, and only send the
14525     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14526     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14527     * handling.
14528     */
14529    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14530        // Serialize this with the rest of the install-process message chain.  In the
14531        // restore-at-install case, this Runnable will necessarily run before the
14532        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14533        // are coherent.  In the non-restore case, the app has already completed install
14534        // and been launched through some other means, so it is not in a problematic
14535        // state for observers to see the FIRST_LAUNCH signal.
14536        mHandler.post(new Runnable() {
14537            @Override
14538            public void run() {
14539                for (int i = 0; i < mRunningInstalls.size(); i++) {
14540                    final PostInstallData data = mRunningInstalls.valueAt(i);
14541                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14542                        continue;
14543                    }
14544                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14545                        // right package; but is it for the right user?
14546                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14547                            if (userId == data.res.newUsers[uIndex]) {
14548                                if (DEBUG_BACKUP) {
14549                                    Slog.i(TAG, "Package " + pkgName
14550                                            + " being restored so deferring FIRST_LAUNCH");
14551                                }
14552                                return;
14553                            }
14554                        }
14555                    }
14556                }
14557                // didn't find it, so not being restored
14558                if (DEBUG_BACKUP) {
14559                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14560                }
14561                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14562            }
14563        });
14564    }
14565
14566    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14567        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14568                installerPkg, null, userIds);
14569    }
14570
14571    private abstract class HandlerParams {
14572        private static final int MAX_RETRIES = 4;
14573
14574        /**
14575         * Number of times startCopy() has been attempted and had a non-fatal
14576         * error.
14577         */
14578        private int mRetries = 0;
14579
14580        /** User handle for the user requesting the information or installation. */
14581        private final UserHandle mUser;
14582        String traceMethod;
14583        int traceCookie;
14584
14585        HandlerParams(UserHandle user) {
14586            mUser = user;
14587        }
14588
14589        UserHandle getUser() {
14590            return mUser;
14591        }
14592
14593        HandlerParams setTraceMethod(String traceMethod) {
14594            this.traceMethod = traceMethod;
14595            return this;
14596        }
14597
14598        HandlerParams setTraceCookie(int traceCookie) {
14599            this.traceCookie = traceCookie;
14600            return this;
14601        }
14602
14603        final boolean startCopy() {
14604            boolean res;
14605            try {
14606                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14607
14608                if (++mRetries > MAX_RETRIES) {
14609                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14610                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14611                    handleServiceError();
14612                    return false;
14613                } else {
14614                    handleStartCopy();
14615                    res = true;
14616                }
14617            } catch (RemoteException e) {
14618                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14619                mHandler.sendEmptyMessage(MCS_RECONNECT);
14620                res = false;
14621            }
14622            handleReturnCode();
14623            return res;
14624        }
14625
14626        final void serviceError() {
14627            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14628            handleServiceError();
14629            handleReturnCode();
14630        }
14631
14632        abstract void handleStartCopy() throws RemoteException;
14633        abstract void handleServiceError();
14634        abstract void handleReturnCode();
14635    }
14636
14637    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14638        for (File path : paths) {
14639            try {
14640                mcs.clearDirectory(path.getAbsolutePath());
14641            } catch (RemoteException e) {
14642            }
14643        }
14644    }
14645
14646    static class OriginInfo {
14647        /**
14648         * Location where install is coming from, before it has been
14649         * copied/renamed into place. This could be a single monolithic APK
14650         * file, or a cluster directory. This location may be untrusted.
14651         */
14652        final File file;
14653        final String cid;
14654
14655        /**
14656         * Flag indicating that {@link #file} or {@link #cid} has already been
14657         * staged, meaning downstream users don't need to defensively copy the
14658         * contents.
14659         */
14660        final boolean staged;
14661
14662        /**
14663         * Flag indicating that {@link #file} or {@link #cid} is an already
14664         * installed app that is being moved.
14665         */
14666        final boolean existing;
14667
14668        final String resolvedPath;
14669        final File resolvedFile;
14670
14671        static OriginInfo fromNothing() {
14672            return new OriginInfo(null, null, false, false);
14673        }
14674
14675        static OriginInfo fromUntrustedFile(File file) {
14676            return new OriginInfo(file, null, false, false);
14677        }
14678
14679        static OriginInfo fromExistingFile(File file) {
14680            return new OriginInfo(file, null, false, true);
14681        }
14682
14683        static OriginInfo fromStagedFile(File file) {
14684            return new OriginInfo(file, null, true, false);
14685        }
14686
14687        static OriginInfo fromStagedContainer(String cid) {
14688            return new OriginInfo(null, cid, true, false);
14689        }
14690
14691        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14692            this.file = file;
14693            this.cid = cid;
14694            this.staged = staged;
14695            this.existing = existing;
14696
14697            if (cid != null) {
14698                resolvedPath = PackageHelper.getSdDir(cid);
14699                resolvedFile = new File(resolvedPath);
14700            } else if (file != null) {
14701                resolvedPath = file.getAbsolutePath();
14702                resolvedFile = file;
14703            } else {
14704                resolvedPath = null;
14705                resolvedFile = null;
14706            }
14707        }
14708    }
14709
14710    static class MoveInfo {
14711        final int moveId;
14712        final String fromUuid;
14713        final String toUuid;
14714        final String packageName;
14715        final String dataAppName;
14716        final int appId;
14717        final String seinfo;
14718        final int targetSdkVersion;
14719
14720        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14721                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14722            this.moveId = moveId;
14723            this.fromUuid = fromUuid;
14724            this.toUuid = toUuid;
14725            this.packageName = packageName;
14726            this.dataAppName = dataAppName;
14727            this.appId = appId;
14728            this.seinfo = seinfo;
14729            this.targetSdkVersion = targetSdkVersion;
14730        }
14731    }
14732
14733    static class VerificationInfo {
14734        /** A constant used to indicate that a uid value is not present. */
14735        public static final int NO_UID = -1;
14736
14737        /** URI referencing where the package was downloaded from. */
14738        final Uri originatingUri;
14739
14740        /** HTTP referrer URI associated with the originatingURI. */
14741        final Uri referrer;
14742
14743        /** UID of the application that the install request originated from. */
14744        final int originatingUid;
14745
14746        /** UID of application requesting the install */
14747        final int installerUid;
14748
14749        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14750            this.originatingUri = originatingUri;
14751            this.referrer = referrer;
14752            this.originatingUid = originatingUid;
14753            this.installerUid = installerUid;
14754        }
14755    }
14756
14757    class InstallParams extends HandlerParams {
14758        final OriginInfo origin;
14759        final MoveInfo move;
14760        final IPackageInstallObserver2 observer;
14761        int installFlags;
14762        final String installerPackageName;
14763        final String volumeUuid;
14764        private InstallArgs mArgs;
14765        private int mRet;
14766        final String packageAbiOverride;
14767        final String[] grantedRuntimePermissions;
14768        final VerificationInfo verificationInfo;
14769        final Certificate[][] certificates;
14770        final int installReason;
14771
14772        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14773                int installFlags, String installerPackageName, String volumeUuid,
14774                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14775                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14776            super(user);
14777            this.origin = origin;
14778            this.move = move;
14779            this.observer = observer;
14780            this.installFlags = installFlags;
14781            this.installerPackageName = installerPackageName;
14782            this.volumeUuid = volumeUuid;
14783            this.verificationInfo = verificationInfo;
14784            this.packageAbiOverride = packageAbiOverride;
14785            this.grantedRuntimePermissions = grantedPermissions;
14786            this.certificates = certificates;
14787            this.installReason = installReason;
14788        }
14789
14790        @Override
14791        public String toString() {
14792            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14793                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14794        }
14795
14796        private int installLocationPolicy(PackageInfoLite pkgLite) {
14797            String packageName = pkgLite.packageName;
14798            int installLocation = pkgLite.installLocation;
14799            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14800            // reader
14801            synchronized (mPackages) {
14802                // Currently installed package which the new package is attempting to replace or
14803                // null if no such package is installed.
14804                PackageParser.Package installedPkg = mPackages.get(packageName);
14805                // Package which currently owns the data which the new package will own if installed.
14806                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14807                // will be null whereas dataOwnerPkg will contain information about the package
14808                // which was uninstalled while keeping its data.
14809                PackageParser.Package dataOwnerPkg = installedPkg;
14810                if (dataOwnerPkg  == null) {
14811                    PackageSetting ps = mSettings.mPackages.get(packageName);
14812                    if (ps != null) {
14813                        dataOwnerPkg = ps.pkg;
14814                    }
14815                }
14816
14817                if (dataOwnerPkg != null) {
14818                    // If installed, the package will get access to data left on the device by its
14819                    // predecessor. As a security measure, this is permited only if this is not a
14820                    // version downgrade or if the predecessor package is marked as debuggable and
14821                    // a downgrade is explicitly requested.
14822                    //
14823                    // On debuggable platform builds, downgrades are permitted even for
14824                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14825                    // not offer security guarantees and thus it's OK to disable some security
14826                    // mechanisms to make debugging/testing easier on those builds. However, even on
14827                    // debuggable builds downgrades of packages are permitted only if requested via
14828                    // installFlags. This is because we aim to keep the behavior of debuggable
14829                    // platform builds as close as possible to the behavior of non-debuggable
14830                    // platform builds.
14831                    final boolean downgradeRequested =
14832                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14833                    final boolean packageDebuggable =
14834                                (dataOwnerPkg.applicationInfo.flags
14835                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14836                    final boolean downgradePermitted =
14837                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14838                    if (!downgradePermitted) {
14839                        try {
14840                            checkDowngrade(dataOwnerPkg, pkgLite);
14841                        } catch (PackageManagerException e) {
14842                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14843                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14844                        }
14845                    }
14846                }
14847
14848                if (installedPkg != null) {
14849                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14850                        // Check for updated system application.
14851                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14852                            if (onSd) {
14853                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14854                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14855                            }
14856                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14857                        } else {
14858                            if (onSd) {
14859                                // Install flag overrides everything.
14860                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14861                            }
14862                            // If current upgrade specifies particular preference
14863                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14864                                // Application explicitly specified internal.
14865                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14866                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14867                                // App explictly prefers external. Let policy decide
14868                            } else {
14869                                // Prefer previous location
14870                                if (isExternal(installedPkg)) {
14871                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14872                                }
14873                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14874                            }
14875                        }
14876                    } else {
14877                        // Invalid install. Return error code
14878                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14879                    }
14880                }
14881            }
14882            // All the special cases have been taken care of.
14883            // Return result based on recommended install location.
14884            if (onSd) {
14885                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14886            }
14887            return pkgLite.recommendedInstallLocation;
14888        }
14889
14890        /*
14891         * Invoke remote method to get package information and install
14892         * location values. Override install location based on default
14893         * policy if needed and then create install arguments based
14894         * on the install location.
14895         */
14896        public void handleStartCopy() throws RemoteException {
14897            int ret = PackageManager.INSTALL_SUCCEEDED;
14898
14899            // If we're already staged, we've firmly committed to an install location
14900            if (origin.staged) {
14901                if (origin.file != null) {
14902                    installFlags |= PackageManager.INSTALL_INTERNAL;
14903                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14904                } else if (origin.cid != null) {
14905                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14906                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14907                } else {
14908                    throw new IllegalStateException("Invalid stage location");
14909                }
14910            }
14911
14912            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14913            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14914            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14915            PackageInfoLite pkgLite = null;
14916
14917            if (onInt && onSd) {
14918                // Check if both bits are set.
14919                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14920                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14921            } else if (onSd && ephemeral) {
14922                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14923                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14924            } else {
14925                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14926                        packageAbiOverride);
14927
14928                if (DEBUG_EPHEMERAL && ephemeral) {
14929                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14930                }
14931
14932                /*
14933                 * If we have too little free space, try to free cache
14934                 * before giving up.
14935                 */
14936                if (!origin.staged && pkgLite.recommendedInstallLocation
14937                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14938                    // TODO: focus freeing disk space on the target device
14939                    final StorageManager storage = StorageManager.from(mContext);
14940                    final long lowThreshold = storage.getStorageLowBytes(
14941                            Environment.getDataDirectory());
14942
14943                    final long sizeBytes = mContainerService.calculateInstalledSize(
14944                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14945
14946                    try {
14947                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14948                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14949                                installFlags, packageAbiOverride);
14950                    } catch (InstallerException e) {
14951                        Slog.w(TAG, "Failed to free cache", e);
14952                    }
14953
14954                    /*
14955                     * The cache free must have deleted the file we
14956                     * downloaded to install.
14957                     *
14958                     * TODO: fix the "freeCache" call to not delete
14959                     *       the file we care about.
14960                     */
14961                    if (pkgLite.recommendedInstallLocation
14962                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14963                        pkgLite.recommendedInstallLocation
14964                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14965                    }
14966                }
14967            }
14968
14969            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14970                int loc = pkgLite.recommendedInstallLocation;
14971                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14972                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14973                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14974                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14975                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14976                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14977                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14978                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14979                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14980                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14981                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14982                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14983                } else {
14984                    // Override with defaults if needed.
14985                    loc = installLocationPolicy(pkgLite);
14986                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14987                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14988                    } else if (!onSd && !onInt) {
14989                        // Override install location with flags
14990                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14991                            // Set the flag to install on external media.
14992                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14993                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14994                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14995                            if (DEBUG_EPHEMERAL) {
14996                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14997                            }
14998                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14999                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15000                                    |PackageManager.INSTALL_INTERNAL);
15001                        } else {
15002                            // Make sure the flag for installing on external
15003                            // media is unset
15004                            installFlags |= PackageManager.INSTALL_INTERNAL;
15005                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15006                        }
15007                    }
15008                }
15009            }
15010
15011            final InstallArgs args = createInstallArgs(this);
15012            mArgs = args;
15013
15014            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15015                // TODO: http://b/22976637
15016                // Apps installed for "all" users use the device owner to verify the app
15017                UserHandle verifierUser = getUser();
15018                if (verifierUser == UserHandle.ALL) {
15019                    verifierUser = UserHandle.SYSTEM;
15020                }
15021
15022                /*
15023                 * Determine if we have any installed package verifiers. If we
15024                 * do, then we'll defer to them to verify the packages.
15025                 */
15026                final int requiredUid = mRequiredVerifierPackage == null ? -1
15027                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15028                                verifierUser.getIdentifier());
15029                if (!origin.existing && requiredUid != -1
15030                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
15031                    final Intent verification = new Intent(
15032                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15033                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15034                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15035                            PACKAGE_MIME_TYPE);
15036                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15037
15038                    // Query all live verifiers based on current user state
15039                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15040                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15041
15042                    if (DEBUG_VERIFY) {
15043                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15044                                + verification.toString() + " with " + pkgLite.verifiers.length
15045                                + " optional verifiers");
15046                    }
15047
15048                    final int verificationId = mPendingVerificationToken++;
15049
15050                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15051
15052                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15053                            installerPackageName);
15054
15055                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15056                            installFlags);
15057
15058                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15059                            pkgLite.packageName);
15060
15061                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15062                            pkgLite.versionCode);
15063
15064                    if (verificationInfo != null) {
15065                        if (verificationInfo.originatingUri != null) {
15066                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15067                                    verificationInfo.originatingUri);
15068                        }
15069                        if (verificationInfo.referrer != null) {
15070                            verification.putExtra(Intent.EXTRA_REFERRER,
15071                                    verificationInfo.referrer);
15072                        }
15073                        if (verificationInfo.originatingUid >= 0) {
15074                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15075                                    verificationInfo.originatingUid);
15076                        }
15077                        if (verificationInfo.installerUid >= 0) {
15078                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15079                                    verificationInfo.installerUid);
15080                        }
15081                    }
15082
15083                    final PackageVerificationState verificationState = new PackageVerificationState(
15084                            requiredUid, args);
15085
15086                    mPendingVerification.append(verificationId, verificationState);
15087
15088                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15089                            receivers, verificationState);
15090
15091                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15092                    final long idleDuration = getVerificationTimeout();
15093
15094                    /*
15095                     * If any sufficient verifiers were listed in the package
15096                     * manifest, attempt to ask them.
15097                     */
15098                    if (sufficientVerifiers != null) {
15099                        final int N = sufficientVerifiers.size();
15100                        if (N == 0) {
15101                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15102                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15103                        } else {
15104                            for (int i = 0; i < N; i++) {
15105                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15106                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15107                                        verifierComponent.getPackageName(), idleDuration,
15108                                        verifierUser.getIdentifier(), false, "package verifier");
15109
15110                                final Intent sufficientIntent = new Intent(verification);
15111                                sufficientIntent.setComponent(verifierComponent);
15112                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15113                            }
15114                        }
15115                    }
15116
15117                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15118                            mRequiredVerifierPackage, receivers);
15119                    if (ret == PackageManager.INSTALL_SUCCEEDED
15120                            && mRequiredVerifierPackage != null) {
15121                        Trace.asyncTraceBegin(
15122                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15123                        /*
15124                         * Send the intent to the required verification agent,
15125                         * but only start the verification timeout after the
15126                         * target BroadcastReceivers have run.
15127                         */
15128                        verification.setComponent(requiredVerifierComponent);
15129                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15130                                mRequiredVerifierPackage, idleDuration,
15131                                verifierUser.getIdentifier(), false, "package verifier");
15132                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15133                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15134                                new BroadcastReceiver() {
15135                                    @Override
15136                                    public void onReceive(Context context, Intent intent) {
15137                                        final Message msg = mHandler
15138                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15139                                        msg.arg1 = verificationId;
15140                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15141                                    }
15142                                }, null, 0, null, null);
15143
15144                        /*
15145                         * We don't want the copy to proceed until verification
15146                         * succeeds, so null out this field.
15147                         */
15148                        mArgs = null;
15149                    }
15150                } else {
15151                    /*
15152                     * No package verification is enabled, so immediately start
15153                     * the remote call to initiate copy using temporary file.
15154                     */
15155                    ret = args.copyApk(mContainerService, true);
15156                }
15157            }
15158
15159            mRet = ret;
15160        }
15161
15162        @Override
15163        void handleReturnCode() {
15164            // If mArgs is null, then MCS couldn't be reached. When it
15165            // reconnects, it will try again to install. At that point, this
15166            // will succeed.
15167            if (mArgs != null) {
15168                processPendingInstall(mArgs, mRet);
15169            }
15170        }
15171
15172        @Override
15173        void handleServiceError() {
15174            mArgs = createInstallArgs(this);
15175            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15176        }
15177
15178        public boolean isForwardLocked() {
15179            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15180        }
15181    }
15182
15183    /**
15184     * Used during creation of InstallArgs
15185     *
15186     * @param installFlags package installation flags
15187     * @return true if should be installed on external storage
15188     */
15189    private static boolean installOnExternalAsec(int installFlags) {
15190        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
15191            return false;
15192        }
15193        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
15194            return true;
15195        }
15196        return false;
15197    }
15198
15199    /**
15200     * Used during creation of InstallArgs
15201     *
15202     * @param installFlags package installation flags
15203     * @return true if should be installed as forward locked
15204     */
15205    private static boolean installForwardLocked(int installFlags) {
15206        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15207    }
15208
15209    private InstallArgs createInstallArgs(InstallParams params) {
15210        if (params.move != null) {
15211            return new MoveInstallArgs(params);
15212        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
15213            return new AsecInstallArgs(params);
15214        } else {
15215            return new FileInstallArgs(params);
15216        }
15217    }
15218
15219    /**
15220     * Create args that describe an existing installed package. Typically used
15221     * when cleaning up old installs, or used as a move source.
15222     */
15223    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15224            String resourcePath, String[] instructionSets) {
15225        final boolean isInAsec;
15226        if (installOnExternalAsec(installFlags)) {
15227            /* Apps on SD card are always in ASEC containers. */
15228            isInAsec = true;
15229        } else if (installForwardLocked(installFlags)
15230                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
15231            /*
15232             * Forward-locked apps are only in ASEC containers if they're the
15233             * new style
15234             */
15235            isInAsec = true;
15236        } else {
15237            isInAsec = false;
15238        }
15239
15240        if (isInAsec) {
15241            return new AsecInstallArgs(codePath, instructionSets,
15242                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
15243        } else {
15244            return new FileInstallArgs(codePath, resourcePath, instructionSets);
15245        }
15246    }
15247
15248    static abstract class InstallArgs {
15249        /** @see InstallParams#origin */
15250        final OriginInfo origin;
15251        /** @see InstallParams#move */
15252        final MoveInfo move;
15253
15254        final IPackageInstallObserver2 observer;
15255        // Always refers to PackageManager flags only
15256        final int installFlags;
15257        final String installerPackageName;
15258        final String volumeUuid;
15259        final UserHandle user;
15260        final String abiOverride;
15261        final String[] installGrantPermissions;
15262        /** If non-null, drop an async trace when the install completes */
15263        final String traceMethod;
15264        final int traceCookie;
15265        final Certificate[][] certificates;
15266        final int installReason;
15267
15268        // The list of instruction sets supported by this app. This is currently
15269        // only used during the rmdex() phase to clean up resources. We can get rid of this
15270        // if we move dex files under the common app path.
15271        /* nullable */ String[] instructionSets;
15272
15273        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15274                int installFlags, String installerPackageName, String volumeUuid,
15275                UserHandle user, String[] instructionSets,
15276                String abiOverride, String[] installGrantPermissions,
15277                String traceMethod, int traceCookie, Certificate[][] certificates,
15278                int installReason) {
15279            this.origin = origin;
15280            this.move = move;
15281            this.installFlags = installFlags;
15282            this.observer = observer;
15283            this.installerPackageName = installerPackageName;
15284            this.volumeUuid = volumeUuid;
15285            this.user = user;
15286            this.instructionSets = instructionSets;
15287            this.abiOverride = abiOverride;
15288            this.installGrantPermissions = installGrantPermissions;
15289            this.traceMethod = traceMethod;
15290            this.traceCookie = traceCookie;
15291            this.certificates = certificates;
15292            this.installReason = installReason;
15293        }
15294
15295        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15296        abstract int doPreInstall(int status);
15297
15298        /**
15299         * Rename package into final resting place. All paths on the given
15300         * scanned package should be updated to reflect the rename.
15301         */
15302        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15303        abstract int doPostInstall(int status, int uid);
15304
15305        /** @see PackageSettingBase#codePathString */
15306        abstract String getCodePath();
15307        /** @see PackageSettingBase#resourcePathString */
15308        abstract String getResourcePath();
15309
15310        // Need installer lock especially for dex file removal.
15311        abstract void cleanUpResourcesLI();
15312        abstract boolean doPostDeleteLI(boolean delete);
15313
15314        /**
15315         * Called before the source arguments are copied. This is used mostly
15316         * for MoveParams when it needs to read the source file to put it in the
15317         * destination.
15318         */
15319        int doPreCopy() {
15320            return PackageManager.INSTALL_SUCCEEDED;
15321        }
15322
15323        /**
15324         * Called after the source arguments are copied. This is used mostly for
15325         * MoveParams when it needs to read the source file to put it in the
15326         * destination.
15327         */
15328        int doPostCopy(int uid) {
15329            return PackageManager.INSTALL_SUCCEEDED;
15330        }
15331
15332        protected boolean isFwdLocked() {
15333            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15334        }
15335
15336        protected boolean isExternalAsec() {
15337            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15338        }
15339
15340        protected boolean isEphemeral() {
15341            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15342        }
15343
15344        UserHandle getUser() {
15345            return user;
15346        }
15347    }
15348
15349    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15350        if (!allCodePaths.isEmpty()) {
15351            if (instructionSets == null) {
15352                throw new IllegalStateException("instructionSet == null");
15353            }
15354            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15355            for (String codePath : allCodePaths) {
15356                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15357                    try {
15358                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15359                    } catch (InstallerException ignored) {
15360                    }
15361                }
15362            }
15363        }
15364    }
15365
15366    /**
15367     * Logic to handle installation of non-ASEC applications, including copying
15368     * and renaming logic.
15369     */
15370    class FileInstallArgs extends InstallArgs {
15371        private File codeFile;
15372        private File resourceFile;
15373
15374        // Example topology:
15375        // /data/app/com.example/base.apk
15376        // /data/app/com.example/split_foo.apk
15377        // /data/app/com.example/lib/arm/libfoo.so
15378        // /data/app/com.example/lib/arm64/libfoo.so
15379        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15380
15381        /** New install */
15382        FileInstallArgs(InstallParams params) {
15383            super(params.origin, params.move, params.observer, params.installFlags,
15384                    params.installerPackageName, params.volumeUuid,
15385                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15386                    params.grantedRuntimePermissions,
15387                    params.traceMethod, params.traceCookie, params.certificates,
15388                    params.installReason);
15389            if (isFwdLocked()) {
15390                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15391            }
15392        }
15393
15394        /** Existing install */
15395        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15396            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15397                    null, null, null, 0, null /*certificates*/,
15398                    PackageManager.INSTALL_REASON_UNKNOWN);
15399            this.codeFile = (codePath != null) ? new File(codePath) : null;
15400            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15401        }
15402
15403        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15404            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15405            try {
15406                return doCopyApk(imcs, temp);
15407            } finally {
15408                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15409            }
15410        }
15411
15412        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15413            if (origin.staged) {
15414                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15415                codeFile = origin.file;
15416                resourceFile = origin.file;
15417                return PackageManager.INSTALL_SUCCEEDED;
15418            }
15419
15420            try {
15421                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15422                final File tempDir =
15423                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15424                codeFile = tempDir;
15425                resourceFile = tempDir;
15426            } catch (IOException e) {
15427                Slog.w(TAG, "Failed to create copy file: " + e);
15428                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15429            }
15430
15431            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15432                @Override
15433                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15434                    if (!FileUtils.isValidExtFilename(name)) {
15435                        throw new IllegalArgumentException("Invalid filename: " + name);
15436                    }
15437                    try {
15438                        final File file = new File(codeFile, name);
15439                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15440                                O_RDWR | O_CREAT, 0644);
15441                        Os.chmod(file.getAbsolutePath(), 0644);
15442                        return new ParcelFileDescriptor(fd);
15443                    } catch (ErrnoException e) {
15444                        throw new RemoteException("Failed to open: " + e.getMessage());
15445                    }
15446                }
15447            };
15448
15449            int ret = PackageManager.INSTALL_SUCCEEDED;
15450            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15451            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15452                Slog.e(TAG, "Failed to copy package");
15453                return ret;
15454            }
15455
15456            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15457            NativeLibraryHelper.Handle handle = null;
15458            try {
15459                handle = NativeLibraryHelper.Handle.create(codeFile);
15460                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15461                        abiOverride);
15462            } catch (IOException e) {
15463                Slog.e(TAG, "Copying native libraries failed", e);
15464                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15465            } finally {
15466                IoUtils.closeQuietly(handle);
15467            }
15468
15469            return ret;
15470        }
15471
15472        int doPreInstall(int status) {
15473            if (status != PackageManager.INSTALL_SUCCEEDED) {
15474                cleanUp();
15475            }
15476            return status;
15477        }
15478
15479        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15480            if (status != PackageManager.INSTALL_SUCCEEDED) {
15481                cleanUp();
15482                return false;
15483            }
15484
15485            final File targetDir = codeFile.getParentFile();
15486            final File beforeCodeFile = codeFile;
15487            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15488
15489            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15490            try {
15491                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15492            } catch (ErrnoException e) {
15493                Slog.w(TAG, "Failed to rename", e);
15494                return false;
15495            }
15496
15497            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15498                Slog.w(TAG, "Failed to restorecon");
15499                return false;
15500            }
15501
15502            // Reflect the rename internally
15503            codeFile = afterCodeFile;
15504            resourceFile = afterCodeFile;
15505
15506            // Reflect the rename in scanned details
15507            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15508            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15509                    afterCodeFile, pkg.baseCodePath));
15510            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15511                    afterCodeFile, pkg.splitCodePaths));
15512
15513            // Reflect the rename in app info
15514            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15515            pkg.setApplicationInfoCodePath(pkg.codePath);
15516            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15517            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15518            pkg.setApplicationInfoResourcePath(pkg.codePath);
15519            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15520            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15521
15522            return true;
15523        }
15524
15525        int doPostInstall(int status, int uid) {
15526            if (status != PackageManager.INSTALL_SUCCEEDED) {
15527                cleanUp();
15528            }
15529            return status;
15530        }
15531
15532        @Override
15533        String getCodePath() {
15534            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15535        }
15536
15537        @Override
15538        String getResourcePath() {
15539            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15540        }
15541
15542        private boolean cleanUp() {
15543            if (codeFile == null || !codeFile.exists()) {
15544                return false;
15545            }
15546
15547            removeCodePathLI(codeFile);
15548
15549            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15550                resourceFile.delete();
15551            }
15552
15553            return true;
15554        }
15555
15556        void cleanUpResourcesLI() {
15557            // Try enumerating all code paths before deleting
15558            List<String> allCodePaths = Collections.EMPTY_LIST;
15559            if (codeFile != null && codeFile.exists()) {
15560                try {
15561                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15562                    allCodePaths = pkg.getAllCodePaths();
15563                } catch (PackageParserException e) {
15564                    // Ignored; we tried our best
15565                }
15566            }
15567
15568            cleanUp();
15569            removeDexFiles(allCodePaths, instructionSets);
15570        }
15571
15572        boolean doPostDeleteLI(boolean delete) {
15573            // XXX err, shouldn't we respect the delete flag?
15574            cleanUpResourcesLI();
15575            return true;
15576        }
15577    }
15578
15579    private boolean isAsecExternal(String cid) {
15580        final String asecPath = PackageHelper.getSdFilesystem(cid);
15581        return !asecPath.startsWith(mAsecInternalPath);
15582    }
15583
15584    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15585            PackageManagerException {
15586        if (copyRet < 0) {
15587            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15588                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15589                throw new PackageManagerException(copyRet, message);
15590            }
15591        }
15592    }
15593
15594    /**
15595     * Extract the StorageManagerService "container ID" from the full code path of an
15596     * .apk.
15597     */
15598    static String cidFromCodePath(String fullCodePath) {
15599        int eidx = fullCodePath.lastIndexOf("/");
15600        String subStr1 = fullCodePath.substring(0, eidx);
15601        int sidx = subStr1.lastIndexOf("/");
15602        return subStr1.substring(sidx+1, eidx);
15603    }
15604
15605    /**
15606     * Logic to handle installation of ASEC applications, including copying and
15607     * renaming logic.
15608     */
15609    class AsecInstallArgs extends InstallArgs {
15610        static final String RES_FILE_NAME = "pkg.apk";
15611        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15612
15613        String cid;
15614        String packagePath;
15615        String resourcePath;
15616
15617        /** New install */
15618        AsecInstallArgs(InstallParams params) {
15619            super(params.origin, params.move, params.observer, params.installFlags,
15620                    params.installerPackageName, params.volumeUuid,
15621                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15622                    params.grantedRuntimePermissions,
15623                    params.traceMethod, params.traceCookie, params.certificates,
15624                    params.installReason);
15625        }
15626
15627        /** Existing install */
15628        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15629                        boolean isExternal, boolean isForwardLocked) {
15630            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15631                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15632                    instructionSets, null, null, null, 0, null /*certificates*/,
15633                    PackageManager.INSTALL_REASON_UNKNOWN);
15634            // Hackily pretend we're still looking at a full code path
15635            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15636                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15637            }
15638
15639            // Extract cid from fullCodePath
15640            int eidx = fullCodePath.lastIndexOf("/");
15641            String subStr1 = fullCodePath.substring(0, eidx);
15642            int sidx = subStr1.lastIndexOf("/");
15643            cid = subStr1.substring(sidx+1, eidx);
15644            setMountPath(subStr1);
15645        }
15646
15647        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15648            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15649                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15650                    instructionSets, null, null, null, 0, null /*certificates*/,
15651                    PackageManager.INSTALL_REASON_UNKNOWN);
15652            this.cid = cid;
15653            setMountPath(PackageHelper.getSdDir(cid));
15654        }
15655
15656        void createCopyFile() {
15657            cid = mInstallerService.allocateExternalStageCidLegacy();
15658        }
15659
15660        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15661            if (origin.staged && origin.cid != null) {
15662                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15663                cid = origin.cid;
15664                setMountPath(PackageHelper.getSdDir(cid));
15665                return PackageManager.INSTALL_SUCCEEDED;
15666            }
15667
15668            if (temp) {
15669                createCopyFile();
15670            } else {
15671                /*
15672                 * Pre-emptively destroy the container since it's destroyed if
15673                 * copying fails due to it existing anyway.
15674                 */
15675                PackageHelper.destroySdDir(cid);
15676            }
15677
15678            final String newMountPath = imcs.copyPackageToContainer(
15679                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15680                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15681
15682            if (newMountPath != null) {
15683                setMountPath(newMountPath);
15684                return PackageManager.INSTALL_SUCCEEDED;
15685            } else {
15686                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15687            }
15688        }
15689
15690        @Override
15691        String getCodePath() {
15692            return packagePath;
15693        }
15694
15695        @Override
15696        String getResourcePath() {
15697            return resourcePath;
15698        }
15699
15700        int doPreInstall(int status) {
15701            if (status != PackageManager.INSTALL_SUCCEEDED) {
15702                // Destroy container
15703                PackageHelper.destroySdDir(cid);
15704            } else {
15705                boolean mounted = PackageHelper.isContainerMounted(cid);
15706                if (!mounted) {
15707                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15708                            Process.SYSTEM_UID);
15709                    if (newMountPath != null) {
15710                        setMountPath(newMountPath);
15711                    } else {
15712                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15713                    }
15714                }
15715            }
15716            return status;
15717        }
15718
15719        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15720            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15721            String newMountPath = null;
15722            if (PackageHelper.isContainerMounted(cid)) {
15723                // Unmount the container
15724                if (!PackageHelper.unMountSdDir(cid)) {
15725                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15726                    return false;
15727                }
15728            }
15729            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15730                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15731                        " which might be stale. Will try to clean up.");
15732                // Clean up the stale container and proceed to recreate.
15733                if (!PackageHelper.destroySdDir(newCacheId)) {
15734                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15735                    return false;
15736                }
15737                // Successfully cleaned up stale container. Try to rename again.
15738                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15739                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15740                            + " inspite of cleaning it up.");
15741                    return false;
15742                }
15743            }
15744            if (!PackageHelper.isContainerMounted(newCacheId)) {
15745                Slog.w(TAG, "Mounting container " + newCacheId);
15746                newMountPath = PackageHelper.mountSdDir(newCacheId,
15747                        getEncryptKey(), Process.SYSTEM_UID);
15748            } else {
15749                newMountPath = PackageHelper.getSdDir(newCacheId);
15750            }
15751            if (newMountPath == null) {
15752                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15753                return false;
15754            }
15755            Log.i(TAG, "Succesfully renamed " + cid +
15756                    " to " + newCacheId +
15757                    " at new path: " + newMountPath);
15758            cid = newCacheId;
15759
15760            final File beforeCodeFile = new File(packagePath);
15761            setMountPath(newMountPath);
15762            final File afterCodeFile = new File(packagePath);
15763
15764            // Reflect the rename in scanned details
15765            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15766            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15767                    afterCodeFile, pkg.baseCodePath));
15768            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15769                    afterCodeFile, pkg.splitCodePaths));
15770
15771            // Reflect the rename in app info
15772            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15773            pkg.setApplicationInfoCodePath(pkg.codePath);
15774            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15775            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15776            pkg.setApplicationInfoResourcePath(pkg.codePath);
15777            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15778            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15779
15780            return true;
15781        }
15782
15783        private void setMountPath(String mountPath) {
15784            final File mountFile = new File(mountPath);
15785
15786            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15787            if (monolithicFile.exists()) {
15788                packagePath = monolithicFile.getAbsolutePath();
15789                if (isFwdLocked()) {
15790                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15791                } else {
15792                    resourcePath = packagePath;
15793                }
15794            } else {
15795                packagePath = mountFile.getAbsolutePath();
15796                resourcePath = packagePath;
15797            }
15798        }
15799
15800        int doPostInstall(int status, int uid) {
15801            if (status != PackageManager.INSTALL_SUCCEEDED) {
15802                cleanUp();
15803            } else {
15804                final int groupOwner;
15805                final String protectedFile;
15806                if (isFwdLocked()) {
15807                    groupOwner = UserHandle.getSharedAppGid(uid);
15808                    protectedFile = RES_FILE_NAME;
15809                } else {
15810                    groupOwner = -1;
15811                    protectedFile = null;
15812                }
15813
15814                if (uid < Process.FIRST_APPLICATION_UID
15815                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15816                    Slog.e(TAG, "Failed to finalize " + cid);
15817                    PackageHelper.destroySdDir(cid);
15818                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15819                }
15820
15821                boolean mounted = PackageHelper.isContainerMounted(cid);
15822                if (!mounted) {
15823                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15824                }
15825            }
15826            return status;
15827        }
15828
15829        private void cleanUp() {
15830            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15831
15832            // Destroy secure container
15833            PackageHelper.destroySdDir(cid);
15834        }
15835
15836        private List<String> getAllCodePaths() {
15837            final File codeFile = new File(getCodePath());
15838            if (codeFile != null && codeFile.exists()) {
15839                try {
15840                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15841                    return pkg.getAllCodePaths();
15842                } catch (PackageParserException e) {
15843                    // Ignored; we tried our best
15844                }
15845            }
15846            return Collections.EMPTY_LIST;
15847        }
15848
15849        void cleanUpResourcesLI() {
15850            // Enumerate all code paths before deleting
15851            cleanUpResourcesLI(getAllCodePaths());
15852        }
15853
15854        private void cleanUpResourcesLI(List<String> allCodePaths) {
15855            cleanUp();
15856            removeDexFiles(allCodePaths, instructionSets);
15857        }
15858
15859        String getPackageName() {
15860            return getAsecPackageName(cid);
15861        }
15862
15863        boolean doPostDeleteLI(boolean delete) {
15864            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15865            final List<String> allCodePaths = getAllCodePaths();
15866            boolean mounted = PackageHelper.isContainerMounted(cid);
15867            if (mounted) {
15868                // Unmount first
15869                if (PackageHelper.unMountSdDir(cid)) {
15870                    mounted = false;
15871                }
15872            }
15873            if (!mounted && delete) {
15874                cleanUpResourcesLI(allCodePaths);
15875            }
15876            return !mounted;
15877        }
15878
15879        @Override
15880        int doPreCopy() {
15881            if (isFwdLocked()) {
15882                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15883                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15884                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15885                }
15886            }
15887
15888            return PackageManager.INSTALL_SUCCEEDED;
15889        }
15890
15891        @Override
15892        int doPostCopy(int uid) {
15893            if (isFwdLocked()) {
15894                if (uid < Process.FIRST_APPLICATION_UID
15895                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15896                                RES_FILE_NAME)) {
15897                    Slog.e(TAG, "Failed to finalize " + cid);
15898                    PackageHelper.destroySdDir(cid);
15899                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15900                }
15901            }
15902
15903            return PackageManager.INSTALL_SUCCEEDED;
15904        }
15905    }
15906
15907    /**
15908     * Logic to handle movement of existing installed applications.
15909     */
15910    class MoveInstallArgs extends InstallArgs {
15911        private File codeFile;
15912        private File resourceFile;
15913
15914        /** New install */
15915        MoveInstallArgs(InstallParams params) {
15916            super(params.origin, params.move, params.observer, params.installFlags,
15917                    params.installerPackageName, params.volumeUuid,
15918                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15919                    params.grantedRuntimePermissions,
15920                    params.traceMethod, params.traceCookie, params.certificates,
15921                    params.installReason);
15922        }
15923
15924        int copyApk(IMediaContainerService imcs, boolean temp) {
15925            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15926                    + move.fromUuid + " to " + move.toUuid);
15927            synchronized (mInstaller) {
15928                try {
15929                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15930                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15931                } catch (InstallerException e) {
15932                    Slog.w(TAG, "Failed to move app", e);
15933                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15934                }
15935            }
15936
15937            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15938            resourceFile = codeFile;
15939            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15940
15941            return PackageManager.INSTALL_SUCCEEDED;
15942        }
15943
15944        int doPreInstall(int status) {
15945            if (status != PackageManager.INSTALL_SUCCEEDED) {
15946                cleanUp(move.toUuid);
15947            }
15948            return status;
15949        }
15950
15951        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15952            if (status != PackageManager.INSTALL_SUCCEEDED) {
15953                cleanUp(move.toUuid);
15954                return false;
15955            }
15956
15957            // Reflect the move in app info
15958            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15959            pkg.setApplicationInfoCodePath(pkg.codePath);
15960            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15961            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15962            pkg.setApplicationInfoResourcePath(pkg.codePath);
15963            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15964            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15965
15966            return true;
15967        }
15968
15969        int doPostInstall(int status, int uid) {
15970            if (status == PackageManager.INSTALL_SUCCEEDED) {
15971                cleanUp(move.fromUuid);
15972            } else {
15973                cleanUp(move.toUuid);
15974            }
15975            return status;
15976        }
15977
15978        @Override
15979        String getCodePath() {
15980            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15981        }
15982
15983        @Override
15984        String getResourcePath() {
15985            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15986        }
15987
15988        private boolean cleanUp(String volumeUuid) {
15989            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15990                    move.dataAppName);
15991            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15992            final int[] userIds = sUserManager.getUserIds();
15993            synchronized (mInstallLock) {
15994                // Clean up both app data and code
15995                // All package moves are frozen until finished
15996                for (int userId : userIds) {
15997                    try {
15998                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15999                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16000                    } catch (InstallerException e) {
16001                        Slog.w(TAG, String.valueOf(e));
16002                    }
16003                }
16004                removeCodePathLI(codeFile);
16005            }
16006            return true;
16007        }
16008
16009        void cleanUpResourcesLI() {
16010            throw new UnsupportedOperationException();
16011        }
16012
16013        boolean doPostDeleteLI(boolean delete) {
16014            throw new UnsupportedOperationException();
16015        }
16016    }
16017
16018    static String getAsecPackageName(String packageCid) {
16019        int idx = packageCid.lastIndexOf("-");
16020        if (idx == -1) {
16021            return packageCid;
16022        }
16023        return packageCid.substring(0, idx);
16024    }
16025
16026    // Utility method used to create code paths based on package name and available index.
16027    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16028        String idxStr = "";
16029        int idx = 1;
16030        // Fall back to default value of idx=1 if prefix is not
16031        // part of oldCodePath
16032        if (oldCodePath != null) {
16033            String subStr = oldCodePath;
16034            // Drop the suffix right away
16035            if (suffix != null && subStr.endsWith(suffix)) {
16036                subStr = subStr.substring(0, subStr.length() - suffix.length());
16037            }
16038            // If oldCodePath already contains prefix find out the
16039            // ending index to either increment or decrement.
16040            int sidx = subStr.lastIndexOf(prefix);
16041            if (sidx != -1) {
16042                subStr = subStr.substring(sidx + prefix.length());
16043                if (subStr != null) {
16044                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16045                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16046                    }
16047                    try {
16048                        idx = Integer.parseInt(subStr);
16049                        if (idx <= 1) {
16050                            idx++;
16051                        } else {
16052                            idx--;
16053                        }
16054                    } catch(NumberFormatException e) {
16055                    }
16056                }
16057            }
16058        }
16059        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16060        return prefix + idxStr;
16061    }
16062
16063    private File getNextCodePath(File targetDir, String packageName) {
16064        File result;
16065        SecureRandom random = new SecureRandom();
16066        byte[] bytes = new byte[16];
16067        do {
16068            random.nextBytes(bytes);
16069            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16070            result = new File(targetDir, packageName + "-" + suffix);
16071        } while (result.exists());
16072        return result;
16073    }
16074
16075    // Utility method that returns the relative package path with respect
16076    // to the installation directory. Like say for /data/data/com.test-1.apk
16077    // string com.test-1 is returned.
16078    static String deriveCodePathName(String codePath) {
16079        if (codePath == null) {
16080            return null;
16081        }
16082        final File codeFile = new File(codePath);
16083        final String name = codeFile.getName();
16084        if (codeFile.isDirectory()) {
16085            return name;
16086        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16087            final int lastDot = name.lastIndexOf('.');
16088            return name.substring(0, lastDot);
16089        } else {
16090            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16091            return null;
16092        }
16093    }
16094
16095    static class PackageInstalledInfo {
16096        String name;
16097        int uid;
16098        // The set of users that originally had this package installed.
16099        int[] origUsers;
16100        // The set of users that now have this package installed.
16101        int[] newUsers;
16102        PackageParser.Package pkg;
16103        int returnCode;
16104        String returnMsg;
16105        PackageRemovedInfo removedInfo;
16106        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16107
16108        public void setError(int code, String msg) {
16109            setReturnCode(code);
16110            setReturnMessage(msg);
16111            Slog.w(TAG, msg);
16112        }
16113
16114        public void setError(String msg, PackageParserException e) {
16115            setReturnCode(e.error);
16116            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16117            Slog.w(TAG, msg, e);
16118        }
16119
16120        public void setError(String msg, PackageManagerException e) {
16121            returnCode = e.error;
16122            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16123            Slog.w(TAG, msg, e);
16124        }
16125
16126        public void setReturnCode(int returnCode) {
16127            this.returnCode = returnCode;
16128            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16129            for (int i = 0; i < childCount; i++) {
16130                addedChildPackages.valueAt(i).returnCode = returnCode;
16131            }
16132        }
16133
16134        private void setReturnMessage(String returnMsg) {
16135            this.returnMsg = returnMsg;
16136            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16137            for (int i = 0; i < childCount; i++) {
16138                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16139            }
16140        }
16141
16142        // In some error cases we want to convey more info back to the observer
16143        String origPackage;
16144        String origPermission;
16145    }
16146
16147    /*
16148     * Install a non-existing package.
16149     */
16150    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
16151            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
16152            PackageInstalledInfo res, int installReason) {
16153        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16154
16155        // Remember this for later, in case we need to rollback this install
16156        String pkgName = pkg.packageName;
16157
16158        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16159
16160        synchronized(mPackages) {
16161            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16162            if (renamedPackage != null) {
16163                // A package with the same name is already installed, though
16164                // it has been renamed to an older name.  The package we
16165                // are trying to install should be installed as an update to
16166                // the existing one, but that has not been requested, so bail.
16167                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16168                        + " without first uninstalling package running as "
16169                        + renamedPackage);
16170                return;
16171            }
16172            if (mPackages.containsKey(pkgName)) {
16173                // Don't allow installation over an existing package with the same name.
16174                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16175                        + " without first uninstalling.");
16176                return;
16177            }
16178        }
16179
16180        try {
16181            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
16182                    System.currentTimeMillis(), user);
16183
16184            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16185
16186            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16187                prepareAppDataAfterInstallLIF(newPackage);
16188
16189            } else {
16190                // Remove package from internal structures, but keep around any
16191                // data that might have already existed
16192                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16193                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16194            }
16195        } catch (PackageManagerException e) {
16196            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16197        }
16198
16199        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16200    }
16201
16202    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
16203        // Can't rotate keys during boot or if sharedUser.
16204        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
16205                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
16206            return false;
16207        }
16208        // app is using upgradeKeySets; make sure all are valid
16209        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16210        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
16211        for (int i = 0; i < upgradeKeySets.length; i++) {
16212            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
16213                Slog.wtf(TAG, "Package "
16214                         + (oldPs.name != null ? oldPs.name : "<null>")
16215                         + " contains upgrade-key-set reference to unknown key-set: "
16216                         + upgradeKeySets[i]
16217                         + " reverting to signatures check.");
16218                return false;
16219            }
16220        }
16221        return true;
16222    }
16223
16224    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
16225        // Upgrade keysets are being used.  Determine if new package has a superset of the
16226        // required keys.
16227        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
16228        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16229        for (int i = 0; i < upgradeKeySets.length; i++) {
16230            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
16231            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
16232                return true;
16233            }
16234        }
16235        return false;
16236    }
16237
16238    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16239        try (DigestInputStream digestStream =
16240                new DigestInputStream(new FileInputStream(file), digest)) {
16241            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16242        }
16243    }
16244
16245    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
16246            UserHandle user, String installerPackageName, PackageInstalledInfo res,
16247            int installReason) {
16248        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16249
16250        final PackageParser.Package oldPackage;
16251        final PackageSetting ps;
16252        final String pkgName = pkg.packageName;
16253        final int[] allUsers;
16254        final int[] installedUsers;
16255
16256        synchronized(mPackages) {
16257            oldPackage = mPackages.get(pkgName);
16258            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16259
16260            // don't allow upgrade to target a release SDK from a pre-release SDK
16261            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16262                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16263            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16264                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16265            if (oldTargetsPreRelease
16266                    && !newTargetsPreRelease
16267                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16268                Slog.w(TAG, "Can't install package targeting released sdk");
16269                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16270                return;
16271            }
16272
16273            ps = mSettings.mPackages.get(pkgName);
16274
16275            // verify signatures are valid
16276            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
16277                if (!checkUpgradeKeySetLP(ps, pkg)) {
16278                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16279                            "New package not signed by keys specified by upgrade-keysets: "
16280                                    + pkgName);
16281                    return;
16282                }
16283            } else {
16284                // default to original signature matching
16285                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
16286                        != PackageManager.SIGNATURE_MATCH) {
16287                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16288                            "New package has a different signature: " + pkgName);
16289                    return;
16290                }
16291            }
16292
16293            // don't allow a system upgrade unless the upgrade hash matches
16294            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
16295                byte[] digestBytes = null;
16296                try {
16297                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16298                    updateDigest(digest, new File(pkg.baseCodePath));
16299                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16300                        for (String path : pkg.splitCodePaths) {
16301                            updateDigest(digest, new File(path));
16302                        }
16303                    }
16304                    digestBytes = digest.digest();
16305                } catch (NoSuchAlgorithmException | IOException e) {
16306                    res.setError(INSTALL_FAILED_INVALID_APK,
16307                            "Could not compute hash: " + pkgName);
16308                    return;
16309                }
16310                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16311                    res.setError(INSTALL_FAILED_INVALID_APK,
16312                            "New package fails restrict-update check: " + pkgName);
16313                    return;
16314                }
16315                // retain upgrade restriction
16316                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16317            }
16318
16319            // Check for shared user id changes
16320            String invalidPackageName =
16321                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16322            if (invalidPackageName != null) {
16323                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16324                        "Package " + invalidPackageName + " tried to change user "
16325                                + oldPackage.mSharedUserId);
16326                return;
16327            }
16328
16329            // In case of rollback, remember per-user/profile install state
16330            allUsers = sUserManager.getUserIds();
16331            installedUsers = ps.queryInstalledUsers(allUsers, true);
16332
16333            // don't allow an upgrade from full to ephemeral
16334            if (isInstantApp) {
16335                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16336                    for (int currentUser : allUsers) {
16337                        if (!ps.getInstantApp(currentUser)) {
16338                            // can't downgrade from full to instant
16339                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16340                                    + " for user: " + currentUser);
16341                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16342                            return;
16343                        }
16344                    }
16345                } else if (!ps.getInstantApp(user.getIdentifier())) {
16346                    // can't downgrade from full to instant
16347                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16348                            + " for user: " + user.getIdentifier());
16349                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16350                    return;
16351                }
16352            }
16353        }
16354
16355        // Update what is removed
16356        res.removedInfo = new PackageRemovedInfo(this);
16357        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16358        res.removedInfo.removedPackage = oldPackage.packageName;
16359        res.removedInfo.installerPackageName = ps.installerPackageName;
16360        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16361        res.removedInfo.isUpdate = true;
16362        res.removedInfo.origUsers = installedUsers;
16363        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16364        for (int i = 0; i < installedUsers.length; i++) {
16365            final int userId = installedUsers[i];
16366            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16367        }
16368
16369        final int childCount = (oldPackage.childPackages != null)
16370                ? oldPackage.childPackages.size() : 0;
16371        for (int i = 0; i < childCount; i++) {
16372            boolean childPackageUpdated = false;
16373            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16374            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16375            if (res.addedChildPackages != null) {
16376                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16377                if (childRes != null) {
16378                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16379                    childRes.removedInfo.removedPackage = childPkg.packageName;
16380                    if (childPs != null) {
16381                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16382                    }
16383                    childRes.removedInfo.isUpdate = true;
16384                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16385                    childPackageUpdated = true;
16386                }
16387            }
16388            if (!childPackageUpdated) {
16389                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16390                childRemovedRes.removedPackage = childPkg.packageName;
16391                if (childPs != null) {
16392                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16393                }
16394                childRemovedRes.isUpdate = false;
16395                childRemovedRes.dataRemoved = true;
16396                synchronized (mPackages) {
16397                    if (childPs != null) {
16398                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16399                    }
16400                }
16401                if (res.removedInfo.removedChildPackages == null) {
16402                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16403                }
16404                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16405            }
16406        }
16407
16408        boolean sysPkg = (isSystemApp(oldPackage));
16409        if (sysPkg) {
16410            // Set the system/privileged flags as needed
16411            final boolean privileged =
16412                    (oldPackage.applicationInfo.privateFlags
16413                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16414            final int systemPolicyFlags = policyFlags
16415                    | PackageParser.PARSE_IS_SYSTEM
16416                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
16417
16418            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
16419                    user, allUsers, installerPackageName, res, installReason);
16420        } else {
16421            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
16422                    user, allUsers, installerPackageName, res, installReason);
16423        }
16424    }
16425
16426    public List<String> getPreviousCodePaths(String packageName) {
16427        final PackageSetting ps = mSettings.mPackages.get(packageName);
16428        final List<String> result = new ArrayList<String>();
16429        if (ps != null && ps.oldCodePaths != null) {
16430            result.addAll(ps.oldCodePaths);
16431        }
16432        return result;
16433    }
16434
16435    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16436            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16437            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16438            int installReason) {
16439        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16440                + deletedPackage);
16441
16442        String pkgName = deletedPackage.packageName;
16443        boolean deletedPkg = true;
16444        boolean addedPkg = false;
16445        boolean updatedSettings = false;
16446        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16447        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16448                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16449
16450        final long origUpdateTime = (pkg.mExtras != null)
16451                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16452
16453        // First delete the existing package while retaining the data directory
16454        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16455                res.removedInfo, true, pkg)) {
16456            // If the existing package wasn't successfully deleted
16457            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16458            deletedPkg = false;
16459        } else {
16460            // Successfully deleted the old package; proceed with replace.
16461
16462            // If deleted package lived in a container, give users a chance to
16463            // relinquish resources before killing.
16464            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16465                if (DEBUG_INSTALL) {
16466                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16467                }
16468                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16469                final ArrayList<String> pkgList = new ArrayList<String>(1);
16470                pkgList.add(deletedPackage.applicationInfo.packageName);
16471                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16472            }
16473
16474            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16475                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16476            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16477
16478            try {
16479                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
16480                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16481                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16482                        installReason);
16483
16484                // Update the in-memory copy of the previous code paths.
16485                PackageSetting ps = mSettings.mPackages.get(pkgName);
16486                if (!killApp) {
16487                    if (ps.oldCodePaths == null) {
16488                        ps.oldCodePaths = new ArraySet<>();
16489                    }
16490                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16491                    if (deletedPackage.splitCodePaths != null) {
16492                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16493                    }
16494                } else {
16495                    ps.oldCodePaths = null;
16496                }
16497                if (ps.childPackageNames != null) {
16498                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16499                        final String childPkgName = ps.childPackageNames.get(i);
16500                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16501                        childPs.oldCodePaths = ps.oldCodePaths;
16502                    }
16503                }
16504                // set instant app status, but, only if it's explicitly specified
16505                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16506                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16507                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16508                prepareAppDataAfterInstallLIF(newPackage);
16509                addedPkg = true;
16510                mDexManager.notifyPackageUpdated(newPackage.packageName,
16511                        newPackage.baseCodePath, newPackage.splitCodePaths);
16512            } catch (PackageManagerException e) {
16513                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16514            }
16515        }
16516
16517        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16518            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16519
16520            // Revert all internal state mutations and added folders for the failed install
16521            if (addedPkg) {
16522                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16523                        res.removedInfo, true, null);
16524            }
16525
16526            // Restore the old package
16527            if (deletedPkg) {
16528                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16529                File restoreFile = new File(deletedPackage.codePath);
16530                // Parse old package
16531                boolean oldExternal = isExternal(deletedPackage);
16532                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16533                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16534                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16535                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16536                try {
16537                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16538                            null);
16539                } catch (PackageManagerException e) {
16540                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16541                            + e.getMessage());
16542                    return;
16543                }
16544
16545                synchronized (mPackages) {
16546                    // Ensure the installer package name up to date
16547                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16548
16549                    // Update permissions for restored package
16550                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16551
16552                    mSettings.writeLPr();
16553                }
16554
16555                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16556            }
16557        } else {
16558            synchronized (mPackages) {
16559                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16560                if (ps != null) {
16561                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16562                    if (res.removedInfo.removedChildPackages != null) {
16563                        final int childCount = res.removedInfo.removedChildPackages.size();
16564                        // Iterate in reverse as we may modify the collection
16565                        for (int i = childCount - 1; i >= 0; i--) {
16566                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16567                            if (res.addedChildPackages.containsKey(childPackageName)) {
16568                                res.removedInfo.removedChildPackages.removeAt(i);
16569                            } else {
16570                                PackageRemovedInfo childInfo = res.removedInfo
16571                                        .removedChildPackages.valueAt(i);
16572                                childInfo.removedForAllUsers = mPackages.get(
16573                                        childInfo.removedPackage) == null;
16574                            }
16575                        }
16576                    }
16577                }
16578            }
16579        }
16580    }
16581
16582    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16583            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16584            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16585            int installReason) {
16586        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16587                + ", old=" + deletedPackage);
16588
16589        final boolean disabledSystem;
16590
16591        // Remove existing system package
16592        removePackageLI(deletedPackage, true);
16593
16594        synchronized (mPackages) {
16595            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16596        }
16597        if (!disabledSystem) {
16598            // We didn't need to disable the .apk as a current system package,
16599            // which means we are replacing another update that is already
16600            // installed.  We need to make sure to delete the older one's .apk.
16601            res.removedInfo.args = createInstallArgsForExisting(0,
16602                    deletedPackage.applicationInfo.getCodePath(),
16603                    deletedPackage.applicationInfo.getResourcePath(),
16604                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16605        } else {
16606            res.removedInfo.args = null;
16607        }
16608
16609        // Successfully disabled the old package. Now proceed with re-installation
16610        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16611                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16612        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16613
16614        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16615        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16616                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16617
16618        PackageParser.Package newPackage = null;
16619        try {
16620            // Add the package to the internal data structures
16621            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16622
16623            // Set the update and install times
16624            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16625            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16626                    System.currentTimeMillis());
16627
16628            // Update the package dynamic state if succeeded
16629            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16630                // Now that the install succeeded make sure we remove data
16631                // directories for any child package the update removed.
16632                final int deletedChildCount = (deletedPackage.childPackages != null)
16633                        ? deletedPackage.childPackages.size() : 0;
16634                final int newChildCount = (newPackage.childPackages != null)
16635                        ? newPackage.childPackages.size() : 0;
16636                for (int i = 0; i < deletedChildCount; i++) {
16637                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16638                    boolean childPackageDeleted = true;
16639                    for (int j = 0; j < newChildCount; j++) {
16640                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16641                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16642                            childPackageDeleted = false;
16643                            break;
16644                        }
16645                    }
16646                    if (childPackageDeleted) {
16647                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16648                                deletedChildPkg.packageName);
16649                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16650                            PackageRemovedInfo removedChildRes = res.removedInfo
16651                                    .removedChildPackages.get(deletedChildPkg.packageName);
16652                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16653                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16654                        }
16655                    }
16656                }
16657
16658                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16659                        installReason);
16660                prepareAppDataAfterInstallLIF(newPackage);
16661
16662                mDexManager.notifyPackageUpdated(newPackage.packageName,
16663                            newPackage.baseCodePath, newPackage.splitCodePaths);
16664            }
16665        } catch (PackageManagerException e) {
16666            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16667            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16668        }
16669
16670        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16671            // Re installation failed. Restore old information
16672            // Remove new pkg information
16673            if (newPackage != null) {
16674                removeInstalledPackageLI(newPackage, true);
16675            }
16676            // Add back the old system package
16677            try {
16678                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16679            } catch (PackageManagerException e) {
16680                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16681            }
16682
16683            synchronized (mPackages) {
16684                if (disabledSystem) {
16685                    enableSystemPackageLPw(deletedPackage);
16686                }
16687
16688                // Ensure the installer package name up to date
16689                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16690
16691                // Update permissions for restored package
16692                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16693
16694                mSettings.writeLPr();
16695            }
16696
16697            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16698                    + " after failed upgrade");
16699        }
16700    }
16701
16702    /**
16703     * Checks whether the parent or any of the child packages have a change shared
16704     * user. For a package to be a valid update the shred users of the parent and
16705     * the children should match. We may later support changing child shared users.
16706     * @param oldPkg The updated package.
16707     * @param newPkg The update package.
16708     * @return The shared user that change between the versions.
16709     */
16710    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16711            PackageParser.Package newPkg) {
16712        // Check parent shared user
16713        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16714            return newPkg.packageName;
16715        }
16716        // Check child shared users
16717        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16718        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16719        for (int i = 0; i < newChildCount; i++) {
16720            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16721            // If this child was present, did it have the same shared user?
16722            for (int j = 0; j < oldChildCount; j++) {
16723                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16724                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16725                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16726                    return newChildPkg.packageName;
16727                }
16728            }
16729        }
16730        return null;
16731    }
16732
16733    private void removeNativeBinariesLI(PackageSetting ps) {
16734        // Remove the lib path for the parent package
16735        if (ps != null) {
16736            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16737            // Remove the lib path for the child packages
16738            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16739            for (int i = 0; i < childCount; i++) {
16740                PackageSetting childPs = null;
16741                synchronized (mPackages) {
16742                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16743                }
16744                if (childPs != null) {
16745                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16746                            .legacyNativeLibraryPathString);
16747                }
16748            }
16749        }
16750    }
16751
16752    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16753        // Enable the parent package
16754        mSettings.enableSystemPackageLPw(pkg.packageName);
16755        // Enable the child packages
16756        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16757        for (int i = 0; i < childCount; i++) {
16758            PackageParser.Package childPkg = pkg.childPackages.get(i);
16759            mSettings.enableSystemPackageLPw(childPkg.packageName);
16760        }
16761    }
16762
16763    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16764            PackageParser.Package newPkg) {
16765        // Disable the parent package (parent always replaced)
16766        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16767        // Disable the child packages
16768        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16769        for (int i = 0; i < childCount; i++) {
16770            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16771            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16772            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16773        }
16774        return disabled;
16775    }
16776
16777    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16778            String installerPackageName) {
16779        // Enable the parent package
16780        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16781        // Enable the child packages
16782        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16783        for (int i = 0; i < childCount; i++) {
16784            PackageParser.Package childPkg = pkg.childPackages.get(i);
16785            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16786        }
16787    }
16788
16789    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16790        // Collect all used permissions in the UID
16791        ArraySet<String> usedPermissions = new ArraySet<>();
16792        final int packageCount = su.packages.size();
16793        for (int i = 0; i < packageCount; i++) {
16794            PackageSetting ps = su.packages.valueAt(i);
16795            if (ps.pkg == null) {
16796                continue;
16797            }
16798            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16799            for (int j = 0; j < requestedPermCount; j++) {
16800                String permission = ps.pkg.requestedPermissions.get(j);
16801                BasePermission bp = mSettings.mPermissions.get(permission);
16802                if (bp != null) {
16803                    usedPermissions.add(permission);
16804                }
16805            }
16806        }
16807
16808        PermissionsState permissionsState = su.getPermissionsState();
16809        // Prune install permissions
16810        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16811        final int installPermCount = installPermStates.size();
16812        for (int i = installPermCount - 1; i >= 0;  i--) {
16813            PermissionState permissionState = installPermStates.get(i);
16814            if (!usedPermissions.contains(permissionState.getName())) {
16815                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16816                if (bp != null) {
16817                    permissionsState.revokeInstallPermission(bp);
16818                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16819                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16820                }
16821            }
16822        }
16823
16824        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16825
16826        // Prune runtime permissions
16827        for (int userId : allUserIds) {
16828            List<PermissionState> runtimePermStates = permissionsState
16829                    .getRuntimePermissionStates(userId);
16830            final int runtimePermCount = runtimePermStates.size();
16831            for (int i = runtimePermCount - 1; i >= 0; i--) {
16832                PermissionState permissionState = runtimePermStates.get(i);
16833                if (!usedPermissions.contains(permissionState.getName())) {
16834                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16835                    if (bp != null) {
16836                        permissionsState.revokeRuntimePermission(bp, userId);
16837                        permissionsState.updatePermissionFlags(bp, userId,
16838                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16839                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16840                                runtimePermissionChangedUserIds, userId);
16841                    }
16842                }
16843            }
16844        }
16845
16846        return runtimePermissionChangedUserIds;
16847    }
16848
16849    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16850            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16851        // Update the parent package setting
16852        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16853                res, user, installReason);
16854        // Update the child packages setting
16855        final int childCount = (newPackage.childPackages != null)
16856                ? newPackage.childPackages.size() : 0;
16857        for (int i = 0; i < childCount; i++) {
16858            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16859            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16860            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16861                    childRes.origUsers, childRes, user, installReason);
16862        }
16863    }
16864
16865    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16866            String installerPackageName, int[] allUsers, int[] installedForUsers,
16867            PackageInstalledInfo res, UserHandle user, int installReason) {
16868        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16869
16870        String pkgName = newPackage.packageName;
16871        synchronized (mPackages) {
16872            //write settings. the installStatus will be incomplete at this stage.
16873            //note that the new package setting would have already been
16874            //added to mPackages. It hasn't been persisted yet.
16875            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16876            // TODO: Remove this write? It's also written at the end of this method
16877            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16878            mSettings.writeLPr();
16879            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16880        }
16881
16882        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16883        synchronized (mPackages) {
16884            updatePermissionsLPw(newPackage.packageName, newPackage,
16885                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16886                            ? UPDATE_PERMISSIONS_ALL : 0));
16887            // For system-bundled packages, we assume that installing an upgraded version
16888            // of the package implies that the user actually wants to run that new code,
16889            // so we enable the package.
16890            PackageSetting ps = mSettings.mPackages.get(pkgName);
16891            final int userId = user.getIdentifier();
16892            if (ps != null) {
16893                if (isSystemApp(newPackage)) {
16894                    if (DEBUG_INSTALL) {
16895                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16896                    }
16897                    // Enable system package for requested users
16898                    if (res.origUsers != null) {
16899                        for (int origUserId : res.origUsers) {
16900                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16901                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16902                                        origUserId, installerPackageName);
16903                            }
16904                        }
16905                    }
16906                    // Also convey the prior install/uninstall state
16907                    if (allUsers != null && installedForUsers != null) {
16908                        for (int currentUserId : allUsers) {
16909                            final boolean installed = ArrayUtils.contains(
16910                                    installedForUsers, currentUserId);
16911                            if (DEBUG_INSTALL) {
16912                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16913                            }
16914                            ps.setInstalled(installed, currentUserId);
16915                        }
16916                        // these install state changes will be persisted in the
16917                        // upcoming call to mSettings.writeLPr().
16918                    }
16919                }
16920                // It's implied that when a user requests installation, they want the app to be
16921                // installed and enabled.
16922                if (userId != UserHandle.USER_ALL) {
16923                    ps.setInstalled(true, userId);
16924                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16925                }
16926
16927                // When replacing an existing package, preserve the original install reason for all
16928                // users that had the package installed before.
16929                final Set<Integer> previousUserIds = new ArraySet<>();
16930                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16931                    final int installReasonCount = res.removedInfo.installReasons.size();
16932                    for (int i = 0; i < installReasonCount; i++) {
16933                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16934                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16935                        ps.setInstallReason(previousInstallReason, previousUserId);
16936                        previousUserIds.add(previousUserId);
16937                    }
16938                }
16939
16940                // Set install reason for users that are having the package newly installed.
16941                if (userId == UserHandle.USER_ALL) {
16942                    for (int currentUserId : sUserManager.getUserIds()) {
16943                        if (!previousUserIds.contains(currentUserId)) {
16944                            ps.setInstallReason(installReason, currentUserId);
16945                        }
16946                    }
16947                } else if (!previousUserIds.contains(userId)) {
16948                    ps.setInstallReason(installReason, userId);
16949                }
16950                mSettings.writeKernelMappingLPr(ps);
16951            }
16952            res.name = pkgName;
16953            res.uid = newPackage.applicationInfo.uid;
16954            res.pkg = newPackage;
16955            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16956            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16957            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16958            //to update install status
16959            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16960            mSettings.writeLPr();
16961            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16962        }
16963
16964        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16965    }
16966
16967    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16968        try {
16969            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16970            installPackageLI(args, res);
16971        } finally {
16972            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16973        }
16974    }
16975
16976    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16977        final int installFlags = args.installFlags;
16978        final String installerPackageName = args.installerPackageName;
16979        final String volumeUuid = args.volumeUuid;
16980        final File tmpPackageFile = new File(args.getCodePath());
16981        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16982        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16983                || (args.volumeUuid != null));
16984        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16985        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16986        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16987        boolean replace = false;
16988        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16989        if (args.move != null) {
16990            // moving a complete application; perform an initial scan on the new install location
16991            scanFlags |= SCAN_INITIAL;
16992        }
16993        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16994            scanFlags |= SCAN_DONT_KILL_APP;
16995        }
16996        if (instantApp) {
16997            scanFlags |= SCAN_AS_INSTANT_APP;
16998        }
16999        if (fullApp) {
17000            scanFlags |= SCAN_AS_FULL_APP;
17001        }
17002
17003        // Result object to be returned
17004        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17005
17006        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17007
17008        // Sanity check
17009        if (instantApp && (forwardLocked || onExternal)) {
17010            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17011                    + " external=" + onExternal);
17012            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17013            return;
17014        }
17015
17016        // Retrieve PackageSettings and parse package
17017        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17018                | PackageParser.PARSE_ENFORCE_CODE
17019                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17020                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17021                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17022                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17023        PackageParser pp = new PackageParser();
17024        pp.setSeparateProcesses(mSeparateProcesses);
17025        pp.setDisplayMetrics(mMetrics);
17026        pp.setCallback(mPackageParserCallback);
17027
17028        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17029        final PackageParser.Package pkg;
17030        try {
17031            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17032        } catch (PackageParserException e) {
17033            res.setError("Failed parse during installPackageLI", e);
17034            return;
17035        } finally {
17036            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17037        }
17038
17039        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17040        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17041            Slog.w(TAG, "Instant app package " + pkg.packageName
17042                    + " does not target O, this will be a fatal error.");
17043            // STOPSHIP: Make this a fatal error
17044            pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O;
17045        }
17046        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17047            Slog.w(TAG, "Instant app package " + pkg.packageName
17048                    + " does not target targetSandboxVersion 2, this will be a fatal error.");
17049            // STOPSHIP: Make this a fatal error
17050            pkg.applicationInfo.targetSandboxVersion = 2;
17051        }
17052
17053        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17054            // Static shared libraries have synthetic package names
17055            renameStaticSharedLibraryPackage(pkg);
17056
17057            // No static shared libs on external storage
17058            if (onExternal) {
17059                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17060                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17061                        "Packages declaring static-shared libs cannot be updated");
17062                return;
17063            }
17064        }
17065
17066        // If we are installing a clustered package add results for the children
17067        if (pkg.childPackages != null) {
17068            synchronized (mPackages) {
17069                final int childCount = pkg.childPackages.size();
17070                for (int i = 0; i < childCount; i++) {
17071                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17072                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17073                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17074                    childRes.pkg = childPkg;
17075                    childRes.name = childPkg.packageName;
17076                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17077                    if (childPs != null) {
17078                        childRes.origUsers = childPs.queryInstalledUsers(
17079                                sUserManager.getUserIds(), true);
17080                    }
17081                    if ((mPackages.containsKey(childPkg.packageName))) {
17082                        childRes.removedInfo = new PackageRemovedInfo(this);
17083                        childRes.removedInfo.removedPackage = childPkg.packageName;
17084                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17085                    }
17086                    if (res.addedChildPackages == null) {
17087                        res.addedChildPackages = new ArrayMap<>();
17088                    }
17089                    res.addedChildPackages.put(childPkg.packageName, childRes);
17090                }
17091            }
17092        }
17093
17094        // If package doesn't declare API override, mark that we have an install
17095        // time CPU ABI override.
17096        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17097            pkg.cpuAbiOverride = args.abiOverride;
17098        }
17099
17100        String pkgName = res.name = pkg.packageName;
17101        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17102            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17103                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17104                return;
17105            }
17106        }
17107
17108        try {
17109            // either use what we've been given or parse directly from the APK
17110            if (args.certificates != null) {
17111                try {
17112                    PackageParser.populateCertificates(pkg, args.certificates);
17113                } catch (PackageParserException e) {
17114                    // there was something wrong with the certificates we were given;
17115                    // try to pull them from the APK
17116                    PackageParser.collectCertificates(pkg, parseFlags);
17117                }
17118            } else {
17119                PackageParser.collectCertificates(pkg, parseFlags);
17120            }
17121        } catch (PackageParserException e) {
17122            res.setError("Failed collect during installPackageLI", e);
17123            return;
17124        }
17125
17126        // Get rid of all references to package scan path via parser.
17127        pp = null;
17128        String oldCodePath = null;
17129        boolean systemApp = false;
17130        synchronized (mPackages) {
17131            // Check if installing already existing package
17132            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17133                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17134                if (pkg.mOriginalPackages != null
17135                        && pkg.mOriginalPackages.contains(oldName)
17136                        && mPackages.containsKey(oldName)) {
17137                    // This package is derived from an original package,
17138                    // and this device has been updating from that original
17139                    // name.  We must continue using the original name, so
17140                    // rename the new package here.
17141                    pkg.setPackageName(oldName);
17142                    pkgName = pkg.packageName;
17143                    replace = true;
17144                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17145                            + oldName + " pkgName=" + pkgName);
17146                } else if (mPackages.containsKey(pkgName)) {
17147                    // This package, under its official name, already exists
17148                    // on the device; we should replace it.
17149                    replace = true;
17150                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17151                }
17152
17153                // Child packages are installed through the parent package
17154                if (pkg.parentPackage != null) {
17155                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17156                            "Package " + pkg.packageName + " is child of package "
17157                                    + pkg.parentPackage.parentPackage + ". Child packages "
17158                                    + "can be updated only through the parent package.");
17159                    return;
17160                }
17161
17162                if (replace) {
17163                    // Prevent apps opting out from runtime permissions
17164                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17165                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17166                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17167                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17168                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17169                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17170                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17171                                        + " doesn't support runtime permissions but the old"
17172                                        + " target SDK " + oldTargetSdk + " does.");
17173                        return;
17174                    }
17175                    // Prevent apps from downgrading their targetSandbox.
17176                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17177                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17178                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17179                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17180                                "Package " + pkg.packageName + " new target sandbox "
17181                                + newTargetSandbox + " is incompatible with the previous value of"
17182                                + oldTargetSandbox + ".");
17183                        return;
17184                    }
17185
17186                    // Prevent installing of child packages
17187                    if (oldPackage.parentPackage != null) {
17188                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17189                                "Package " + pkg.packageName + " is child of package "
17190                                        + oldPackage.parentPackage + ". Child packages "
17191                                        + "can be updated only through the parent package.");
17192                        return;
17193                    }
17194                }
17195            }
17196
17197            PackageSetting ps = mSettings.mPackages.get(pkgName);
17198            if (ps != null) {
17199                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17200
17201                // Static shared libs have same package with different versions where
17202                // we internally use a synthetic package name to allow multiple versions
17203                // of the same package, therefore we need to compare signatures against
17204                // the package setting for the latest library version.
17205                PackageSetting signatureCheckPs = ps;
17206                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17207                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17208                    if (libraryEntry != null) {
17209                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17210                    }
17211                }
17212
17213                // Quick sanity check that we're signed correctly if updating;
17214                // we'll check this again later when scanning, but we want to
17215                // bail early here before tripping over redefined permissions.
17216                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
17217                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
17218                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17219                                + pkg.packageName + " upgrade keys do not match the "
17220                                + "previously installed version");
17221                        return;
17222                    }
17223                } else {
17224                    try {
17225                        verifySignaturesLP(signatureCheckPs, pkg);
17226                    } catch (PackageManagerException e) {
17227                        res.setError(e.error, e.getMessage());
17228                        return;
17229                    }
17230                }
17231
17232                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17233                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17234                    systemApp = (ps.pkg.applicationInfo.flags &
17235                            ApplicationInfo.FLAG_SYSTEM) != 0;
17236                }
17237                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17238            }
17239
17240            int N = pkg.permissions.size();
17241            for (int i = N-1; i >= 0; i--) {
17242                PackageParser.Permission perm = pkg.permissions.get(i);
17243                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
17244
17245                // Don't allow anyone but the system to define ephemeral permissions.
17246                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
17247                        && !systemApp) {
17248                    Slog.w(TAG, "Non-System package " + pkg.packageName
17249                            + " attempting to delcare ephemeral permission "
17250                            + perm.info.name + "; Removing ephemeral.");
17251                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
17252                }
17253                // Check whether the newly-scanned package wants to define an already-defined perm
17254                if (bp != null) {
17255                    // If the defining package is signed with our cert, it's okay.  This
17256                    // also includes the "updating the same package" case, of course.
17257                    // "updating same package" could also involve key-rotation.
17258                    final boolean sigsOk;
17259                    if (bp.sourcePackage.equals(pkg.packageName)
17260                            && (bp.packageSetting instanceof PackageSetting)
17261                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
17262                                    scanFlags))) {
17263                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
17264                    } else {
17265                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
17266                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
17267                    }
17268                    if (!sigsOk) {
17269                        // If the owning package is the system itself, we log but allow
17270                        // install to proceed; we fail the install on all other permission
17271                        // redefinitions.
17272                        if (!bp.sourcePackage.equals("android")) {
17273                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17274                                    + pkg.packageName + " attempting to redeclare permission "
17275                                    + perm.info.name + " already owned by " + bp.sourcePackage);
17276                            res.origPermission = perm.info.name;
17277                            res.origPackage = bp.sourcePackage;
17278                            return;
17279                        } else {
17280                            Slog.w(TAG, "Package " + pkg.packageName
17281                                    + " attempting to redeclare system permission "
17282                                    + perm.info.name + "; ignoring new declaration");
17283                            pkg.permissions.remove(i);
17284                        }
17285                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17286                        // Prevent apps to change protection level to dangerous from any other
17287                        // type as this would allow a privilege escalation where an app adds a
17288                        // normal/signature permission in other app's group and later redefines
17289                        // it as dangerous leading to the group auto-grant.
17290                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17291                                == PermissionInfo.PROTECTION_DANGEROUS) {
17292                            if (bp != null && !bp.isRuntime()) {
17293                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17294                                        + "non-runtime permission " + perm.info.name
17295                                        + " to runtime; keeping old protection level");
17296                                perm.info.protectionLevel = bp.protectionLevel;
17297                            }
17298                        }
17299                    }
17300                }
17301            }
17302        }
17303
17304        if (systemApp) {
17305            if (onExternal) {
17306                // Abort update; system app can't be replaced with app on sdcard
17307                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17308                        "Cannot install updates to system apps on sdcard");
17309                return;
17310            } else if (instantApp) {
17311                // Abort update; system app can't be replaced with an instant app
17312                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17313                        "Cannot update a system app with an instant app");
17314                return;
17315            }
17316        }
17317
17318        if (args.move != null) {
17319            // We did an in-place move, so dex is ready to roll
17320            scanFlags |= SCAN_NO_DEX;
17321            scanFlags |= SCAN_MOVE;
17322
17323            synchronized (mPackages) {
17324                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17325                if (ps == null) {
17326                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17327                            "Missing settings for moved package " + pkgName);
17328                }
17329
17330                // We moved the entire application as-is, so bring over the
17331                // previously derived ABI information.
17332                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17333                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17334            }
17335
17336        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17337            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17338            scanFlags |= SCAN_NO_DEX;
17339
17340            try {
17341                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17342                    args.abiOverride : pkg.cpuAbiOverride);
17343                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
17344                        true /*extractLibs*/, mAppLib32InstallDir);
17345            } catch (PackageManagerException pme) {
17346                Slog.e(TAG, "Error deriving application ABI", pme);
17347                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17348                return;
17349            }
17350
17351            // Shared libraries for the package need to be updated.
17352            synchronized (mPackages) {
17353                try {
17354                    updateSharedLibrariesLPr(pkg, null);
17355                } catch (PackageManagerException e) {
17356                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17357                }
17358            }
17359
17360            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17361            // Do not run PackageDexOptimizer through the local performDexOpt
17362            // method because `pkg` may not be in `mPackages` yet.
17363            //
17364            // Also, don't fail application installs if the dexopt step fails.
17365            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17366                    null /* instructionSets */, false /* checkProfiles */,
17367                    getCompilerFilterForReason(REASON_INSTALL),
17368                    getOrCreateCompilerPackageStats(pkg),
17369                    mDexManager.isUsedByOtherApps(pkg.packageName));
17370            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17371
17372            // Notify BackgroundDexOptService that the package has been changed.
17373            // If this is an update of a package which used to fail to compile,
17374            // BDOS will remove it from its blacklist.
17375            // TODO: Layering violation
17376            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17377        }
17378
17379        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17380            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17381            return;
17382        }
17383
17384        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17385
17386        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17387                "installPackageLI")) {
17388            if (replace) {
17389                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17390                    // Static libs have a synthetic package name containing the version
17391                    // and cannot be updated as an update would get a new package name,
17392                    // unless this is the exact same version code which is useful for
17393                    // development.
17394                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17395                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
17396                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17397                                + "static-shared libs cannot be updated");
17398                        return;
17399                    }
17400                }
17401                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
17402                        installerPackageName, res, args.installReason);
17403            } else {
17404                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17405                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17406            }
17407        }
17408
17409        synchronized (mPackages) {
17410            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17411            if (ps != null) {
17412                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17413                ps.setUpdateAvailable(false /*updateAvailable*/);
17414            }
17415
17416            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17417            for (int i = 0; i < childCount; i++) {
17418                PackageParser.Package childPkg = pkg.childPackages.get(i);
17419                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17420                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17421                if (childPs != null) {
17422                    childRes.newUsers = childPs.queryInstalledUsers(
17423                            sUserManager.getUserIds(), true);
17424                }
17425            }
17426
17427            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17428                updateSequenceNumberLP(pkgName, res.newUsers);
17429                updateInstantAppInstallerLocked(pkgName);
17430            }
17431        }
17432    }
17433
17434    private void startIntentFilterVerifications(int userId, boolean replacing,
17435            PackageParser.Package pkg) {
17436        if (mIntentFilterVerifierComponent == null) {
17437            Slog.w(TAG, "No IntentFilter verification will not be done as "
17438                    + "there is no IntentFilterVerifier available!");
17439            return;
17440        }
17441
17442        final int verifierUid = getPackageUid(
17443                mIntentFilterVerifierComponent.getPackageName(),
17444                MATCH_DEBUG_TRIAGED_MISSING,
17445                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17446
17447        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17448        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17449        mHandler.sendMessage(msg);
17450
17451        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17452        for (int i = 0; i < childCount; i++) {
17453            PackageParser.Package childPkg = pkg.childPackages.get(i);
17454            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17455            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17456            mHandler.sendMessage(msg);
17457        }
17458    }
17459
17460    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17461            PackageParser.Package pkg) {
17462        int size = pkg.activities.size();
17463        if (size == 0) {
17464            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17465                    "No activity, so no need to verify any IntentFilter!");
17466            return;
17467        }
17468
17469        final boolean hasDomainURLs = hasDomainURLs(pkg);
17470        if (!hasDomainURLs) {
17471            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17472                    "No domain URLs, so no need to verify any IntentFilter!");
17473            return;
17474        }
17475
17476        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17477                + " if any IntentFilter from the " + size
17478                + " Activities needs verification ...");
17479
17480        int count = 0;
17481        final String packageName = pkg.packageName;
17482
17483        synchronized (mPackages) {
17484            // If this is a new install and we see that we've already run verification for this
17485            // package, we have nothing to do: it means the state was restored from backup.
17486            if (!replacing) {
17487                IntentFilterVerificationInfo ivi =
17488                        mSettings.getIntentFilterVerificationLPr(packageName);
17489                if (ivi != null) {
17490                    if (DEBUG_DOMAIN_VERIFICATION) {
17491                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17492                                + ivi.getStatusString());
17493                    }
17494                    return;
17495                }
17496            }
17497
17498            // If any filters need to be verified, then all need to be.
17499            boolean needToVerify = false;
17500            for (PackageParser.Activity a : pkg.activities) {
17501                for (ActivityIntentInfo filter : a.intents) {
17502                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17503                        if (DEBUG_DOMAIN_VERIFICATION) {
17504                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
17505                        }
17506                        needToVerify = true;
17507                        break;
17508                    }
17509                }
17510            }
17511
17512            if (needToVerify) {
17513                final int verificationId = mIntentFilterVerificationToken++;
17514                for (PackageParser.Activity a : pkg.activities) {
17515                    for (ActivityIntentInfo filter : a.intents) {
17516                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17517                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17518                                    "Verification needed for IntentFilter:" + filter.toString());
17519                            mIntentFilterVerifier.addOneIntentFilterVerification(
17520                                    verifierUid, userId, verificationId, filter, packageName);
17521                            count++;
17522                        }
17523                    }
17524                }
17525            }
17526        }
17527
17528        if (count > 0) {
17529            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17530                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17531                    +  " for userId:" + userId);
17532            mIntentFilterVerifier.startVerifications(userId);
17533        } else {
17534            if (DEBUG_DOMAIN_VERIFICATION) {
17535                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17536            }
17537        }
17538    }
17539
17540    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17541        final ComponentName cn  = filter.activity.getComponentName();
17542        final String packageName = cn.getPackageName();
17543
17544        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17545                packageName);
17546        if (ivi == null) {
17547            return true;
17548        }
17549        int status = ivi.getStatus();
17550        switch (status) {
17551            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17552            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17553                return true;
17554
17555            default:
17556                // Nothing to do
17557                return false;
17558        }
17559    }
17560
17561    private static boolean isMultiArch(ApplicationInfo info) {
17562        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17563    }
17564
17565    private static boolean isExternal(PackageParser.Package pkg) {
17566        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17567    }
17568
17569    private static boolean isExternal(PackageSetting ps) {
17570        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17571    }
17572
17573    private static boolean isSystemApp(PackageParser.Package pkg) {
17574        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17575    }
17576
17577    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17578        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17579    }
17580
17581    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17582        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17583    }
17584
17585    private static boolean isSystemApp(PackageSetting ps) {
17586        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17587    }
17588
17589    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17590        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17591    }
17592
17593    private int packageFlagsToInstallFlags(PackageSetting ps) {
17594        int installFlags = 0;
17595        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17596            // This existing package was an external ASEC install when we have
17597            // the external flag without a UUID
17598            installFlags |= PackageManager.INSTALL_EXTERNAL;
17599        }
17600        if (ps.isForwardLocked()) {
17601            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17602        }
17603        return installFlags;
17604    }
17605
17606    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17607        if (isExternal(pkg)) {
17608            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17609                return StorageManager.UUID_PRIMARY_PHYSICAL;
17610            } else {
17611                return pkg.volumeUuid;
17612            }
17613        } else {
17614            return StorageManager.UUID_PRIVATE_INTERNAL;
17615        }
17616    }
17617
17618    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17619        if (isExternal(pkg)) {
17620            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17621                return mSettings.getExternalVersion();
17622            } else {
17623                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17624            }
17625        } else {
17626            return mSettings.getInternalVersion();
17627        }
17628    }
17629
17630    private void deleteTempPackageFiles() {
17631        final FilenameFilter filter = new FilenameFilter() {
17632            public boolean accept(File dir, String name) {
17633                return name.startsWith("vmdl") && name.endsWith(".tmp");
17634            }
17635        };
17636        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17637            file.delete();
17638        }
17639    }
17640
17641    @Override
17642    public void deletePackageAsUser(String packageName, int versionCode,
17643            IPackageDeleteObserver observer, int userId, int flags) {
17644        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17645                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17646    }
17647
17648    @Override
17649    public void deletePackageVersioned(VersionedPackage versionedPackage,
17650            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17651        mContext.enforceCallingOrSelfPermission(
17652                android.Manifest.permission.DELETE_PACKAGES, null);
17653        Preconditions.checkNotNull(versionedPackage);
17654        Preconditions.checkNotNull(observer);
17655        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17656                PackageManager.VERSION_CODE_HIGHEST,
17657                Integer.MAX_VALUE, "versionCode must be >= -1");
17658
17659        final String packageName = versionedPackage.getPackageName();
17660        // TODO: We will change version code to long, so in the new API it is long
17661        final int versionCode = (int) versionedPackage.getVersionCode();
17662        final String internalPackageName;
17663        synchronized (mPackages) {
17664            // Normalize package name to handle renamed packages and static libs
17665            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17666                    // TODO: We will change version code to long, so in the new API it is long
17667                    (int) versionedPackage.getVersionCode());
17668        }
17669
17670        final int uid = Binder.getCallingUid();
17671        if (!isOrphaned(internalPackageName)
17672                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17673            try {
17674                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17675                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17676                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17677                observer.onUserActionRequired(intent);
17678            } catch (RemoteException re) {
17679            }
17680            return;
17681        }
17682        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17683        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17684        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17685            mContext.enforceCallingOrSelfPermission(
17686                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17687                    "deletePackage for user " + userId);
17688        }
17689
17690        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17691            try {
17692                observer.onPackageDeleted(packageName,
17693                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17694            } catch (RemoteException re) {
17695            }
17696            return;
17697        }
17698
17699        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17700            try {
17701                observer.onPackageDeleted(packageName,
17702                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17703            } catch (RemoteException re) {
17704            }
17705            return;
17706        }
17707
17708        if (DEBUG_REMOVE) {
17709            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17710                    + " deleteAllUsers: " + deleteAllUsers + " version="
17711                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17712                    ? "VERSION_CODE_HIGHEST" : versionCode));
17713        }
17714        // Queue up an async operation since the package deletion may take a little while.
17715        mHandler.post(new Runnable() {
17716            public void run() {
17717                mHandler.removeCallbacks(this);
17718                int returnCode;
17719                if (!deleteAllUsers) {
17720                    returnCode = deletePackageX(internalPackageName, versionCode,
17721                            userId, deleteFlags);
17722                } else {
17723                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17724                            internalPackageName, users);
17725                    // If nobody is blocking uninstall, proceed with delete for all users
17726                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17727                        returnCode = deletePackageX(internalPackageName, versionCode,
17728                                userId, deleteFlags);
17729                    } else {
17730                        // Otherwise uninstall individually for users with blockUninstalls=false
17731                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17732                        for (int userId : users) {
17733                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17734                                returnCode = deletePackageX(internalPackageName, versionCode,
17735                                        userId, userFlags);
17736                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17737                                    Slog.w(TAG, "Package delete failed for user " + userId
17738                                            + ", returnCode " + returnCode);
17739                                }
17740                            }
17741                        }
17742                        // The app has only been marked uninstalled for certain users.
17743                        // We still need to report that delete was blocked
17744                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17745                    }
17746                }
17747                try {
17748                    observer.onPackageDeleted(packageName, returnCode, null);
17749                } catch (RemoteException e) {
17750                    Log.i(TAG, "Observer no longer exists.");
17751                } //end catch
17752            } //end run
17753        });
17754    }
17755
17756    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17757        if (pkg.staticSharedLibName != null) {
17758            return pkg.manifestPackageName;
17759        }
17760        return pkg.packageName;
17761    }
17762
17763    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17764        // Handle renamed packages
17765        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17766        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17767
17768        // Is this a static library?
17769        SparseArray<SharedLibraryEntry> versionedLib =
17770                mStaticLibsByDeclaringPackage.get(packageName);
17771        if (versionedLib == null || versionedLib.size() <= 0) {
17772            return packageName;
17773        }
17774
17775        // Figure out which lib versions the caller can see
17776        SparseIntArray versionsCallerCanSee = null;
17777        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17778        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17779                && callingAppId != Process.ROOT_UID) {
17780            versionsCallerCanSee = new SparseIntArray();
17781            String libName = versionedLib.valueAt(0).info.getName();
17782            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17783            if (uidPackages != null) {
17784                for (String uidPackage : uidPackages) {
17785                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17786                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17787                    if (libIdx >= 0) {
17788                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17789                        versionsCallerCanSee.append(libVersion, libVersion);
17790                    }
17791                }
17792            }
17793        }
17794
17795        // Caller can see nothing - done
17796        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17797            return packageName;
17798        }
17799
17800        // Find the version the caller can see and the app version code
17801        SharedLibraryEntry highestVersion = null;
17802        final int versionCount = versionedLib.size();
17803        for (int i = 0; i < versionCount; i++) {
17804            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17805            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17806                    libEntry.info.getVersion()) < 0) {
17807                continue;
17808            }
17809            // TODO: We will change version code to long, so in the new API it is long
17810            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17811            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17812                if (libVersionCode == versionCode) {
17813                    return libEntry.apk;
17814                }
17815            } else if (highestVersion == null) {
17816                highestVersion = libEntry;
17817            } else if (libVersionCode  > highestVersion.info
17818                    .getDeclaringPackage().getVersionCode()) {
17819                highestVersion = libEntry;
17820            }
17821        }
17822
17823        if (highestVersion != null) {
17824            return highestVersion.apk;
17825        }
17826
17827        return packageName;
17828    }
17829
17830    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17831        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17832              || callingUid == Process.SYSTEM_UID) {
17833            return true;
17834        }
17835        final int callingUserId = UserHandle.getUserId(callingUid);
17836        // If the caller installed the pkgName, then allow it to silently uninstall.
17837        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17838            return true;
17839        }
17840
17841        // Allow package verifier to silently uninstall.
17842        if (mRequiredVerifierPackage != null &&
17843                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17844            return true;
17845        }
17846
17847        // Allow package uninstaller to silently uninstall.
17848        if (mRequiredUninstallerPackage != null &&
17849                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17850            return true;
17851        }
17852
17853        // Allow storage manager to silently uninstall.
17854        if (mStorageManagerPackage != null &&
17855                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17856            return true;
17857        }
17858        return false;
17859    }
17860
17861    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17862        int[] result = EMPTY_INT_ARRAY;
17863        for (int userId : userIds) {
17864            if (getBlockUninstallForUser(packageName, userId)) {
17865                result = ArrayUtils.appendInt(result, userId);
17866            }
17867        }
17868        return result;
17869    }
17870
17871    @Override
17872    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17873        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17874    }
17875
17876    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17877        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17878                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17879        try {
17880            if (dpm != null) {
17881                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17882                        /* callingUserOnly =*/ false);
17883                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17884                        : deviceOwnerComponentName.getPackageName();
17885                // Does the package contains the device owner?
17886                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17887                // this check is probably not needed, since DO should be registered as a device
17888                // admin on some user too. (Original bug for this: b/17657954)
17889                if (packageName.equals(deviceOwnerPackageName)) {
17890                    return true;
17891                }
17892                // Does it contain a device admin for any user?
17893                int[] users;
17894                if (userId == UserHandle.USER_ALL) {
17895                    users = sUserManager.getUserIds();
17896                } else {
17897                    users = new int[]{userId};
17898                }
17899                for (int i = 0; i < users.length; ++i) {
17900                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17901                        return true;
17902                    }
17903                }
17904            }
17905        } catch (RemoteException e) {
17906        }
17907        return false;
17908    }
17909
17910    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17911        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17912    }
17913
17914    /**
17915     *  This method is an internal method that could be get invoked either
17916     *  to delete an installed package or to clean up a failed installation.
17917     *  After deleting an installed package, a broadcast is sent to notify any
17918     *  listeners that the package has been removed. For cleaning up a failed
17919     *  installation, the broadcast is not necessary since the package's
17920     *  installation wouldn't have sent the initial broadcast either
17921     *  The key steps in deleting a package are
17922     *  deleting the package information in internal structures like mPackages,
17923     *  deleting the packages base directories through installd
17924     *  updating mSettings to reflect current status
17925     *  persisting settings for later use
17926     *  sending a broadcast if necessary
17927     */
17928    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17929        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17930        final boolean res;
17931
17932        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17933                ? UserHandle.USER_ALL : userId;
17934
17935        if (isPackageDeviceAdmin(packageName, removeUser)) {
17936            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17937            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17938        }
17939
17940        PackageSetting uninstalledPs = null;
17941        PackageParser.Package pkg = null;
17942
17943        // for the uninstall-updates case and restricted profiles, remember the per-
17944        // user handle installed state
17945        int[] allUsers;
17946        synchronized (mPackages) {
17947            uninstalledPs = mSettings.mPackages.get(packageName);
17948            if (uninstalledPs == null) {
17949                Slog.w(TAG, "Not removing non-existent package " + packageName);
17950                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17951            }
17952
17953            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17954                    && uninstalledPs.versionCode != versionCode) {
17955                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17956                        + uninstalledPs.versionCode + " != " + versionCode);
17957                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17958            }
17959
17960            // Static shared libs can be declared by any package, so let us not
17961            // allow removing a package if it provides a lib others depend on.
17962            pkg = mPackages.get(packageName);
17963            if (pkg != null && pkg.staticSharedLibName != null) {
17964                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17965                        pkg.staticSharedLibVersion);
17966                if (libEntry != null) {
17967                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17968                            libEntry.info, 0, userId);
17969                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17970                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17971                                + " hosting lib " + libEntry.info.getName() + " version "
17972                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17973                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17974                    }
17975                }
17976            }
17977
17978            allUsers = sUserManager.getUserIds();
17979            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17980        }
17981
17982        final int freezeUser;
17983        if (isUpdatedSystemApp(uninstalledPs)
17984                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17985            // We're downgrading a system app, which will apply to all users, so
17986            // freeze them all during the downgrade
17987            freezeUser = UserHandle.USER_ALL;
17988        } else {
17989            freezeUser = removeUser;
17990        }
17991
17992        synchronized (mInstallLock) {
17993            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17994            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17995                    deleteFlags, "deletePackageX")) {
17996                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17997                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
17998            }
17999            synchronized (mPackages) {
18000                if (res) {
18001                    if (pkg != null) {
18002                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18003                    }
18004                    updateSequenceNumberLP(packageName, info.removedUsers);
18005                    updateInstantAppInstallerLocked(packageName);
18006                }
18007            }
18008        }
18009
18010        if (res) {
18011            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18012            info.sendPackageRemovedBroadcasts(killApp);
18013            info.sendSystemPackageUpdatedBroadcasts();
18014            info.sendSystemPackageAppearedBroadcasts();
18015        }
18016        // Force a gc here.
18017        Runtime.getRuntime().gc();
18018        // Delete the resources here after sending the broadcast to let
18019        // other processes clean up before deleting resources.
18020        if (info.args != null) {
18021            synchronized (mInstallLock) {
18022                info.args.doPostDeleteLI(true);
18023            }
18024        }
18025
18026        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18027    }
18028
18029    static class PackageRemovedInfo {
18030        final PackageSender packageSender;
18031        String removedPackage;
18032        String installerPackageName;
18033        int uid = -1;
18034        int removedAppId = -1;
18035        int[] origUsers;
18036        int[] removedUsers = null;
18037        int[] broadcastUsers = null;
18038        SparseArray<Integer> installReasons;
18039        boolean isRemovedPackageSystemUpdate = false;
18040        boolean isUpdate;
18041        boolean dataRemoved;
18042        boolean removedForAllUsers;
18043        boolean isStaticSharedLib;
18044        // Clean up resources deleted packages.
18045        InstallArgs args = null;
18046        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18047        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18048
18049        PackageRemovedInfo(PackageSender packageSender) {
18050            this.packageSender = packageSender;
18051        }
18052
18053        void sendPackageRemovedBroadcasts(boolean killApp) {
18054            sendPackageRemovedBroadcastInternal(killApp);
18055            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18056            for (int i = 0; i < childCount; i++) {
18057                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18058                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18059            }
18060        }
18061
18062        void sendSystemPackageUpdatedBroadcasts() {
18063            if (isRemovedPackageSystemUpdate) {
18064                sendSystemPackageUpdatedBroadcastsInternal();
18065                final int childCount = (removedChildPackages != null)
18066                        ? removedChildPackages.size() : 0;
18067                for (int i = 0; i < childCount; i++) {
18068                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18069                    if (childInfo.isRemovedPackageSystemUpdate) {
18070                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18071                    }
18072                }
18073            }
18074        }
18075
18076        void sendSystemPackageAppearedBroadcasts() {
18077            final int packageCount = (appearedChildPackages != null)
18078                    ? appearedChildPackages.size() : 0;
18079            for (int i = 0; i < packageCount; i++) {
18080                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18081                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18082                    true, UserHandle.getAppId(installedInfo.uid),
18083                    installedInfo.newUsers);
18084            }
18085        }
18086
18087        private void sendSystemPackageUpdatedBroadcastsInternal() {
18088            Bundle extras = new Bundle(2);
18089            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18090            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18091            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18092                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18093            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18094                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18095            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18096                null, null, 0, removedPackage, null, null);
18097            if (installerPackageName != null) {
18098                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18099                        removedPackage, extras, 0 /*flags*/,
18100                        installerPackageName, null, null);
18101                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18102                        removedPackage, extras, 0 /*flags*/,
18103                        installerPackageName, null, null);
18104            }
18105        }
18106
18107        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18108            // Don't send static shared library removal broadcasts as these
18109            // libs are visible only the the apps that depend on them an one
18110            // cannot remove the library if it has a dependency.
18111            if (isStaticSharedLib) {
18112                return;
18113            }
18114            Bundle extras = new Bundle(2);
18115            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18116            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18117            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18118            if (isUpdate || isRemovedPackageSystemUpdate) {
18119                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18120            }
18121            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18122            if (removedPackage != null) {
18123                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18124                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
18125                if (installerPackageName != null) {
18126                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18127                            removedPackage, extras, 0 /*flags*/,
18128                            installerPackageName, null, broadcastUsers);
18129                }
18130                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18131                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18132                        removedPackage, extras,
18133                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18134                        null, null, broadcastUsers);
18135                }
18136            }
18137            if (removedAppId >= 0) {
18138                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras,
18139                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, null, null, broadcastUsers);
18140            }
18141        }
18142
18143        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18144            removedUsers = userIds;
18145            if (removedUsers == null) {
18146                broadcastUsers = null;
18147                return;
18148            }
18149
18150            broadcastUsers = EMPTY_INT_ARRAY;
18151            for (int i = userIds.length - 1; i >= 0; --i) {
18152                final int userId = userIds[i];
18153                if (deletedPackageSetting.getInstantApp(userId)) {
18154                    continue;
18155                }
18156                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18157            }
18158        }
18159    }
18160
18161    /*
18162     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18163     * flag is not set, the data directory is removed as well.
18164     * make sure this flag is set for partially installed apps. If not its meaningless to
18165     * delete a partially installed application.
18166     */
18167    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18168            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18169        String packageName = ps.name;
18170        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18171        // Retrieve object to delete permissions for shared user later on
18172        final PackageParser.Package deletedPkg;
18173        final PackageSetting deletedPs;
18174        // reader
18175        synchronized (mPackages) {
18176            deletedPkg = mPackages.get(packageName);
18177            deletedPs = mSettings.mPackages.get(packageName);
18178            if (outInfo != null) {
18179                outInfo.removedPackage = packageName;
18180                outInfo.installerPackageName = ps.installerPackageName;
18181                outInfo.isStaticSharedLib = deletedPkg != null
18182                        && deletedPkg.staticSharedLibName != null;
18183                outInfo.populateUsers(deletedPs == null ? null
18184                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18185            }
18186        }
18187
18188        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
18189
18190        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18191            final PackageParser.Package resolvedPkg;
18192            if (deletedPkg != null) {
18193                resolvedPkg = deletedPkg;
18194            } else {
18195                // We don't have a parsed package when it lives on an ejected
18196                // adopted storage device, so fake something together
18197                resolvedPkg = new PackageParser.Package(ps.name);
18198                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18199            }
18200            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18201                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18202            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18203            if (outInfo != null) {
18204                outInfo.dataRemoved = true;
18205            }
18206            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18207        }
18208
18209        int removedAppId = -1;
18210
18211        // writer
18212        synchronized (mPackages) {
18213            boolean installedStateChanged = false;
18214            if (deletedPs != null) {
18215                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18216                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18217                    clearDefaultBrowserIfNeeded(packageName);
18218                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18219                    removedAppId = mSettings.removePackageLPw(packageName);
18220                    if (outInfo != null) {
18221                        outInfo.removedAppId = removedAppId;
18222                    }
18223                    updatePermissionsLPw(deletedPs.name, null, 0);
18224                    if (deletedPs.sharedUser != null) {
18225                        // Remove permissions associated with package. Since runtime
18226                        // permissions are per user we have to kill the removed package
18227                        // or packages running under the shared user of the removed
18228                        // package if revoking the permissions requested only by the removed
18229                        // package is successful and this causes a change in gids.
18230                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18231                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18232                                    userId);
18233                            if (userIdToKill == UserHandle.USER_ALL
18234                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18235                                // If gids changed for this user, kill all affected packages.
18236                                mHandler.post(new Runnable() {
18237                                    @Override
18238                                    public void run() {
18239                                        // This has to happen with no lock held.
18240                                        killApplication(deletedPs.name, deletedPs.appId,
18241                                                KILL_APP_REASON_GIDS_CHANGED);
18242                                    }
18243                                });
18244                                break;
18245                            }
18246                        }
18247                    }
18248                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18249                }
18250                // make sure to preserve per-user disabled state if this removal was just
18251                // a downgrade of a system app to the factory package
18252                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18253                    if (DEBUG_REMOVE) {
18254                        Slog.d(TAG, "Propagating install state across downgrade");
18255                    }
18256                    for (int userId : allUserHandles) {
18257                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18258                        if (DEBUG_REMOVE) {
18259                            Slog.d(TAG, "    user " + userId + " => " + installed);
18260                        }
18261                        if (installed != ps.getInstalled(userId)) {
18262                            installedStateChanged = true;
18263                        }
18264                        ps.setInstalled(installed, userId);
18265                    }
18266                }
18267            }
18268            // can downgrade to reader
18269            if (writeSettings) {
18270                // Save settings now
18271                mSettings.writeLPr();
18272            }
18273            if (installedStateChanged) {
18274                mSettings.writeKernelMappingLPr(ps);
18275            }
18276        }
18277        if (removedAppId != -1) {
18278            // A user ID was deleted here. Go through all users and remove it
18279            // from KeyStore.
18280            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18281        }
18282    }
18283
18284    static boolean locationIsPrivileged(File path) {
18285        try {
18286            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
18287                    .getCanonicalPath();
18288            return path.getCanonicalPath().startsWith(privilegedAppDir);
18289        } catch (IOException e) {
18290            Slog.e(TAG, "Unable to access code path " + path);
18291        }
18292        return false;
18293    }
18294
18295    /*
18296     * Tries to delete system package.
18297     */
18298    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18299            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18300            boolean writeSettings) {
18301        if (deletedPs.parentPackageName != null) {
18302            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18303            return false;
18304        }
18305
18306        final boolean applyUserRestrictions
18307                = (allUserHandles != null) && (outInfo.origUsers != null);
18308        final PackageSetting disabledPs;
18309        // Confirm if the system package has been updated
18310        // An updated system app can be deleted. This will also have to restore
18311        // the system pkg from system partition
18312        // reader
18313        synchronized (mPackages) {
18314            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18315        }
18316
18317        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18318                + " disabledPs=" + disabledPs);
18319
18320        if (disabledPs == null) {
18321            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18322            return false;
18323        } else if (DEBUG_REMOVE) {
18324            Slog.d(TAG, "Deleting system pkg from data partition");
18325        }
18326
18327        if (DEBUG_REMOVE) {
18328            if (applyUserRestrictions) {
18329                Slog.d(TAG, "Remembering install states:");
18330                for (int userId : allUserHandles) {
18331                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18332                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18333                }
18334            }
18335        }
18336
18337        // Delete the updated package
18338        outInfo.isRemovedPackageSystemUpdate = true;
18339        if (outInfo.removedChildPackages != null) {
18340            final int childCount = (deletedPs.childPackageNames != null)
18341                    ? deletedPs.childPackageNames.size() : 0;
18342            for (int i = 0; i < childCount; i++) {
18343                String childPackageName = deletedPs.childPackageNames.get(i);
18344                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18345                        .contains(childPackageName)) {
18346                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18347                            childPackageName);
18348                    if (childInfo != null) {
18349                        childInfo.isRemovedPackageSystemUpdate = true;
18350                    }
18351                }
18352            }
18353        }
18354
18355        if (disabledPs.versionCode < deletedPs.versionCode) {
18356            // Delete data for downgrades
18357            flags &= ~PackageManager.DELETE_KEEP_DATA;
18358        } else {
18359            // Preserve data by setting flag
18360            flags |= PackageManager.DELETE_KEEP_DATA;
18361        }
18362
18363        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18364                outInfo, writeSettings, disabledPs.pkg);
18365        if (!ret) {
18366            return false;
18367        }
18368
18369        // writer
18370        synchronized (mPackages) {
18371            // Reinstate the old system package
18372            enableSystemPackageLPw(disabledPs.pkg);
18373            // Remove any native libraries from the upgraded package.
18374            removeNativeBinariesLI(deletedPs);
18375        }
18376
18377        // Install the system package
18378        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18379        int parseFlags = mDefParseFlags
18380                | PackageParser.PARSE_MUST_BE_APK
18381                | PackageParser.PARSE_IS_SYSTEM
18382                | PackageParser.PARSE_IS_SYSTEM_DIR;
18383        if (locationIsPrivileged(disabledPs.codePath)) {
18384            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
18385        }
18386
18387        final PackageParser.Package newPkg;
18388        try {
18389            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
18390                0 /* currentTime */, null);
18391        } catch (PackageManagerException e) {
18392            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18393                    + e.getMessage());
18394            return false;
18395        }
18396
18397        try {
18398            // update shared libraries for the newly re-installed system package
18399            updateSharedLibrariesLPr(newPkg, null);
18400        } catch (PackageManagerException e) {
18401            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18402        }
18403
18404        prepareAppDataAfterInstallLIF(newPkg);
18405
18406        // writer
18407        synchronized (mPackages) {
18408            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
18409
18410            // Propagate the permissions state as we do not want to drop on the floor
18411            // runtime permissions. The update permissions method below will take
18412            // care of removing obsolete permissions and grant install permissions.
18413            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
18414            updatePermissionsLPw(newPkg.packageName, newPkg,
18415                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
18416
18417            if (applyUserRestrictions) {
18418                boolean installedStateChanged = false;
18419                if (DEBUG_REMOVE) {
18420                    Slog.d(TAG, "Propagating install state across reinstall");
18421                }
18422                for (int userId : allUserHandles) {
18423                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18424                    if (DEBUG_REMOVE) {
18425                        Slog.d(TAG, "    user " + userId + " => " + installed);
18426                    }
18427                    if (installed != ps.getInstalled(userId)) {
18428                        installedStateChanged = true;
18429                    }
18430                    ps.setInstalled(installed, userId);
18431
18432                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18433                }
18434                // Regardless of writeSettings we need to ensure that this restriction
18435                // state propagation is persisted
18436                mSettings.writeAllUsersPackageRestrictionsLPr();
18437                if (installedStateChanged) {
18438                    mSettings.writeKernelMappingLPr(ps);
18439                }
18440            }
18441            // can downgrade to reader here
18442            if (writeSettings) {
18443                mSettings.writeLPr();
18444            }
18445        }
18446        return true;
18447    }
18448
18449    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18450            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18451            PackageRemovedInfo outInfo, boolean writeSettings,
18452            PackageParser.Package replacingPackage) {
18453        synchronized (mPackages) {
18454            if (outInfo != null) {
18455                outInfo.uid = ps.appId;
18456            }
18457
18458            if (outInfo != null && outInfo.removedChildPackages != null) {
18459                final int childCount = (ps.childPackageNames != null)
18460                        ? ps.childPackageNames.size() : 0;
18461                for (int i = 0; i < childCount; i++) {
18462                    String childPackageName = ps.childPackageNames.get(i);
18463                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18464                    if (childPs == null) {
18465                        return false;
18466                    }
18467                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18468                            childPackageName);
18469                    if (childInfo != null) {
18470                        childInfo.uid = childPs.appId;
18471                    }
18472                }
18473            }
18474        }
18475
18476        // Delete package data from internal structures and also remove data if flag is set
18477        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18478
18479        // Delete the child packages data
18480        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18481        for (int i = 0; i < childCount; i++) {
18482            PackageSetting childPs;
18483            synchronized (mPackages) {
18484                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18485            }
18486            if (childPs != null) {
18487                PackageRemovedInfo childOutInfo = (outInfo != null
18488                        && outInfo.removedChildPackages != null)
18489                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18490                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18491                        && (replacingPackage != null
18492                        && !replacingPackage.hasChildPackage(childPs.name))
18493                        ? flags & ~DELETE_KEEP_DATA : flags;
18494                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18495                        deleteFlags, writeSettings);
18496            }
18497        }
18498
18499        // Delete application code and resources only for parent packages
18500        if (ps.parentPackageName == null) {
18501            if (deleteCodeAndResources && (outInfo != null)) {
18502                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18503                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18504                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18505            }
18506        }
18507
18508        return true;
18509    }
18510
18511    @Override
18512    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18513            int userId) {
18514        mContext.enforceCallingOrSelfPermission(
18515                android.Manifest.permission.DELETE_PACKAGES, null);
18516        synchronized (mPackages) {
18517            PackageSetting ps = mSettings.mPackages.get(packageName);
18518            if (ps == null) {
18519                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
18520                return false;
18521            }
18522            // Cannot block uninstall of static shared libs as they are
18523            // considered a part of the using app (emulating static linking).
18524            // Also static libs are installed always on internal storage.
18525            PackageParser.Package pkg = mPackages.get(packageName);
18526            if (pkg != null && pkg.staticSharedLibName != null) {
18527                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18528                        + " providing static shared library: " + pkg.staticSharedLibName);
18529                return false;
18530            }
18531            if (!ps.getInstalled(userId)) {
18532                // Can't block uninstall for an app that is not installed or enabled.
18533                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
18534                return false;
18535            }
18536            ps.setBlockUninstall(blockUninstall, userId);
18537            mSettings.writePackageRestrictionsLPr(userId);
18538        }
18539        return true;
18540    }
18541
18542    @Override
18543    public boolean getBlockUninstallForUser(String packageName, int userId) {
18544        synchronized (mPackages) {
18545            PackageSetting ps = mSettings.mPackages.get(packageName);
18546            if (ps == null) {
18547                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
18548                return false;
18549            }
18550            return ps.getBlockUninstall(userId);
18551        }
18552    }
18553
18554    @Override
18555    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18556        int callingUid = Binder.getCallingUid();
18557        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
18558            throw new SecurityException(
18559                    "setRequiredForSystemUser can only be run by the system or root");
18560        }
18561        synchronized (mPackages) {
18562            PackageSetting ps = mSettings.mPackages.get(packageName);
18563            if (ps == null) {
18564                Log.w(TAG, "Package doesn't exist: " + packageName);
18565                return false;
18566            }
18567            if (systemUserApp) {
18568                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18569            } else {
18570                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18571            }
18572            mSettings.writeLPr();
18573        }
18574        return true;
18575    }
18576
18577    /*
18578     * This method handles package deletion in general
18579     */
18580    private boolean deletePackageLIF(String packageName, UserHandle user,
18581            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18582            PackageRemovedInfo outInfo, boolean writeSettings,
18583            PackageParser.Package replacingPackage) {
18584        if (packageName == null) {
18585            Slog.w(TAG, "Attempt to delete null packageName.");
18586            return false;
18587        }
18588
18589        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18590
18591        PackageSetting ps;
18592        synchronized (mPackages) {
18593            ps = mSettings.mPackages.get(packageName);
18594            if (ps == null) {
18595                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18596                return false;
18597            }
18598
18599            if (ps.parentPackageName != null && (!isSystemApp(ps)
18600                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18601                if (DEBUG_REMOVE) {
18602                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18603                            + ((user == null) ? UserHandle.USER_ALL : user));
18604                }
18605                final int removedUserId = (user != null) ? user.getIdentifier()
18606                        : UserHandle.USER_ALL;
18607                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18608                    return false;
18609                }
18610                markPackageUninstalledForUserLPw(ps, user);
18611                scheduleWritePackageRestrictionsLocked(user);
18612                return true;
18613            }
18614        }
18615
18616        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18617                && user.getIdentifier() != UserHandle.USER_ALL)) {
18618            // The caller is asking that the package only be deleted for a single
18619            // user.  To do this, we just mark its uninstalled state and delete
18620            // its data. If this is a system app, we only allow this to happen if
18621            // they have set the special DELETE_SYSTEM_APP which requests different
18622            // semantics than normal for uninstalling system apps.
18623            markPackageUninstalledForUserLPw(ps, user);
18624
18625            if (!isSystemApp(ps)) {
18626                // Do not uninstall the APK if an app should be cached
18627                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18628                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18629                    // Other user still have this package installed, so all
18630                    // we need to do is clear this user's data and save that
18631                    // it is uninstalled.
18632                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18633                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18634                        return false;
18635                    }
18636                    scheduleWritePackageRestrictionsLocked(user);
18637                    return true;
18638                } else {
18639                    // We need to set it back to 'installed' so the uninstall
18640                    // broadcasts will be sent correctly.
18641                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18642                    ps.setInstalled(true, user.getIdentifier());
18643                    mSettings.writeKernelMappingLPr(ps);
18644                }
18645            } else {
18646                // This is a system app, so we assume that the
18647                // other users still have this package installed, so all
18648                // we need to do is clear this user's data and save that
18649                // it is uninstalled.
18650                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18651                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18652                    return false;
18653                }
18654                scheduleWritePackageRestrictionsLocked(user);
18655                return true;
18656            }
18657        }
18658
18659        // If we are deleting a composite package for all users, keep track
18660        // of result for each child.
18661        if (ps.childPackageNames != null && outInfo != null) {
18662            synchronized (mPackages) {
18663                final int childCount = ps.childPackageNames.size();
18664                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18665                for (int i = 0; i < childCount; i++) {
18666                    String childPackageName = ps.childPackageNames.get(i);
18667                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18668                    childInfo.removedPackage = childPackageName;
18669                    childInfo.installerPackageName = ps.installerPackageName;
18670                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18671                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18672                    if (childPs != null) {
18673                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18674                    }
18675                }
18676            }
18677        }
18678
18679        boolean ret = false;
18680        if (isSystemApp(ps)) {
18681            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18682            // When an updated system application is deleted we delete the existing resources
18683            // as well and fall back to existing code in system partition
18684            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18685        } else {
18686            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18687            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18688                    outInfo, writeSettings, replacingPackage);
18689        }
18690
18691        // Take a note whether we deleted the package for all users
18692        if (outInfo != null) {
18693            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18694            if (outInfo.removedChildPackages != null) {
18695                synchronized (mPackages) {
18696                    final int childCount = outInfo.removedChildPackages.size();
18697                    for (int i = 0; i < childCount; i++) {
18698                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18699                        if (childInfo != null) {
18700                            childInfo.removedForAllUsers = mPackages.get(
18701                                    childInfo.removedPackage) == null;
18702                        }
18703                    }
18704                }
18705            }
18706            // If we uninstalled an update to a system app there may be some
18707            // child packages that appeared as they are declared in the system
18708            // app but were not declared in the update.
18709            if (isSystemApp(ps)) {
18710                synchronized (mPackages) {
18711                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18712                    final int childCount = (updatedPs.childPackageNames != null)
18713                            ? updatedPs.childPackageNames.size() : 0;
18714                    for (int i = 0; i < childCount; i++) {
18715                        String childPackageName = updatedPs.childPackageNames.get(i);
18716                        if (outInfo.removedChildPackages == null
18717                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18718                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18719                            if (childPs == null) {
18720                                continue;
18721                            }
18722                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18723                            installRes.name = childPackageName;
18724                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18725                            installRes.pkg = mPackages.get(childPackageName);
18726                            installRes.uid = childPs.pkg.applicationInfo.uid;
18727                            if (outInfo.appearedChildPackages == null) {
18728                                outInfo.appearedChildPackages = new ArrayMap<>();
18729                            }
18730                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18731                        }
18732                    }
18733                }
18734            }
18735        }
18736
18737        return ret;
18738    }
18739
18740    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18741        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18742                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18743        for (int nextUserId : userIds) {
18744            if (DEBUG_REMOVE) {
18745                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18746            }
18747            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18748                    false /*installed*/,
18749                    true /*stopped*/,
18750                    true /*notLaunched*/,
18751                    false /*hidden*/,
18752                    false /*suspended*/,
18753                    false /*instantApp*/,
18754                    null /*lastDisableAppCaller*/,
18755                    null /*enabledComponents*/,
18756                    null /*disabledComponents*/,
18757                    false /*blockUninstall*/,
18758                    ps.readUserState(nextUserId).domainVerificationStatus,
18759                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18760        }
18761        mSettings.writeKernelMappingLPr(ps);
18762    }
18763
18764    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18765            PackageRemovedInfo outInfo) {
18766        final PackageParser.Package pkg;
18767        synchronized (mPackages) {
18768            pkg = mPackages.get(ps.name);
18769        }
18770
18771        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18772                : new int[] {userId};
18773        for (int nextUserId : userIds) {
18774            if (DEBUG_REMOVE) {
18775                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18776                        + nextUserId);
18777            }
18778
18779            destroyAppDataLIF(pkg, userId,
18780                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18781            destroyAppProfilesLIF(pkg, userId);
18782            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18783            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18784            schedulePackageCleaning(ps.name, nextUserId, false);
18785            synchronized (mPackages) {
18786                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18787                    scheduleWritePackageRestrictionsLocked(nextUserId);
18788                }
18789                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18790            }
18791        }
18792
18793        if (outInfo != null) {
18794            outInfo.removedPackage = ps.name;
18795            outInfo.installerPackageName = ps.installerPackageName;
18796            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18797            outInfo.removedAppId = ps.appId;
18798            outInfo.removedUsers = userIds;
18799            outInfo.broadcastUsers = userIds;
18800        }
18801
18802        return true;
18803    }
18804
18805    private final class ClearStorageConnection implements ServiceConnection {
18806        IMediaContainerService mContainerService;
18807
18808        @Override
18809        public void onServiceConnected(ComponentName name, IBinder service) {
18810            synchronized (this) {
18811                mContainerService = IMediaContainerService.Stub
18812                        .asInterface(Binder.allowBlocking(service));
18813                notifyAll();
18814            }
18815        }
18816
18817        @Override
18818        public void onServiceDisconnected(ComponentName name) {
18819        }
18820    }
18821
18822    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18823        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18824
18825        final boolean mounted;
18826        if (Environment.isExternalStorageEmulated()) {
18827            mounted = true;
18828        } else {
18829            final String status = Environment.getExternalStorageState();
18830
18831            mounted = status.equals(Environment.MEDIA_MOUNTED)
18832                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18833        }
18834
18835        if (!mounted) {
18836            return;
18837        }
18838
18839        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18840        int[] users;
18841        if (userId == UserHandle.USER_ALL) {
18842            users = sUserManager.getUserIds();
18843        } else {
18844            users = new int[] { userId };
18845        }
18846        final ClearStorageConnection conn = new ClearStorageConnection();
18847        if (mContext.bindServiceAsUser(
18848                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18849            try {
18850                for (int curUser : users) {
18851                    long timeout = SystemClock.uptimeMillis() + 5000;
18852                    synchronized (conn) {
18853                        long now;
18854                        while (conn.mContainerService == null &&
18855                                (now = SystemClock.uptimeMillis()) < timeout) {
18856                            try {
18857                                conn.wait(timeout - now);
18858                            } catch (InterruptedException e) {
18859                            }
18860                        }
18861                    }
18862                    if (conn.mContainerService == null) {
18863                        return;
18864                    }
18865
18866                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18867                    clearDirectory(conn.mContainerService,
18868                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18869                    if (allData) {
18870                        clearDirectory(conn.mContainerService,
18871                                userEnv.buildExternalStorageAppDataDirs(packageName));
18872                        clearDirectory(conn.mContainerService,
18873                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18874                    }
18875                }
18876            } finally {
18877                mContext.unbindService(conn);
18878            }
18879        }
18880    }
18881
18882    @Override
18883    public void clearApplicationProfileData(String packageName) {
18884        enforceSystemOrRoot("Only the system can clear all profile data");
18885
18886        final PackageParser.Package pkg;
18887        synchronized (mPackages) {
18888            pkg = mPackages.get(packageName);
18889        }
18890
18891        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18892            synchronized (mInstallLock) {
18893                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18894            }
18895        }
18896    }
18897
18898    @Override
18899    public void clearApplicationUserData(final String packageName,
18900            final IPackageDataObserver observer, final int userId) {
18901        mContext.enforceCallingOrSelfPermission(
18902                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18903
18904        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18905                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18906
18907        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18908            throw new SecurityException("Cannot clear data for a protected package: "
18909                    + packageName);
18910        }
18911        // Queue up an async operation since the package deletion may take a little while.
18912        mHandler.post(new Runnable() {
18913            public void run() {
18914                mHandler.removeCallbacks(this);
18915                final boolean succeeded;
18916                try (PackageFreezer freezer = freezePackage(packageName,
18917                        "clearApplicationUserData")) {
18918                    synchronized (mInstallLock) {
18919                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18920                    }
18921                    clearExternalStorageDataSync(packageName, userId, true);
18922                    synchronized (mPackages) {
18923                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18924                                packageName, userId);
18925                    }
18926                }
18927                if (succeeded) {
18928                    // invoke DeviceStorageMonitor's update method to clear any notifications
18929                    DeviceStorageMonitorInternal dsm = LocalServices
18930                            .getService(DeviceStorageMonitorInternal.class);
18931                    if (dsm != null) {
18932                        dsm.checkMemory();
18933                    }
18934                }
18935                if(observer != null) {
18936                    try {
18937                        observer.onRemoveCompleted(packageName, succeeded);
18938                    } catch (RemoteException e) {
18939                        Log.i(TAG, "Observer no longer exists.");
18940                    }
18941                } //end if observer
18942            } //end run
18943        });
18944    }
18945
18946    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18947        if (packageName == null) {
18948            Slog.w(TAG, "Attempt to delete null packageName.");
18949            return false;
18950        }
18951
18952        // Try finding details about the requested package
18953        PackageParser.Package pkg;
18954        synchronized (mPackages) {
18955            pkg = mPackages.get(packageName);
18956            if (pkg == null) {
18957                final PackageSetting ps = mSettings.mPackages.get(packageName);
18958                if (ps != null) {
18959                    pkg = ps.pkg;
18960                }
18961            }
18962
18963            if (pkg == null) {
18964                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18965                return false;
18966            }
18967
18968            PackageSetting ps = (PackageSetting) pkg.mExtras;
18969            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18970        }
18971
18972        clearAppDataLIF(pkg, userId,
18973                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18974
18975        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18976        removeKeystoreDataIfNeeded(userId, appId);
18977
18978        UserManagerInternal umInternal = getUserManagerInternal();
18979        final int flags;
18980        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18981            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18982        } else if (umInternal.isUserRunning(userId)) {
18983            flags = StorageManager.FLAG_STORAGE_DE;
18984        } else {
18985            flags = 0;
18986        }
18987        prepareAppDataContentsLIF(pkg, userId, flags);
18988
18989        return true;
18990    }
18991
18992    /**
18993     * Reverts user permission state changes (permissions and flags) in
18994     * all packages for a given user.
18995     *
18996     * @param userId The device user for which to do a reset.
18997     */
18998    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18999        final int packageCount = mPackages.size();
19000        for (int i = 0; i < packageCount; i++) {
19001            PackageParser.Package pkg = mPackages.valueAt(i);
19002            PackageSetting ps = (PackageSetting) pkg.mExtras;
19003            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19004        }
19005    }
19006
19007    private void resetNetworkPolicies(int userId) {
19008        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19009    }
19010
19011    /**
19012     * Reverts user permission state changes (permissions and flags).
19013     *
19014     * @param ps The package for which to reset.
19015     * @param userId The device user for which to do a reset.
19016     */
19017    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19018            final PackageSetting ps, final int userId) {
19019        if (ps.pkg == null) {
19020            return;
19021        }
19022
19023        // These are flags that can change base on user actions.
19024        final int userSettableMask = FLAG_PERMISSION_USER_SET
19025                | FLAG_PERMISSION_USER_FIXED
19026                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19027                | FLAG_PERMISSION_REVIEW_REQUIRED;
19028
19029        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19030                | FLAG_PERMISSION_POLICY_FIXED;
19031
19032        boolean writeInstallPermissions = false;
19033        boolean writeRuntimePermissions = false;
19034
19035        final int permissionCount = ps.pkg.requestedPermissions.size();
19036        for (int i = 0; i < permissionCount; i++) {
19037            String permission = ps.pkg.requestedPermissions.get(i);
19038
19039            BasePermission bp = mSettings.mPermissions.get(permission);
19040            if (bp == null) {
19041                continue;
19042            }
19043
19044            // If shared user we just reset the state to which only this app contributed.
19045            if (ps.sharedUser != null) {
19046                boolean used = false;
19047                final int packageCount = ps.sharedUser.packages.size();
19048                for (int j = 0; j < packageCount; j++) {
19049                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19050                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19051                            && pkg.pkg.requestedPermissions.contains(permission)) {
19052                        used = true;
19053                        break;
19054                    }
19055                }
19056                if (used) {
19057                    continue;
19058                }
19059            }
19060
19061            PermissionsState permissionsState = ps.getPermissionsState();
19062
19063            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
19064
19065            // Always clear the user settable flags.
19066            final boolean hasInstallState = permissionsState.getInstallPermissionState(
19067                    bp.name) != null;
19068            // If permission review is enabled and this is a legacy app, mark the
19069            // permission as requiring a review as this is the initial state.
19070            int flags = 0;
19071            if (mPermissionReviewRequired
19072                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19073                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19074            }
19075            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19076                if (hasInstallState) {
19077                    writeInstallPermissions = true;
19078                } else {
19079                    writeRuntimePermissions = true;
19080                }
19081            }
19082
19083            // Below is only runtime permission handling.
19084            if (!bp.isRuntime()) {
19085                continue;
19086            }
19087
19088            // Never clobber system or policy.
19089            if ((oldFlags & policyOrSystemFlags) != 0) {
19090                continue;
19091            }
19092
19093            // If this permission was granted by default, make sure it is.
19094            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19095                if (permissionsState.grantRuntimePermission(bp, userId)
19096                        != PERMISSION_OPERATION_FAILURE) {
19097                    writeRuntimePermissions = true;
19098                }
19099            // If permission review is enabled the permissions for a legacy apps
19100            // are represented as constantly granted runtime ones, so don't revoke.
19101            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19102                // Otherwise, reset the permission.
19103                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19104                switch (revokeResult) {
19105                    case PERMISSION_OPERATION_SUCCESS:
19106                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19107                        writeRuntimePermissions = true;
19108                        final int appId = ps.appId;
19109                        mHandler.post(new Runnable() {
19110                            @Override
19111                            public void run() {
19112                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19113                            }
19114                        });
19115                    } break;
19116                }
19117            }
19118        }
19119
19120        // Synchronously write as we are taking permissions away.
19121        if (writeRuntimePermissions) {
19122            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19123        }
19124
19125        // Synchronously write as we are taking permissions away.
19126        if (writeInstallPermissions) {
19127            mSettings.writeLPr();
19128        }
19129    }
19130
19131    /**
19132     * Remove entries from the keystore daemon. Will only remove it if the
19133     * {@code appId} is valid.
19134     */
19135    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19136        if (appId < 0) {
19137            return;
19138        }
19139
19140        final KeyStore keyStore = KeyStore.getInstance();
19141        if (keyStore != null) {
19142            if (userId == UserHandle.USER_ALL) {
19143                for (final int individual : sUserManager.getUserIds()) {
19144                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19145                }
19146            } else {
19147                keyStore.clearUid(UserHandle.getUid(userId, appId));
19148            }
19149        } else {
19150            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19151        }
19152    }
19153
19154    @Override
19155    public void deleteApplicationCacheFiles(final String packageName,
19156            final IPackageDataObserver observer) {
19157        final int userId = UserHandle.getCallingUserId();
19158        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19159    }
19160
19161    @Override
19162    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19163            final IPackageDataObserver observer) {
19164        mContext.enforceCallingOrSelfPermission(
19165                android.Manifest.permission.DELETE_CACHE_FILES, null);
19166        enforceCrossUserPermission(Binder.getCallingUid(), userId,
19167                /* requireFullPermission= */ true, /* checkShell= */ false,
19168                "delete application cache files");
19169
19170        final PackageParser.Package pkg;
19171        synchronized (mPackages) {
19172            pkg = mPackages.get(packageName);
19173        }
19174
19175        // Queue up an async operation since the package deletion may take a little while.
19176        mHandler.post(new Runnable() {
19177            public void run() {
19178                synchronized (mInstallLock) {
19179                    final int flags = StorageManager.FLAG_STORAGE_DE
19180                            | StorageManager.FLAG_STORAGE_CE;
19181                    // We're only clearing cache files, so we don't care if the
19182                    // app is unfrozen and still able to run
19183                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19184                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19185                }
19186                clearExternalStorageDataSync(packageName, userId, false);
19187                if (observer != null) {
19188                    try {
19189                        observer.onRemoveCompleted(packageName, true);
19190                    } catch (RemoteException e) {
19191                        Log.i(TAG, "Observer no longer exists.");
19192                    }
19193                }
19194            }
19195        });
19196    }
19197
19198    @Override
19199    public void getPackageSizeInfo(final String packageName, int userHandle,
19200            final IPackageStatsObserver observer) {
19201        throw new UnsupportedOperationException(
19202                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19203    }
19204
19205    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19206        final PackageSetting ps;
19207        synchronized (mPackages) {
19208            ps = mSettings.mPackages.get(packageName);
19209            if (ps == null) {
19210                Slog.w(TAG, "Failed to find settings for " + packageName);
19211                return false;
19212            }
19213        }
19214
19215        final String[] packageNames = { packageName };
19216        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19217        final String[] codePaths = { ps.codePathString };
19218
19219        try {
19220            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19221                    ps.appId, ceDataInodes, codePaths, stats);
19222
19223            // For now, ignore code size of packages on system partition
19224            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19225                stats.codeSize = 0;
19226            }
19227
19228            // External clients expect these to be tracked separately
19229            stats.dataSize -= stats.cacheSize;
19230
19231        } catch (InstallerException e) {
19232            Slog.w(TAG, String.valueOf(e));
19233            return false;
19234        }
19235
19236        return true;
19237    }
19238
19239    private int getUidTargetSdkVersionLockedLPr(int uid) {
19240        Object obj = mSettings.getUserIdLPr(uid);
19241        if (obj instanceof SharedUserSetting) {
19242            final SharedUserSetting sus = (SharedUserSetting) obj;
19243            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19244            final Iterator<PackageSetting> it = sus.packages.iterator();
19245            while (it.hasNext()) {
19246                final PackageSetting ps = it.next();
19247                if (ps.pkg != null) {
19248                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19249                    if (v < vers) vers = v;
19250                }
19251            }
19252            return vers;
19253        } else if (obj instanceof PackageSetting) {
19254            final PackageSetting ps = (PackageSetting) obj;
19255            if (ps.pkg != null) {
19256                return ps.pkg.applicationInfo.targetSdkVersion;
19257            }
19258        }
19259        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19260    }
19261
19262    @Override
19263    public void addPreferredActivity(IntentFilter filter, int match,
19264            ComponentName[] set, ComponentName activity, int userId) {
19265        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19266                "Adding preferred");
19267    }
19268
19269    private void addPreferredActivityInternal(IntentFilter filter, int match,
19270            ComponentName[] set, ComponentName activity, boolean always, int userId,
19271            String opname) {
19272        // writer
19273        int callingUid = Binder.getCallingUid();
19274        enforceCrossUserPermission(callingUid, userId,
19275                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19276        if (filter.countActions() == 0) {
19277            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19278            return;
19279        }
19280        synchronized (mPackages) {
19281            if (mContext.checkCallingOrSelfPermission(
19282                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19283                    != PackageManager.PERMISSION_GRANTED) {
19284                if (getUidTargetSdkVersionLockedLPr(callingUid)
19285                        < Build.VERSION_CODES.FROYO) {
19286                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19287                            + callingUid);
19288                    return;
19289                }
19290                mContext.enforceCallingOrSelfPermission(
19291                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19292            }
19293
19294            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19295            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19296                    + userId + ":");
19297            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19298            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19299            scheduleWritePackageRestrictionsLocked(userId);
19300            postPreferredActivityChangedBroadcast(userId);
19301        }
19302    }
19303
19304    private void postPreferredActivityChangedBroadcast(int userId) {
19305        mHandler.post(() -> {
19306            final IActivityManager am = ActivityManager.getService();
19307            if (am == null) {
19308                return;
19309            }
19310
19311            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19312            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19313            try {
19314                am.broadcastIntent(null, intent, null, null,
19315                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19316                        null, false, false, userId);
19317            } catch (RemoteException e) {
19318            }
19319        });
19320    }
19321
19322    @Override
19323    public void replacePreferredActivity(IntentFilter filter, int match,
19324            ComponentName[] set, ComponentName activity, int userId) {
19325        if (filter.countActions() != 1) {
19326            throw new IllegalArgumentException(
19327                    "replacePreferredActivity expects filter to have only 1 action.");
19328        }
19329        if (filter.countDataAuthorities() != 0
19330                || filter.countDataPaths() != 0
19331                || filter.countDataSchemes() > 1
19332                || filter.countDataTypes() != 0) {
19333            throw new IllegalArgumentException(
19334                    "replacePreferredActivity expects filter to have no data authorities, " +
19335                    "paths, or types; and at most one scheme.");
19336        }
19337
19338        final int callingUid = Binder.getCallingUid();
19339        enforceCrossUserPermission(callingUid, userId,
19340                true /* requireFullPermission */, false /* checkShell */,
19341                "replace preferred activity");
19342        synchronized (mPackages) {
19343            if (mContext.checkCallingOrSelfPermission(
19344                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19345                    != PackageManager.PERMISSION_GRANTED) {
19346                if (getUidTargetSdkVersionLockedLPr(callingUid)
19347                        < Build.VERSION_CODES.FROYO) {
19348                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19349                            + Binder.getCallingUid());
19350                    return;
19351                }
19352                mContext.enforceCallingOrSelfPermission(
19353                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19354            }
19355
19356            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19357            if (pir != null) {
19358                // Get all of the existing entries that exactly match this filter.
19359                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19360                if (existing != null && existing.size() == 1) {
19361                    PreferredActivity cur = existing.get(0);
19362                    if (DEBUG_PREFERRED) {
19363                        Slog.i(TAG, "Checking replace of preferred:");
19364                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19365                        if (!cur.mPref.mAlways) {
19366                            Slog.i(TAG, "  -- CUR; not mAlways!");
19367                        } else {
19368                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19369                            Slog.i(TAG, "  -- CUR: mSet="
19370                                    + Arrays.toString(cur.mPref.mSetComponents));
19371                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19372                            Slog.i(TAG, "  -- NEW: mMatch="
19373                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19374                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19375                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19376                        }
19377                    }
19378                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19379                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19380                            && cur.mPref.sameSet(set)) {
19381                        // Setting the preferred activity to what it happens to be already
19382                        if (DEBUG_PREFERRED) {
19383                            Slog.i(TAG, "Replacing with same preferred activity "
19384                                    + cur.mPref.mShortComponent + " for user "
19385                                    + userId + ":");
19386                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19387                        }
19388                        return;
19389                    }
19390                }
19391
19392                if (existing != null) {
19393                    if (DEBUG_PREFERRED) {
19394                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19395                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19396                    }
19397                    for (int i = 0; i < existing.size(); i++) {
19398                        PreferredActivity pa = existing.get(i);
19399                        if (DEBUG_PREFERRED) {
19400                            Slog.i(TAG, "Removing existing preferred activity "
19401                                    + pa.mPref.mComponent + ":");
19402                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19403                        }
19404                        pir.removeFilter(pa);
19405                    }
19406                }
19407            }
19408            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19409                    "Replacing preferred");
19410        }
19411    }
19412
19413    @Override
19414    public void clearPackagePreferredActivities(String packageName) {
19415        final int uid = Binder.getCallingUid();
19416        // writer
19417        synchronized (mPackages) {
19418            PackageParser.Package pkg = mPackages.get(packageName);
19419            if (pkg == null || pkg.applicationInfo.uid != uid) {
19420                if (mContext.checkCallingOrSelfPermission(
19421                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19422                        != PackageManager.PERMISSION_GRANTED) {
19423                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
19424                            < Build.VERSION_CODES.FROYO) {
19425                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19426                                + Binder.getCallingUid());
19427                        return;
19428                    }
19429                    mContext.enforceCallingOrSelfPermission(
19430                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19431                }
19432            }
19433
19434            int user = UserHandle.getCallingUserId();
19435            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19436                scheduleWritePackageRestrictionsLocked(user);
19437            }
19438        }
19439    }
19440
19441    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19442    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19443        ArrayList<PreferredActivity> removed = null;
19444        boolean changed = false;
19445        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19446            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19447            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19448            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19449                continue;
19450            }
19451            Iterator<PreferredActivity> it = pir.filterIterator();
19452            while (it.hasNext()) {
19453                PreferredActivity pa = it.next();
19454                // Mark entry for removal only if it matches the package name
19455                // and the entry is of type "always".
19456                if (packageName == null ||
19457                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19458                                && pa.mPref.mAlways)) {
19459                    if (removed == null) {
19460                        removed = new ArrayList<PreferredActivity>();
19461                    }
19462                    removed.add(pa);
19463                }
19464            }
19465            if (removed != null) {
19466                for (int j=0; j<removed.size(); j++) {
19467                    PreferredActivity pa = removed.get(j);
19468                    pir.removeFilter(pa);
19469                }
19470                changed = true;
19471            }
19472        }
19473        if (changed) {
19474            postPreferredActivityChangedBroadcast(userId);
19475        }
19476        return changed;
19477    }
19478
19479    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19480    private void clearIntentFilterVerificationsLPw(int userId) {
19481        final int packageCount = mPackages.size();
19482        for (int i = 0; i < packageCount; i++) {
19483            PackageParser.Package pkg = mPackages.valueAt(i);
19484            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19485        }
19486    }
19487
19488    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19489    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19490        if (userId == UserHandle.USER_ALL) {
19491            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19492                    sUserManager.getUserIds())) {
19493                for (int oneUserId : sUserManager.getUserIds()) {
19494                    scheduleWritePackageRestrictionsLocked(oneUserId);
19495                }
19496            }
19497        } else {
19498            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19499                scheduleWritePackageRestrictionsLocked(userId);
19500            }
19501        }
19502    }
19503
19504    /** Clears state for all users, and touches intent filter verification policy */
19505    void clearDefaultBrowserIfNeeded(String packageName) {
19506        for (int oneUserId : sUserManager.getUserIds()) {
19507            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19508        }
19509    }
19510
19511    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19512        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19513        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19514            if (packageName.equals(defaultBrowserPackageName)) {
19515                setDefaultBrowserPackageName(null, userId);
19516            }
19517        }
19518    }
19519
19520    @Override
19521    public void resetApplicationPreferences(int userId) {
19522        mContext.enforceCallingOrSelfPermission(
19523                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19524        final long identity = Binder.clearCallingIdentity();
19525        // writer
19526        try {
19527            synchronized (mPackages) {
19528                clearPackagePreferredActivitiesLPw(null, userId);
19529                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19530                // TODO: We have to reset the default SMS and Phone. This requires
19531                // significant refactoring to keep all default apps in the package
19532                // manager (cleaner but more work) or have the services provide
19533                // callbacks to the package manager to request a default app reset.
19534                applyFactoryDefaultBrowserLPw(userId);
19535                clearIntentFilterVerificationsLPw(userId);
19536                primeDomainVerificationsLPw(userId);
19537                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19538                scheduleWritePackageRestrictionsLocked(userId);
19539            }
19540            resetNetworkPolicies(userId);
19541        } finally {
19542            Binder.restoreCallingIdentity(identity);
19543        }
19544    }
19545
19546    @Override
19547    public int getPreferredActivities(List<IntentFilter> outFilters,
19548            List<ComponentName> outActivities, String packageName) {
19549
19550        int num = 0;
19551        final int userId = UserHandle.getCallingUserId();
19552        // reader
19553        synchronized (mPackages) {
19554            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19555            if (pir != null) {
19556                final Iterator<PreferredActivity> it = pir.filterIterator();
19557                while (it.hasNext()) {
19558                    final PreferredActivity pa = it.next();
19559                    if (packageName == null
19560                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19561                                    && pa.mPref.mAlways)) {
19562                        if (outFilters != null) {
19563                            outFilters.add(new IntentFilter(pa));
19564                        }
19565                        if (outActivities != null) {
19566                            outActivities.add(pa.mPref.mComponent);
19567                        }
19568                    }
19569                }
19570            }
19571        }
19572
19573        return num;
19574    }
19575
19576    @Override
19577    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19578            int userId) {
19579        int callingUid = Binder.getCallingUid();
19580        if (callingUid != Process.SYSTEM_UID) {
19581            throw new SecurityException(
19582                    "addPersistentPreferredActivity can only be run by the system");
19583        }
19584        if (filter.countActions() == 0) {
19585            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19586            return;
19587        }
19588        synchronized (mPackages) {
19589            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19590                    ":");
19591            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19592            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19593                    new PersistentPreferredActivity(filter, activity));
19594            scheduleWritePackageRestrictionsLocked(userId);
19595            postPreferredActivityChangedBroadcast(userId);
19596        }
19597    }
19598
19599    @Override
19600    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19601        int callingUid = Binder.getCallingUid();
19602        if (callingUid != Process.SYSTEM_UID) {
19603            throw new SecurityException(
19604                    "clearPackagePersistentPreferredActivities can only be run by the system");
19605        }
19606        ArrayList<PersistentPreferredActivity> removed = null;
19607        boolean changed = false;
19608        synchronized (mPackages) {
19609            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19610                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19611                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19612                        .valueAt(i);
19613                if (userId != thisUserId) {
19614                    continue;
19615                }
19616                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19617                while (it.hasNext()) {
19618                    PersistentPreferredActivity ppa = it.next();
19619                    // Mark entry for removal only if it matches the package name.
19620                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19621                        if (removed == null) {
19622                            removed = new ArrayList<PersistentPreferredActivity>();
19623                        }
19624                        removed.add(ppa);
19625                    }
19626                }
19627                if (removed != null) {
19628                    for (int j=0; j<removed.size(); j++) {
19629                        PersistentPreferredActivity ppa = removed.get(j);
19630                        ppir.removeFilter(ppa);
19631                    }
19632                    changed = true;
19633                }
19634            }
19635
19636            if (changed) {
19637                scheduleWritePackageRestrictionsLocked(userId);
19638                postPreferredActivityChangedBroadcast(userId);
19639            }
19640        }
19641    }
19642
19643    /**
19644     * Common machinery for picking apart a restored XML blob and passing
19645     * it to a caller-supplied functor to be applied to the running system.
19646     */
19647    private void restoreFromXml(XmlPullParser parser, int userId,
19648            String expectedStartTag, BlobXmlRestorer functor)
19649            throws IOException, XmlPullParserException {
19650        int type;
19651        while ((type = parser.next()) != XmlPullParser.START_TAG
19652                && type != XmlPullParser.END_DOCUMENT) {
19653        }
19654        if (type != XmlPullParser.START_TAG) {
19655            // oops didn't find a start tag?!
19656            if (DEBUG_BACKUP) {
19657                Slog.e(TAG, "Didn't find start tag during restore");
19658            }
19659            return;
19660        }
19661Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19662        // this is supposed to be TAG_PREFERRED_BACKUP
19663        if (!expectedStartTag.equals(parser.getName())) {
19664            if (DEBUG_BACKUP) {
19665                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19666            }
19667            return;
19668        }
19669
19670        // skip interfering stuff, then we're aligned with the backing implementation
19671        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19672Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19673        functor.apply(parser, userId);
19674    }
19675
19676    private interface BlobXmlRestorer {
19677        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19678    }
19679
19680    /**
19681     * Non-Binder method, support for the backup/restore mechanism: write the
19682     * full set of preferred activities in its canonical XML format.  Returns the
19683     * XML output as a byte array, or null if there is none.
19684     */
19685    @Override
19686    public byte[] getPreferredActivityBackup(int userId) {
19687        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19688            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19689        }
19690
19691        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19692        try {
19693            final XmlSerializer serializer = new FastXmlSerializer();
19694            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19695            serializer.startDocument(null, true);
19696            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19697
19698            synchronized (mPackages) {
19699                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19700            }
19701
19702            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19703            serializer.endDocument();
19704            serializer.flush();
19705        } catch (Exception e) {
19706            if (DEBUG_BACKUP) {
19707                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19708            }
19709            return null;
19710        }
19711
19712        return dataStream.toByteArray();
19713    }
19714
19715    @Override
19716    public void restorePreferredActivities(byte[] backup, int userId) {
19717        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19718            throw new SecurityException("Only the system may call restorePreferredActivities()");
19719        }
19720
19721        try {
19722            final XmlPullParser parser = Xml.newPullParser();
19723            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19724            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19725                    new BlobXmlRestorer() {
19726                        @Override
19727                        public void apply(XmlPullParser parser, int userId)
19728                                throws XmlPullParserException, IOException {
19729                            synchronized (mPackages) {
19730                                mSettings.readPreferredActivitiesLPw(parser, userId);
19731                            }
19732                        }
19733                    } );
19734        } catch (Exception e) {
19735            if (DEBUG_BACKUP) {
19736                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19737            }
19738        }
19739    }
19740
19741    /**
19742     * Non-Binder method, support for the backup/restore mechanism: write the
19743     * default browser (etc) settings in its canonical XML format.  Returns the default
19744     * browser XML representation as a byte array, or null if there is none.
19745     */
19746    @Override
19747    public byte[] getDefaultAppsBackup(int userId) {
19748        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19749            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19750        }
19751
19752        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19753        try {
19754            final XmlSerializer serializer = new FastXmlSerializer();
19755            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19756            serializer.startDocument(null, true);
19757            serializer.startTag(null, TAG_DEFAULT_APPS);
19758
19759            synchronized (mPackages) {
19760                mSettings.writeDefaultAppsLPr(serializer, userId);
19761            }
19762
19763            serializer.endTag(null, TAG_DEFAULT_APPS);
19764            serializer.endDocument();
19765            serializer.flush();
19766        } catch (Exception e) {
19767            if (DEBUG_BACKUP) {
19768                Slog.e(TAG, "Unable to write default apps for backup", e);
19769            }
19770            return null;
19771        }
19772
19773        return dataStream.toByteArray();
19774    }
19775
19776    @Override
19777    public void restoreDefaultApps(byte[] backup, int userId) {
19778        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19779            throw new SecurityException("Only the system may call restoreDefaultApps()");
19780        }
19781
19782        try {
19783            final XmlPullParser parser = Xml.newPullParser();
19784            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19785            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19786                    new BlobXmlRestorer() {
19787                        @Override
19788                        public void apply(XmlPullParser parser, int userId)
19789                                throws XmlPullParserException, IOException {
19790                            synchronized (mPackages) {
19791                                mSettings.readDefaultAppsLPw(parser, userId);
19792                            }
19793                        }
19794                    } );
19795        } catch (Exception e) {
19796            if (DEBUG_BACKUP) {
19797                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19798            }
19799        }
19800    }
19801
19802    @Override
19803    public byte[] getIntentFilterVerificationBackup(int userId) {
19804        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19805            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19806        }
19807
19808        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19809        try {
19810            final XmlSerializer serializer = new FastXmlSerializer();
19811            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19812            serializer.startDocument(null, true);
19813            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19814
19815            synchronized (mPackages) {
19816                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19817            }
19818
19819            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19820            serializer.endDocument();
19821            serializer.flush();
19822        } catch (Exception e) {
19823            if (DEBUG_BACKUP) {
19824                Slog.e(TAG, "Unable to write default apps for backup", e);
19825            }
19826            return null;
19827        }
19828
19829        return dataStream.toByteArray();
19830    }
19831
19832    @Override
19833    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19834        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19835            throw new SecurityException("Only the system may call restorePreferredActivities()");
19836        }
19837
19838        try {
19839            final XmlPullParser parser = Xml.newPullParser();
19840            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19841            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19842                    new BlobXmlRestorer() {
19843                        @Override
19844                        public void apply(XmlPullParser parser, int userId)
19845                                throws XmlPullParserException, IOException {
19846                            synchronized (mPackages) {
19847                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19848                                mSettings.writeLPr();
19849                            }
19850                        }
19851                    } );
19852        } catch (Exception e) {
19853            if (DEBUG_BACKUP) {
19854                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19855            }
19856        }
19857    }
19858
19859    @Override
19860    public byte[] getPermissionGrantBackup(int userId) {
19861        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19862            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19863        }
19864
19865        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19866        try {
19867            final XmlSerializer serializer = new FastXmlSerializer();
19868            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19869            serializer.startDocument(null, true);
19870            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19871
19872            synchronized (mPackages) {
19873                serializeRuntimePermissionGrantsLPr(serializer, userId);
19874            }
19875
19876            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19877            serializer.endDocument();
19878            serializer.flush();
19879        } catch (Exception e) {
19880            if (DEBUG_BACKUP) {
19881                Slog.e(TAG, "Unable to write default apps for backup", e);
19882            }
19883            return null;
19884        }
19885
19886        return dataStream.toByteArray();
19887    }
19888
19889    @Override
19890    public void restorePermissionGrants(byte[] backup, int userId) {
19891        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19892            throw new SecurityException("Only the system may call restorePermissionGrants()");
19893        }
19894
19895        try {
19896            final XmlPullParser parser = Xml.newPullParser();
19897            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19898            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19899                    new BlobXmlRestorer() {
19900                        @Override
19901                        public void apply(XmlPullParser parser, int userId)
19902                                throws XmlPullParserException, IOException {
19903                            synchronized (mPackages) {
19904                                processRestoredPermissionGrantsLPr(parser, userId);
19905                            }
19906                        }
19907                    } );
19908        } catch (Exception e) {
19909            if (DEBUG_BACKUP) {
19910                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19911            }
19912        }
19913    }
19914
19915    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19916            throws IOException {
19917        serializer.startTag(null, TAG_ALL_GRANTS);
19918
19919        final int N = mSettings.mPackages.size();
19920        for (int i = 0; i < N; i++) {
19921            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19922            boolean pkgGrantsKnown = false;
19923
19924            PermissionsState packagePerms = ps.getPermissionsState();
19925
19926            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19927                final int grantFlags = state.getFlags();
19928                // only look at grants that are not system/policy fixed
19929                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19930                    final boolean isGranted = state.isGranted();
19931                    // And only back up the user-twiddled state bits
19932                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19933                        final String packageName = mSettings.mPackages.keyAt(i);
19934                        if (!pkgGrantsKnown) {
19935                            serializer.startTag(null, TAG_GRANT);
19936                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19937                            pkgGrantsKnown = true;
19938                        }
19939
19940                        final boolean userSet =
19941                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19942                        final boolean userFixed =
19943                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19944                        final boolean revoke =
19945                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19946
19947                        serializer.startTag(null, TAG_PERMISSION);
19948                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19949                        if (isGranted) {
19950                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19951                        }
19952                        if (userSet) {
19953                            serializer.attribute(null, ATTR_USER_SET, "true");
19954                        }
19955                        if (userFixed) {
19956                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19957                        }
19958                        if (revoke) {
19959                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19960                        }
19961                        serializer.endTag(null, TAG_PERMISSION);
19962                    }
19963                }
19964            }
19965
19966            if (pkgGrantsKnown) {
19967                serializer.endTag(null, TAG_GRANT);
19968            }
19969        }
19970
19971        serializer.endTag(null, TAG_ALL_GRANTS);
19972    }
19973
19974    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19975            throws XmlPullParserException, IOException {
19976        String pkgName = null;
19977        int outerDepth = parser.getDepth();
19978        int type;
19979        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19980                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19981            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19982                continue;
19983            }
19984
19985            final String tagName = parser.getName();
19986            if (tagName.equals(TAG_GRANT)) {
19987                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19988                if (DEBUG_BACKUP) {
19989                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19990                }
19991            } else if (tagName.equals(TAG_PERMISSION)) {
19992
19993                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19994                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19995
19996                int newFlagSet = 0;
19997                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19998                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19999                }
20000                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20001                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20002                }
20003                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20004                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20005                }
20006                if (DEBUG_BACKUP) {
20007                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
20008                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20009                }
20010                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20011                if (ps != null) {
20012                    // Already installed so we apply the grant immediately
20013                    if (DEBUG_BACKUP) {
20014                        Slog.v(TAG, "        + already installed; applying");
20015                    }
20016                    PermissionsState perms = ps.getPermissionsState();
20017                    BasePermission bp = mSettings.mPermissions.get(permName);
20018                    if (bp != null) {
20019                        if (isGranted) {
20020                            perms.grantRuntimePermission(bp, userId);
20021                        }
20022                        if (newFlagSet != 0) {
20023                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20024                        }
20025                    }
20026                } else {
20027                    // Need to wait for post-restore install to apply the grant
20028                    if (DEBUG_BACKUP) {
20029                        Slog.v(TAG, "        - not yet installed; saving for later");
20030                    }
20031                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20032                            isGranted, newFlagSet, userId);
20033                }
20034            } else {
20035                PackageManagerService.reportSettingsProblem(Log.WARN,
20036                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20037                XmlUtils.skipCurrentTag(parser);
20038            }
20039        }
20040
20041        scheduleWriteSettingsLocked();
20042        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20043    }
20044
20045    @Override
20046    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20047            int sourceUserId, int targetUserId, int flags) {
20048        mContext.enforceCallingOrSelfPermission(
20049                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20050        int callingUid = Binder.getCallingUid();
20051        enforceOwnerRights(ownerPackage, callingUid);
20052        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20053        if (intentFilter.countActions() == 0) {
20054            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20055            return;
20056        }
20057        synchronized (mPackages) {
20058            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20059                    ownerPackage, targetUserId, flags);
20060            CrossProfileIntentResolver resolver =
20061                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20062            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20063            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20064            if (existing != null) {
20065                int size = existing.size();
20066                for (int i = 0; i < size; i++) {
20067                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20068                        return;
20069                    }
20070                }
20071            }
20072            resolver.addFilter(newFilter);
20073            scheduleWritePackageRestrictionsLocked(sourceUserId);
20074        }
20075    }
20076
20077    @Override
20078    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20079        mContext.enforceCallingOrSelfPermission(
20080                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20081        int callingUid = Binder.getCallingUid();
20082        enforceOwnerRights(ownerPackage, callingUid);
20083        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20084        synchronized (mPackages) {
20085            CrossProfileIntentResolver resolver =
20086                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20087            ArraySet<CrossProfileIntentFilter> set =
20088                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20089            for (CrossProfileIntentFilter filter : set) {
20090                if (filter.getOwnerPackage().equals(ownerPackage)) {
20091                    resolver.removeFilter(filter);
20092                }
20093            }
20094            scheduleWritePackageRestrictionsLocked(sourceUserId);
20095        }
20096    }
20097
20098    // Enforcing that callingUid is owning pkg on userId
20099    private void enforceOwnerRights(String pkg, int callingUid) {
20100        // The system owns everything.
20101        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20102            return;
20103        }
20104        int callingUserId = UserHandle.getUserId(callingUid);
20105        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20106        if (pi == null) {
20107            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20108                    + callingUserId);
20109        }
20110        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20111            throw new SecurityException("Calling uid " + callingUid
20112                    + " does not own package " + pkg);
20113        }
20114    }
20115
20116    @Override
20117    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20118        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20119    }
20120
20121    /**
20122     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20123     * then reports the most likely home activity or null if there are more than one.
20124     */
20125    public ComponentName getDefaultHomeActivity(int userId) {
20126        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20127        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20128        if (cn != null) {
20129            return cn;
20130        }
20131
20132        // Find the launcher with the highest priority and return that component if there are no
20133        // other home activity with the same priority.
20134        int lastPriority = Integer.MIN_VALUE;
20135        ComponentName lastComponent = null;
20136        final int size = allHomeCandidates.size();
20137        for (int i = 0; i < size; i++) {
20138            final ResolveInfo ri = allHomeCandidates.get(i);
20139            if (ri.priority > lastPriority) {
20140                lastComponent = ri.activityInfo.getComponentName();
20141                lastPriority = ri.priority;
20142            } else if (ri.priority == lastPriority) {
20143                // Two components found with same priority.
20144                lastComponent = null;
20145            }
20146        }
20147        return lastComponent;
20148    }
20149
20150    private Intent getHomeIntent() {
20151        Intent intent = new Intent(Intent.ACTION_MAIN);
20152        intent.addCategory(Intent.CATEGORY_HOME);
20153        intent.addCategory(Intent.CATEGORY_DEFAULT);
20154        return intent;
20155    }
20156
20157    private IntentFilter getHomeFilter() {
20158        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20159        filter.addCategory(Intent.CATEGORY_HOME);
20160        filter.addCategory(Intent.CATEGORY_DEFAULT);
20161        return filter;
20162    }
20163
20164    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20165            int userId) {
20166        Intent intent  = getHomeIntent();
20167        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20168                PackageManager.GET_META_DATA, userId);
20169        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20170                true, false, false, userId);
20171
20172        allHomeCandidates.clear();
20173        if (list != null) {
20174            for (ResolveInfo ri : list) {
20175                allHomeCandidates.add(ri);
20176            }
20177        }
20178        return (preferred == null || preferred.activityInfo == null)
20179                ? null
20180                : new ComponentName(preferred.activityInfo.packageName,
20181                        preferred.activityInfo.name);
20182    }
20183
20184    @Override
20185    public void setHomeActivity(ComponentName comp, int userId) {
20186        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20187        getHomeActivitiesAsUser(homeActivities, userId);
20188
20189        boolean found = false;
20190
20191        final int size = homeActivities.size();
20192        final ComponentName[] set = new ComponentName[size];
20193        for (int i = 0; i < size; i++) {
20194            final ResolveInfo candidate = homeActivities.get(i);
20195            final ActivityInfo info = candidate.activityInfo;
20196            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20197            set[i] = activityName;
20198            if (!found && activityName.equals(comp)) {
20199                found = true;
20200            }
20201        }
20202        if (!found) {
20203            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20204                    + userId);
20205        }
20206        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20207                set, comp, userId);
20208    }
20209
20210    private @Nullable String getSetupWizardPackageName() {
20211        final Intent intent = new Intent(Intent.ACTION_MAIN);
20212        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20213
20214        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20215                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20216                        | MATCH_DISABLED_COMPONENTS,
20217                UserHandle.myUserId());
20218        if (matches.size() == 1) {
20219            return matches.get(0).getComponentInfo().packageName;
20220        } else {
20221            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20222                    + ": matches=" + matches);
20223            return null;
20224        }
20225    }
20226
20227    private @Nullable String getStorageManagerPackageName() {
20228        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20229
20230        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20231                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20232                        | MATCH_DISABLED_COMPONENTS,
20233                UserHandle.myUserId());
20234        if (matches.size() == 1) {
20235            return matches.get(0).getComponentInfo().packageName;
20236        } else {
20237            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20238                    + matches.size() + ": matches=" + matches);
20239            return null;
20240        }
20241    }
20242
20243    @Override
20244    public void setApplicationEnabledSetting(String appPackageName,
20245            int newState, int flags, int userId, String callingPackage) {
20246        if (!sUserManager.exists(userId)) return;
20247        if (callingPackage == null) {
20248            callingPackage = Integer.toString(Binder.getCallingUid());
20249        }
20250        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20251    }
20252
20253    @Override
20254    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20255        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20256        synchronized (mPackages) {
20257            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20258            if (pkgSetting != null) {
20259                pkgSetting.setUpdateAvailable(updateAvailable);
20260            }
20261        }
20262    }
20263
20264    @Override
20265    public void setComponentEnabledSetting(ComponentName componentName,
20266            int newState, int flags, int userId) {
20267        if (!sUserManager.exists(userId)) return;
20268        setEnabledSetting(componentName.getPackageName(),
20269                componentName.getClassName(), newState, flags, userId, null);
20270    }
20271
20272    private void setEnabledSetting(final String packageName, String className, int newState,
20273            final int flags, int userId, String callingPackage) {
20274        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20275              || newState == COMPONENT_ENABLED_STATE_ENABLED
20276              || newState == COMPONENT_ENABLED_STATE_DISABLED
20277              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20278              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20279            throw new IllegalArgumentException("Invalid new component state: "
20280                    + newState);
20281        }
20282        PackageSetting pkgSetting;
20283        final int uid = Binder.getCallingUid();
20284        final int permission;
20285        if (uid == Process.SYSTEM_UID) {
20286            permission = PackageManager.PERMISSION_GRANTED;
20287        } else {
20288            permission = mContext.checkCallingOrSelfPermission(
20289                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20290        }
20291        enforceCrossUserPermission(uid, userId,
20292                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20293        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20294        boolean sendNow = false;
20295        boolean isApp = (className == null);
20296        String componentName = isApp ? packageName : className;
20297        int packageUid = -1;
20298        ArrayList<String> components;
20299
20300        // writer
20301        synchronized (mPackages) {
20302            pkgSetting = mSettings.mPackages.get(packageName);
20303            if (pkgSetting == null) {
20304                if (className == null) {
20305                    throw new IllegalArgumentException("Unknown package: " + packageName);
20306                }
20307                throw new IllegalArgumentException(
20308                        "Unknown component: " + packageName + "/" + className);
20309            }
20310        }
20311
20312        // Limit who can change which apps
20313        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
20314            // Don't allow apps that don't have permission to modify other apps
20315            if (!allowedByPermission) {
20316                throw new SecurityException(
20317                        "Permission Denial: attempt to change component state from pid="
20318                        + Binder.getCallingPid()
20319                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
20320            }
20321            // Don't allow changing protected packages.
20322            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20323                throw new SecurityException("Cannot disable a protected package: " + packageName);
20324            }
20325        }
20326
20327        synchronized (mPackages) {
20328            if (uid == Process.SHELL_UID
20329                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20330                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20331                // unless it is a test package.
20332                int oldState = pkgSetting.getEnabled(userId);
20333                if (className == null
20334                    &&
20335                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20336                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20337                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20338                    &&
20339                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20340                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
20341                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20342                    // ok
20343                } else {
20344                    throw new SecurityException(
20345                            "Shell cannot change component state for " + packageName + "/"
20346                            + className + " to " + newState);
20347                }
20348            }
20349            if (className == null) {
20350                // We're dealing with an application/package level state change
20351                if (pkgSetting.getEnabled(userId) == newState) {
20352                    // Nothing to do
20353                    return;
20354                }
20355                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20356                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20357                    // Don't care about who enables an app.
20358                    callingPackage = null;
20359                }
20360                pkgSetting.setEnabled(newState, userId, callingPackage);
20361                // pkgSetting.pkg.mSetEnabled = newState;
20362            } else {
20363                // We're dealing with a component level state change
20364                // First, verify that this is a valid class name.
20365                PackageParser.Package pkg = pkgSetting.pkg;
20366                if (pkg == null || !pkg.hasComponentClassName(className)) {
20367                    if (pkg != null &&
20368                            pkg.applicationInfo.targetSdkVersion >=
20369                                    Build.VERSION_CODES.JELLY_BEAN) {
20370                        throw new IllegalArgumentException("Component class " + className
20371                                + " does not exist in " + packageName);
20372                    } else {
20373                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20374                                + className + " does not exist in " + packageName);
20375                    }
20376                }
20377                switch (newState) {
20378                case COMPONENT_ENABLED_STATE_ENABLED:
20379                    if (!pkgSetting.enableComponentLPw(className, userId)) {
20380                        return;
20381                    }
20382                    break;
20383                case COMPONENT_ENABLED_STATE_DISABLED:
20384                    if (!pkgSetting.disableComponentLPw(className, userId)) {
20385                        return;
20386                    }
20387                    break;
20388                case COMPONENT_ENABLED_STATE_DEFAULT:
20389                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
20390                        return;
20391                    }
20392                    break;
20393                default:
20394                    Slog.e(TAG, "Invalid new component state: " + newState);
20395                    return;
20396                }
20397            }
20398            scheduleWritePackageRestrictionsLocked(userId);
20399            updateSequenceNumberLP(packageName, new int[] { userId });
20400            final long callingId = Binder.clearCallingIdentity();
20401            try {
20402                updateInstantAppInstallerLocked(packageName);
20403            } finally {
20404                Binder.restoreCallingIdentity(callingId);
20405            }
20406            components = mPendingBroadcasts.get(userId, packageName);
20407            final boolean newPackage = components == null;
20408            if (newPackage) {
20409                components = new ArrayList<String>();
20410            }
20411            if (!components.contains(componentName)) {
20412                components.add(componentName);
20413            }
20414            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20415                sendNow = true;
20416                // Purge entry from pending broadcast list if another one exists already
20417                // since we are sending one right away.
20418                mPendingBroadcasts.remove(userId, packageName);
20419            } else {
20420                if (newPackage) {
20421                    mPendingBroadcasts.put(userId, packageName, components);
20422                }
20423                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20424                    // Schedule a message
20425                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20426                }
20427            }
20428        }
20429
20430        long callingId = Binder.clearCallingIdentity();
20431        try {
20432            if (sendNow) {
20433                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20434                sendPackageChangedBroadcast(packageName,
20435                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20436            }
20437        } finally {
20438            Binder.restoreCallingIdentity(callingId);
20439        }
20440    }
20441
20442    @Override
20443    public void flushPackageRestrictionsAsUser(int userId) {
20444        if (!sUserManager.exists(userId)) {
20445            return;
20446        }
20447        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20448                false /* checkShell */, "flushPackageRestrictions");
20449        synchronized (mPackages) {
20450            mSettings.writePackageRestrictionsLPr(userId);
20451            mDirtyUsers.remove(userId);
20452            if (mDirtyUsers.isEmpty()) {
20453                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20454            }
20455        }
20456    }
20457
20458    private void sendPackageChangedBroadcast(String packageName,
20459            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20460        if (DEBUG_INSTALL)
20461            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20462                    + componentNames);
20463        Bundle extras = new Bundle(4);
20464        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20465        String nameList[] = new String[componentNames.size()];
20466        componentNames.toArray(nameList);
20467        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20468        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20469        extras.putInt(Intent.EXTRA_UID, packageUid);
20470        // If this is not reporting a change of the overall package, then only send it
20471        // to registered receivers.  We don't want to launch a swath of apps for every
20472        // little component state change.
20473        final int flags = !componentNames.contains(packageName)
20474                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20475        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20476                new int[] {UserHandle.getUserId(packageUid)});
20477    }
20478
20479    @Override
20480    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20481        if (!sUserManager.exists(userId)) return;
20482        final int uid = Binder.getCallingUid();
20483        final int permission = mContext.checkCallingOrSelfPermission(
20484                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20485        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20486        enforceCrossUserPermission(uid, userId,
20487                true /* requireFullPermission */, true /* checkShell */, "stop package");
20488        // writer
20489        synchronized (mPackages) {
20490            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20491                    allowedByPermission, uid, userId)) {
20492                scheduleWritePackageRestrictionsLocked(userId);
20493            }
20494        }
20495    }
20496
20497    @Override
20498    public String getInstallerPackageName(String packageName) {
20499        // reader
20500        synchronized (mPackages) {
20501            return mSettings.getInstallerPackageNameLPr(packageName);
20502        }
20503    }
20504
20505    public boolean isOrphaned(String packageName) {
20506        // reader
20507        synchronized (mPackages) {
20508            return mSettings.isOrphaned(packageName);
20509        }
20510    }
20511
20512    @Override
20513    public int getApplicationEnabledSetting(String packageName, int userId) {
20514        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20515        int uid = Binder.getCallingUid();
20516        enforceCrossUserPermission(uid, userId,
20517                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20518        // reader
20519        synchronized (mPackages) {
20520            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20521        }
20522    }
20523
20524    @Override
20525    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
20526        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20527        int uid = Binder.getCallingUid();
20528        enforceCrossUserPermission(uid, userId,
20529                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
20530        // reader
20531        synchronized (mPackages) {
20532            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
20533        }
20534    }
20535
20536    @Override
20537    public void enterSafeMode() {
20538        enforceSystemOrRoot("Only the system can request entering safe mode");
20539
20540        if (!mSystemReady) {
20541            mSafeMode = true;
20542        }
20543    }
20544
20545    @Override
20546    public void systemReady() {
20547        mSystemReady = true;
20548        final ContentResolver resolver = mContext.getContentResolver();
20549        ContentObserver co = new ContentObserver(mHandler) {
20550            @Override
20551            public void onChange(boolean selfChange) {
20552                mEphemeralAppsDisabled =
20553                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20554                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20555            }
20556        };
20557        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20558                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20559                false, co, UserHandle.USER_SYSTEM);
20560        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20561                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20562        co.onChange(true);
20563
20564        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20565        // disabled after already being started.
20566        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20567                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20568
20569        // Read the compatibilty setting when the system is ready.
20570        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20571                mContext.getContentResolver(),
20572                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20573        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20574        if (DEBUG_SETTINGS) {
20575            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20576        }
20577
20578        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20579
20580        synchronized (mPackages) {
20581            // Verify that all of the preferred activity components actually
20582            // exist.  It is possible for applications to be updated and at
20583            // that point remove a previously declared activity component that
20584            // had been set as a preferred activity.  We try to clean this up
20585            // the next time we encounter that preferred activity, but it is
20586            // possible for the user flow to never be able to return to that
20587            // situation so here we do a sanity check to make sure we haven't
20588            // left any junk around.
20589            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20590            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20591                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20592                removed.clear();
20593                for (PreferredActivity pa : pir.filterSet()) {
20594                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20595                        removed.add(pa);
20596                    }
20597                }
20598                if (removed.size() > 0) {
20599                    for (int r=0; r<removed.size(); r++) {
20600                        PreferredActivity pa = removed.get(r);
20601                        Slog.w(TAG, "Removing dangling preferred activity: "
20602                                + pa.mPref.mComponent);
20603                        pir.removeFilter(pa);
20604                    }
20605                    mSettings.writePackageRestrictionsLPr(
20606                            mSettings.mPreferredActivities.keyAt(i));
20607                }
20608            }
20609
20610            for (int userId : UserManagerService.getInstance().getUserIds()) {
20611                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20612                    grantPermissionsUserIds = ArrayUtils.appendInt(
20613                            grantPermissionsUserIds, userId);
20614                }
20615            }
20616        }
20617        sUserManager.systemReady();
20618
20619        // If we upgraded grant all default permissions before kicking off.
20620        for (int userId : grantPermissionsUserIds) {
20621            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20622        }
20623
20624        // If we did not grant default permissions, we preload from this the
20625        // default permission exceptions lazily to ensure we don't hit the
20626        // disk on a new user creation.
20627        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20628            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20629        }
20630
20631        // Kick off any messages waiting for system ready
20632        if (mPostSystemReadyMessages != null) {
20633            for (Message msg : mPostSystemReadyMessages) {
20634                msg.sendToTarget();
20635            }
20636            mPostSystemReadyMessages = null;
20637        }
20638
20639        // Watch for external volumes that come and go over time
20640        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20641        storage.registerListener(mStorageListener);
20642
20643        mInstallerService.systemReady();
20644        mPackageDexOptimizer.systemReady();
20645
20646        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20647                StorageManagerInternal.class);
20648        StorageManagerInternal.addExternalStoragePolicy(
20649                new StorageManagerInternal.ExternalStorageMountPolicy() {
20650            @Override
20651            public int getMountMode(int uid, String packageName) {
20652                if (Process.isIsolated(uid)) {
20653                    return Zygote.MOUNT_EXTERNAL_NONE;
20654                }
20655                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20656                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20657                }
20658                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20659                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20660                }
20661                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20662                    return Zygote.MOUNT_EXTERNAL_READ;
20663                }
20664                return Zygote.MOUNT_EXTERNAL_WRITE;
20665            }
20666
20667            @Override
20668            public boolean hasExternalStorage(int uid, String packageName) {
20669                return true;
20670            }
20671        });
20672
20673        // Now that we're mostly running, clean up stale users and apps
20674        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20675        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20676
20677        if (mPrivappPermissionsViolations != null) {
20678            Slog.wtf(TAG,"Signature|privileged permissions not in "
20679                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
20680            mPrivappPermissionsViolations = null;
20681        }
20682    }
20683
20684    public void waitForAppDataPrepared() {
20685        if (mPrepareAppDataFuture == null) {
20686            return;
20687        }
20688        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20689        mPrepareAppDataFuture = null;
20690    }
20691
20692    @Override
20693    public boolean isSafeMode() {
20694        return mSafeMode;
20695    }
20696
20697    @Override
20698    public boolean hasSystemUidErrors() {
20699        return mHasSystemUidErrors;
20700    }
20701
20702    static String arrayToString(int[] array) {
20703        StringBuffer buf = new StringBuffer(128);
20704        buf.append('[');
20705        if (array != null) {
20706            for (int i=0; i<array.length; i++) {
20707                if (i > 0) buf.append(", ");
20708                buf.append(array[i]);
20709            }
20710        }
20711        buf.append(']');
20712        return buf.toString();
20713    }
20714
20715    static class DumpState {
20716        public static final int DUMP_LIBS = 1 << 0;
20717        public static final int DUMP_FEATURES = 1 << 1;
20718        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20719        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20720        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20721        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20722        public static final int DUMP_PERMISSIONS = 1 << 6;
20723        public static final int DUMP_PACKAGES = 1 << 7;
20724        public static final int DUMP_SHARED_USERS = 1 << 8;
20725        public static final int DUMP_MESSAGES = 1 << 9;
20726        public static final int DUMP_PROVIDERS = 1 << 10;
20727        public static final int DUMP_VERIFIERS = 1 << 11;
20728        public static final int DUMP_PREFERRED = 1 << 12;
20729        public static final int DUMP_PREFERRED_XML = 1 << 13;
20730        public static final int DUMP_KEYSETS = 1 << 14;
20731        public static final int DUMP_VERSION = 1 << 15;
20732        public static final int DUMP_INSTALLS = 1 << 16;
20733        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20734        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20735        public static final int DUMP_FROZEN = 1 << 19;
20736        public static final int DUMP_DEXOPT = 1 << 20;
20737        public static final int DUMP_COMPILER_STATS = 1 << 21;
20738        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
20739        public static final int DUMP_CHANGES = 1 << 23;
20740
20741        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20742
20743        private int mTypes;
20744
20745        private int mOptions;
20746
20747        private boolean mTitlePrinted;
20748
20749        private SharedUserSetting mSharedUser;
20750
20751        public boolean isDumping(int type) {
20752            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20753                return true;
20754            }
20755
20756            return (mTypes & type) != 0;
20757        }
20758
20759        public void setDump(int type) {
20760            mTypes |= type;
20761        }
20762
20763        public boolean isOptionEnabled(int option) {
20764            return (mOptions & option) != 0;
20765        }
20766
20767        public void setOptionEnabled(int option) {
20768            mOptions |= option;
20769        }
20770
20771        public boolean onTitlePrinted() {
20772            final boolean printed = mTitlePrinted;
20773            mTitlePrinted = true;
20774            return printed;
20775        }
20776
20777        public boolean getTitlePrinted() {
20778            return mTitlePrinted;
20779        }
20780
20781        public void setTitlePrinted(boolean enabled) {
20782            mTitlePrinted = enabled;
20783        }
20784
20785        public SharedUserSetting getSharedUser() {
20786            return mSharedUser;
20787        }
20788
20789        public void setSharedUser(SharedUserSetting user) {
20790            mSharedUser = user;
20791        }
20792    }
20793
20794    @Override
20795    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20796            FileDescriptor err, String[] args, ShellCallback callback,
20797            ResultReceiver resultReceiver) {
20798        (new PackageManagerShellCommand(this)).exec(
20799                this, in, out, err, args, callback, resultReceiver);
20800    }
20801
20802    @Override
20803    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20804        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20805
20806        DumpState dumpState = new DumpState();
20807        boolean fullPreferred = false;
20808        boolean checkin = false;
20809
20810        String packageName = null;
20811        ArraySet<String> permissionNames = null;
20812
20813        int opti = 0;
20814        while (opti < args.length) {
20815            String opt = args[opti];
20816            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20817                break;
20818            }
20819            opti++;
20820
20821            if ("-a".equals(opt)) {
20822                // Right now we only know how to print all.
20823            } else if ("-h".equals(opt)) {
20824                pw.println("Package manager dump options:");
20825                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20826                pw.println("    --checkin: dump for a checkin");
20827                pw.println("    -f: print details of intent filters");
20828                pw.println("    -h: print this help");
20829                pw.println("  cmd may be one of:");
20830                pw.println("    l[ibraries]: list known shared libraries");
20831                pw.println("    f[eatures]: list device features");
20832                pw.println("    k[eysets]: print known keysets");
20833                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20834                pw.println("    perm[issions]: dump permissions");
20835                pw.println("    permission [name ...]: dump declaration and use of given permission");
20836                pw.println("    pref[erred]: print preferred package settings");
20837                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20838                pw.println("    prov[iders]: dump content providers");
20839                pw.println("    p[ackages]: dump installed packages");
20840                pw.println("    s[hared-users]: dump shared user IDs");
20841                pw.println("    m[essages]: print collected runtime messages");
20842                pw.println("    v[erifiers]: print package verifier info");
20843                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20844                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20845                pw.println("    version: print database version info");
20846                pw.println("    write: write current settings now");
20847                pw.println("    installs: details about install sessions");
20848                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20849                pw.println("    dexopt: dump dexopt state");
20850                pw.println("    compiler-stats: dump compiler statistics");
20851                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20852                pw.println("    <package.name>: info about given package");
20853                return;
20854            } else if ("--checkin".equals(opt)) {
20855                checkin = true;
20856            } else if ("-f".equals(opt)) {
20857                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20858            } else if ("--proto".equals(opt)) {
20859                dumpProto(fd);
20860                return;
20861            } else {
20862                pw.println("Unknown argument: " + opt + "; use -h for help");
20863            }
20864        }
20865
20866        // Is the caller requesting to dump a particular piece of data?
20867        if (opti < args.length) {
20868            String cmd = args[opti];
20869            opti++;
20870            // Is this a package name?
20871            if ("android".equals(cmd) || cmd.contains(".")) {
20872                packageName = cmd;
20873                // When dumping a single package, we always dump all of its
20874                // filter information since the amount of data will be reasonable.
20875                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20876            } else if ("check-permission".equals(cmd)) {
20877                if (opti >= args.length) {
20878                    pw.println("Error: check-permission missing permission argument");
20879                    return;
20880                }
20881                String perm = args[opti];
20882                opti++;
20883                if (opti >= args.length) {
20884                    pw.println("Error: check-permission missing package argument");
20885                    return;
20886                }
20887
20888                String pkg = args[opti];
20889                opti++;
20890                int user = UserHandle.getUserId(Binder.getCallingUid());
20891                if (opti < args.length) {
20892                    try {
20893                        user = Integer.parseInt(args[opti]);
20894                    } catch (NumberFormatException e) {
20895                        pw.println("Error: check-permission user argument is not a number: "
20896                                + args[opti]);
20897                        return;
20898                    }
20899                }
20900
20901                // Normalize package name to handle renamed packages and static libs
20902                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20903
20904                pw.println(checkPermission(perm, pkg, user));
20905                return;
20906            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20907                dumpState.setDump(DumpState.DUMP_LIBS);
20908            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20909                dumpState.setDump(DumpState.DUMP_FEATURES);
20910            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20911                if (opti >= args.length) {
20912                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20913                            | DumpState.DUMP_SERVICE_RESOLVERS
20914                            | DumpState.DUMP_RECEIVER_RESOLVERS
20915                            | DumpState.DUMP_CONTENT_RESOLVERS);
20916                } else {
20917                    while (opti < args.length) {
20918                        String name = args[opti];
20919                        if ("a".equals(name) || "activity".equals(name)) {
20920                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20921                        } else if ("s".equals(name) || "service".equals(name)) {
20922                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20923                        } else if ("r".equals(name) || "receiver".equals(name)) {
20924                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20925                        } else if ("c".equals(name) || "content".equals(name)) {
20926                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20927                        } else {
20928                            pw.println("Error: unknown resolver table type: " + name);
20929                            return;
20930                        }
20931                        opti++;
20932                    }
20933                }
20934            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20935                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20936            } else if ("permission".equals(cmd)) {
20937                if (opti >= args.length) {
20938                    pw.println("Error: permission requires permission name");
20939                    return;
20940                }
20941                permissionNames = new ArraySet<>();
20942                while (opti < args.length) {
20943                    permissionNames.add(args[opti]);
20944                    opti++;
20945                }
20946                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20947                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20948            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20949                dumpState.setDump(DumpState.DUMP_PREFERRED);
20950            } else if ("preferred-xml".equals(cmd)) {
20951                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20952                if (opti < args.length && "--full".equals(args[opti])) {
20953                    fullPreferred = true;
20954                    opti++;
20955                }
20956            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20957                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20958            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20959                dumpState.setDump(DumpState.DUMP_PACKAGES);
20960            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20961                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20962            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20963                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20964            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20965                dumpState.setDump(DumpState.DUMP_MESSAGES);
20966            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20967                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20968            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20969                    || "intent-filter-verifiers".equals(cmd)) {
20970                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20971            } else if ("version".equals(cmd)) {
20972                dumpState.setDump(DumpState.DUMP_VERSION);
20973            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20974                dumpState.setDump(DumpState.DUMP_KEYSETS);
20975            } else if ("installs".equals(cmd)) {
20976                dumpState.setDump(DumpState.DUMP_INSTALLS);
20977            } else if ("frozen".equals(cmd)) {
20978                dumpState.setDump(DumpState.DUMP_FROZEN);
20979            } else if ("dexopt".equals(cmd)) {
20980                dumpState.setDump(DumpState.DUMP_DEXOPT);
20981            } else if ("compiler-stats".equals(cmd)) {
20982                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20983            } else if ("enabled-overlays".equals(cmd)) {
20984                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
20985            } else if ("changes".equals(cmd)) {
20986                dumpState.setDump(DumpState.DUMP_CHANGES);
20987            } else if ("write".equals(cmd)) {
20988                synchronized (mPackages) {
20989                    mSettings.writeLPr();
20990                    pw.println("Settings written.");
20991                    return;
20992                }
20993            }
20994        }
20995
20996        if (checkin) {
20997            pw.println("vers,1");
20998        }
20999
21000        // reader
21001        synchronized (mPackages) {
21002            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21003                if (!checkin) {
21004                    if (dumpState.onTitlePrinted())
21005                        pw.println();
21006                    pw.println("Database versions:");
21007                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21008                }
21009            }
21010
21011            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21012                if (!checkin) {
21013                    if (dumpState.onTitlePrinted())
21014                        pw.println();
21015                    pw.println("Verifiers:");
21016                    pw.print("  Required: ");
21017                    pw.print(mRequiredVerifierPackage);
21018                    pw.print(" (uid=");
21019                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21020                            UserHandle.USER_SYSTEM));
21021                    pw.println(")");
21022                } else if (mRequiredVerifierPackage != null) {
21023                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21024                    pw.print(",");
21025                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21026                            UserHandle.USER_SYSTEM));
21027                }
21028            }
21029
21030            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21031                    packageName == null) {
21032                if (mIntentFilterVerifierComponent != null) {
21033                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21034                    if (!checkin) {
21035                        if (dumpState.onTitlePrinted())
21036                            pw.println();
21037                        pw.println("Intent Filter Verifier:");
21038                        pw.print("  Using: ");
21039                        pw.print(verifierPackageName);
21040                        pw.print(" (uid=");
21041                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21042                                UserHandle.USER_SYSTEM));
21043                        pw.println(")");
21044                    } else if (verifierPackageName != null) {
21045                        pw.print("ifv,"); pw.print(verifierPackageName);
21046                        pw.print(",");
21047                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21048                                UserHandle.USER_SYSTEM));
21049                    }
21050                } else {
21051                    pw.println();
21052                    pw.println("No Intent Filter Verifier available!");
21053                }
21054            }
21055
21056            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21057                boolean printedHeader = false;
21058                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21059                while (it.hasNext()) {
21060                    String libName = it.next();
21061                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21062                    if (versionedLib == null) {
21063                        continue;
21064                    }
21065                    final int versionCount = versionedLib.size();
21066                    for (int i = 0; i < versionCount; i++) {
21067                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21068                        if (!checkin) {
21069                            if (!printedHeader) {
21070                                if (dumpState.onTitlePrinted())
21071                                    pw.println();
21072                                pw.println("Libraries:");
21073                                printedHeader = true;
21074                            }
21075                            pw.print("  ");
21076                        } else {
21077                            pw.print("lib,");
21078                        }
21079                        pw.print(libEntry.info.getName());
21080                        if (libEntry.info.isStatic()) {
21081                            pw.print(" version=" + libEntry.info.getVersion());
21082                        }
21083                        if (!checkin) {
21084                            pw.print(" -> ");
21085                        }
21086                        if (libEntry.path != null) {
21087                            pw.print(" (jar) ");
21088                            pw.print(libEntry.path);
21089                        } else {
21090                            pw.print(" (apk) ");
21091                            pw.print(libEntry.apk);
21092                        }
21093                        pw.println();
21094                    }
21095                }
21096            }
21097
21098            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21099                if (dumpState.onTitlePrinted())
21100                    pw.println();
21101                if (!checkin) {
21102                    pw.println("Features:");
21103                }
21104
21105                synchronized (mAvailableFeatures) {
21106                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21107                        if (checkin) {
21108                            pw.print("feat,");
21109                            pw.print(feat.name);
21110                            pw.print(",");
21111                            pw.println(feat.version);
21112                        } else {
21113                            pw.print("  ");
21114                            pw.print(feat.name);
21115                            if (feat.version > 0) {
21116                                pw.print(" version=");
21117                                pw.print(feat.version);
21118                            }
21119                            pw.println();
21120                        }
21121                    }
21122                }
21123            }
21124
21125            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21126                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21127                        : "Activity Resolver Table:", "  ", packageName,
21128                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21129                    dumpState.setTitlePrinted(true);
21130                }
21131            }
21132            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21133                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21134                        : "Receiver Resolver Table:", "  ", packageName,
21135                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21136                    dumpState.setTitlePrinted(true);
21137                }
21138            }
21139            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21140                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21141                        : "Service Resolver Table:", "  ", packageName,
21142                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21143                    dumpState.setTitlePrinted(true);
21144                }
21145            }
21146            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21147                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21148                        : "Provider Resolver Table:", "  ", packageName,
21149                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21150                    dumpState.setTitlePrinted(true);
21151                }
21152            }
21153
21154            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21155                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21156                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21157                    int user = mSettings.mPreferredActivities.keyAt(i);
21158                    if (pir.dump(pw,
21159                            dumpState.getTitlePrinted()
21160                                ? "\nPreferred Activities User " + user + ":"
21161                                : "Preferred Activities User " + user + ":", "  ",
21162                            packageName, true, false)) {
21163                        dumpState.setTitlePrinted(true);
21164                    }
21165                }
21166            }
21167
21168            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21169                pw.flush();
21170                FileOutputStream fout = new FileOutputStream(fd);
21171                BufferedOutputStream str = new BufferedOutputStream(fout);
21172                XmlSerializer serializer = new FastXmlSerializer();
21173                try {
21174                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21175                    serializer.startDocument(null, true);
21176                    serializer.setFeature(
21177                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21178                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21179                    serializer.endDocument();
21180                    serializer.flush();
21181                } catch (IllegalArgumentException e) {
21182                    pw.println("Failed writing: " + e);
21183                } catch (IllegalStateException e) {
21184                    pw.println("Failed writing: " + e);
21185                } catch (IOException e) {
21186                    pw.println("Failed writing: " + e);
21187                }
21188            }
21189
21190            if (!checkin
21191                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21192                    && packageName == null) {
21193                pw.println();
21194                int count = mSettings.mPackages.size();
21195                if (count == 0) {
21196                    pw.println("No applications!");
21197                    pw.println();
21198                } else {
21199                    final String prefix = "  ";
21200                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21201                    if (allPackageSettings.size() == 0) {
21202                        pw.println("No domain preferred apps!");
21203                        pw.println();
21204                    } else {
21205                        pw.println("App verification status:");
21206                        pw.println();
21207                        count = 0;
21208                        for (PackageSetting ps : allPackageSettings) {
21209                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21210                            if (ivi == null || ivi.getPackageName() == null) continue;
21211                            pw.println(prefix + "Package: " + ivi.getPackageName());
21212                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21213                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21214                            pw.println();
21215                            count++;
21216                        }
21217                        if (count == 0) {
21218                            pw.println(prefix + "No app verification established.");
21219                            pw.println();
21220                        }
21221                        for (int userId : sUserManager.getUserIds()) {
21222                            pw.println("App linkages for user " + userId + ":");
21223                            pw.println();
21224                            count = 0;
21225                            for (PackageSetting ps : allPackageSettings) {
21226                                final long status = ps.getDomainVerificationStatusForUser(userId);
21227                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21228                                        && !DEBUG_DOMAIN_VERIFICATION) {
21229                                    continue;
21230                                }
21231                                pw.println(prefix + "Package: " + ps.name);
21232                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21233                                String statusStr = IntentFilterVerificationInfo.
21234                                        getStatusStringFromValue(status);
21235                                pw.println(prefix + "Status:  " + statusStr);
21236                                pw.println();
21237                                count++;
21238                            }
21239                            if (count == 0) {
21240                                pw.println(prefix + "No configured app linkages.");
21241                                pw.println();
21242                            }
21243                        }
21244                    }
21245                }
21246            }
21247
21248            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21249                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21250                if (packageName == null && permissionNames == null) {
21251                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
21252                        if (iperm == 0) {
21253                            if (dumpState.onTitlePrinted())
21254                                pw.println();
21255                            pw.println("AppOp Permissions:");
21256                        }
21257                        pw.print("  AppOp Permission ");
21258                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
21259                        pw.println(":");
21260                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
21261                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
21262                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
21263                        }
21264                    }
21265                }
21266            }
21267
21268            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21269                boolean printedSomething = false;
21270                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21271                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21272                        continue;
21273                    }
21274                    if (!printedSomething) {
21275                        if (dumpState.onTitlePrinted())
21276                            pw.println();
21277                        pw.println("Registered ContentProviders:");
21278                        printedSomething = true;
21279                    }
21280                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21281                    pw.print("    "); pw.println(p.toString());
21282                }
21283                printedSomething = false;
21284                for (Map.Entry<String, PackageParser.Provider> entry :
21285                        mProvidersByAuthority.entrySet()) {
21286                    PackageParser.Provider p = entry.getValue();
21287                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21288                        continue;
21289                    }
21290                    if (!printedSomething) {
21291                        if (dumpState.onTitlePrinted())
21292                            pw.println();
21293                        pw.println("ContentProvider Authorities:");
21294                        printedSomething = true;
21295                    }
21296                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21297                    pw.print("    "); pw.println(p.toString());
21298                    if (p.info != null && p.info.applicationInfo != null) {
21299                        final String appInfo = p.info.applicationInfo.toString();
21300                        pw.print("      applicationInfo="); pw.println(appInfo);
21301                    }
21302                }
21303            }
21304
21305            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21306                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21307            }
21308
21309            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21310                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21311            }
21312
21313            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21314                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21315            }
21316
21317            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21318                if (dumpState.onTitlePrinted()) pw.println();
21319                pw.println("Package Changes:");
21320                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21321                final int K = mChangedPackages.size();
21322                for (int i = 0; i < K; i++) {
21323                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21324                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21325                    final int N = changes.size();
21326                    if (N == 0) {
21327                        pw.print("    "); pw.println("No packages changed");
21328                    } else {
21329                        for (int j = 0; j < N; j++) {
21330                            final String pkgName = changes.valueAt(j);
21331                            final int sequenceNumber = changes.keyAt(j);
21332                            pw.print("    ");
21333                            pw.print("seq=");
21334                            pw.print(sequenceNumber);
21335                            pw.print(", package=");
21336                            pw.println(pkgName);
21337                        }
21338                    }
21339                }
21340            }
21341
21342            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21343                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21344            }
21345
21346            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21347                // XXX should handle packageName != null by dumping only install data that
21348                // the given package is involved with.
21349                if (dumpState.onTitlePrinted()) pw.println();
21350
21351                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21352                ipw.println();
21353                ipw.println("Frozen packages:");
21354                ipw.increaseIndent();
21355                if (mFrozenPackages.size() == 0) {
21356                    ipw.println("(none)");
21357                } else {
21358                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21359                        ipw.println(mFrozenPackages.valueAt(i));
21360                    }
21361                }
21362                ipw.decreaseIndent();
21363            }
21364
21365            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21366                if (dumpState.onTitlePrinted()) pw.println();
21367                dumpDexoptStateLPr(pw, packageName);
21368            }
21369
21370            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21371                if (dumpState.onTitlePrinted()) pw.println();
21372                dumpCompilerStatsLPr(pw, packageName);
21373            }
21374
21375            if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) {
21376                if (dumpState.onTitlePrinted()) pw.println();
21377                dumpEnabledOverlaysLPr(pw);
21378            }
21379
21380            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21381                if (dumpState.onTitlePrinted()) pw.println();
21382                mSettings.dumpReadMessagesLPr(pw, dumpState);
21383
21384                pw.println();
21385                pw.println("Package warning messages:");
21386                BufferedReader in = null;
21387                String line = null;
21388                try {
21389                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21390                    while ((line = in.readLine()) != null) {
21391                        if (line.contains("ignored: updated version")) continue;
21392                        pw.println(line);
21393                    }
21394                } catch (IOException ignored) {
21395                } finally {
21396                    IoUtils.closeQuietly(in);
21397                }
21398            }
21399
21400            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21401                BufferedReader in = null;
21402                String line = null;
21403                try {
21404                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21405                    while ((line = in.readLine()) != null) {
21406                        if (line.contains("ignored: updated version")) continue;
21407                        pw.print("msg,");
21408                        pw.println(line);
21409                    }
21410                } catch (IOException ignored) {
21411                } finally {
21412                    IoUtils.closeQuietly(in);
21413                }
21414            }
21415        }
21416
21417        // PackageInstaller should be called outside of mPackages lock
21418        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21419            // XXX should handle packageName != null by dumping only install data that
21420            // the given package is involved with.
21421            if (dumpState.onTitlePrinted()) pw.println();
21422            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21423        }
21424    }
21425
21426    private void dumpProto(FileDescriptor fd) {
21427        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21428
21429        synchronized (mPackages) {
21430            final long requiredVerifierPackageToken =
21431                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21432            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21433            proto.write(
21434                    PackageServiceDumpProto.PackageShortProto.UID,
21435                    getPackageUid(
21436                            mRequiredVerifierPackage,
21437                            MATCH_DEBUG_TRIAGED_MISSING,
21438                            UserHandle.USER_SYSTEM));
21439            proto.end(requiredVerifierPackageToken);
21440
21441            if (mIntentFilterVerifierComponent != null) {
21442                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21443                final long verifierPackageToken =
21444                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21445                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21446                proto.write(
21447                        PackageServiceDumpProto.PackageShortProto.UID,
21448                        getPackageUid(
21449                                verifierPackageName,
21450                                MATCH_DEBUG_TRIAGED_MISSING,
21451                                UserHandle.USER_SYSTEM));
21452                proto.end(verifierPackageToken);
21453            }
21454
21455            dumpSharedLibrariesProto(proto);
21456            dumpFeaturesProto(proto);
21457            mSettings.dumpPackagesProto(proto);
21458            mSettings.dumpSharedUsersProto(proto);
21459            dumpMessagesProto(proto);
21460        }
21461        proto.flush();
21462    }
21463
21464    private void dumpMessagesProto(ProtoOutputStream proto) {
21465        BufferedReader in = null;
21466        String line = null;
21467        try {
21468            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21469            while ((line = in.readLine()) != null) {
21470                if (line.contains("ignored: updated version")) continue;
21471                proto.write(PackageServiceDumpProto.MESSAGES, line);
21472            }
21473        } catch (IOException ignored) {
21474        } finally {
21475            IoUtils.closeQuietly(in);
21476        }
21477    }
21478
21479    private void dumpFeaturesProto(ProtoOutputStream proto) {
21480        synchronized (mAvailableFeatures) {
21481            final int count = mAvailableFeatures.size();
21482            for (int i = 0; i < count; i++) {
21483                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
21484                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
21485                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
21486                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
21487                proto.end(featureToken);
21488            }
21489        }
21490    }
21491
21492    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21493        final int count = mSharedLibraries.size();
21494        for (int i = 0; i < count; i++) {
21495            final String libName = mSharedLibraries.keyAt(i);
21496            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21497            if (versionedLib == null) {
21498                continue;
21499            }
21500            final int versionCount = versionedLib.size();
21501            for (int j = 0; j < versionCount; j++) {
21502                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21503                final long sharedLibraryToken =
21504                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21505                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21506                final boolean isJar = (libEntry.path != null);
21507                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21508                if (isJar) {
21509                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21510                } else {
21511                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21512                }
21513                proto.end(sharedLibraryToken);
21514            }
21515        }
21516    }
21517
21518    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21519        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21520        ipw.println();
21521        ipw.println("Dexopt state:");
21522        ipw.increaseIndent();
21523        Collection<PackageParser.Package> packages = null;
21524        if (packageName != null) {
21525            PackageParser.Package targetPackage = mPackages.get(packageName);
21526            if (targetPackage != null) {
21527                packages = Collections.singletonList(targetPackage);
21528            } else {
21529                ipw.println("Unable to find package: " + packageName);
21530                return;
21531            }
21532        } else {
21533            packages = mPackages.values();
21534        }
21535
21536        for (PackageParser.Package pkg : packages) {
21537            ipw.println("[" + pkg.packageName + "]");
21538            ipw.increaseIndent();
21539            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
21540            ipw.decreaseIndent();
21541        }
21542    }
21543
21544    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21545        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21546        ipw.println();
21547        ipw.println("Compiler stats:");
21548        ipw.increaseIndent();
21549        Collection<PackageParser.Package> packages = null;
21550        if (packageName != null) {
21551            PackageParser.Package targetPackage = mPackages.get(packageName);
21552            if (targetPackage != null) {
21553                packages = Collections.singletonList(targetPackage);
21554            } else {
21555                ipw.println("Unable to find package: " + packageName);
21556                return;
21557            }
21558        } else {
21559            packages = mPackages.values();
21560        }
21561
21562        for (PackageParser.Package pkg : packages) {
21563            ipw.println("[" + pkg.packageName + "]");
21564            ipw.increaseIndent();
21565
21566            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21567            if (stats == null) {
21568                ipw.println("(No recorded stats)");
21569            } else {
21570                stats.dump(ipw);
21571            }
21572            ipw.decreaseIndent();
21573        }
21574    }
21575
21576    private void dumpEnabledOverlaysLPr(PrintWriter pw) {
21577        pw.println("Enabled overlay paths:");
21578        final int N = mEnabledOverlayPaths.size();
21579        for (int i = 0; i < N; i++) {
21580            final int userId = mEnabledOverlayPaths.keyAt(i);
21581            pw.println(String.format("    User %d:", userId));
21582            final ArrayMap<String, ArrayList<String>> userSpecificOverlays =
21583                mEnabledOverlayPaths.valueAt(i);
21584            final int M = userSpecificOverlays.size();
21585            for (int j = 0; j < M; j++) {
21586                final String targetPackageName = userSpecificOverlays.keyAt(j);
21587                final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j);
21588                pw.println(String.format("        %s: %s", targetPackageName, overlayPackagePaths));
21589            }
21590        }
21591    }
21592
21593    private String dumpDomainString(String packageName) {
21594        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21595                .getList();
21596        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21597
21598        ArraySet<String> result = new ArraySet<>();
21599        if (iviList.size() > 0) {
21600            for (IntentFilterVerificationInfo ivi : iviList) {
21601                for (String host : ivi.getDomains()) {
21602                    result.add(host);
21603                }
21604            }
21605        }
21606        if (filters != null && filters.size() > 0) {
21607            for (IntentFilter filter : filters) {
21608                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21609                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21610                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21611                    result.addAll(filter.getHostsList());
21612                }
21613            }
21614        }
21615
21616        StringBuilder sb = new StringBuilder(result.size() * 16);
21617        for (String domain : result) {
21618            if (sb.length() > 0) sb.append(" ");
21619            sb.append(domain);
21620        }
21621        return sb.toString();
21622    }
21623
21624    // ------- apps on sdcard specific code -------
21625    static final boolean DEBUG_SD_INSTALL = false;
21626
21627    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21628
21629    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21630
21631    private boolean mMediaMounted = false;
21632
21633    static String getEncryptKey() {
21634        try {
21635            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21636                    SD_ENCRYPTION_KEYSTORE_NAME);
21637            if (sdEncKey == null) {
21638                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21639                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21640                if (sdEncKey == null) {
21641                    Slog.e(TAG, "Failed to create encryption keys");
21642                    return null;
21643                }
21644            }
21645            return sdEncKey;
21646        } catch (NoSuchAlgorithmException nsae) {
21647            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21648            return null;
21649        } catch (IOException ioe) {
21650            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21651            return null;
21652        }
21653    }
21654
21655    /*
21656     * Update media status on PackageManager.
21657     */
21658    @Override
21659    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
21660        int callingUid = Binder.getCallingUid();
21661        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
21662            throw new SecurityException("Media status can only be updated by the system");
21663        }
21664        // reader; this apparently protects mMediaMounted, but should probably
21665        // be a different lock in that case.
21666        synchronized (mPackages) {
21667            Log.i(TAG, "Updating external media status from "
21668                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
21669                    + (mediaStatus ? "mounted" : "unmounted"));
21670            if (DEBUG_SD_INSTALL)
21671                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
21672                        + ", mMediaMounted=" + mMediaMounted);
21673            if (mediaStatus == mMediaMounted) {
21674                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
21675                        : 0, -1);
21676                mHandler.sendMessage(msg);
21677                return;
21678            }
21679            mMediaMounted = mediaStatus;
21680        }
21681        // Queue up an async operation since the package installation may take a
21682        // little while.
21683        mHandler.post(new Runnable() {
21684            public void run() {
21685                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
21686            }
21687        });
21688    }
21689
21690    /**
21691     * Called by StorageManagerService when the initial ASECs to scan are available.
21692     * Should block until all the ASEC containers are finished being scanned.
21693     */
21694    public void scanAvailableAsecs() {
21695        updateExternalMediaStatusInner(true, false, false);
21696    }
21697
21698    /*
21699     * Collect information of applications on external media, map them against
21700     * existing containers and update information based on current mount status.
21701     * Please note that we always have to report status if reportStatus has been
21702     * set to true especially when unloading packages.
21703     */
21704    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
21705            boolean externalStorage) {
21706        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
21707        int[] uidArr = EmptyArray.INT;
21708
21709        final String[] list = PackageHelper.getSecureContainerList();
21710        if (ArrayUtils.isEmpty(list)) {
21711            Log.i(TAG, "No secure containers found");
21712        } else {
21713            // Process list of secure containers and categorize them
21714            // as active or stale based on their package internal state.
21715
21716            // reader
21717            synchronized (mPackages) {
21718                for (String cid : list) {
21719                    // Leave stages untouched for now; installer service owns them
21720                    if (PackageInstallerService.isStageName(cid)) continue;
21721
21722                    if (DEBUG_SD_INSTALL)
21723                        Log.i(TAG, "Processing container " + cid);
21724                    String pkgName = getAsecPackageName(cid);
21725                    if (pkgName == null) {
21726                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
21727                        continue;
21728                    }
21729                    if (DEBUG_SD_INSTALL)
21730                        Log.i(TAG, "Looking for pkg : " + pkgName);
21731
21732                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
21733                    if (ps == null) {
21734                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
21735                        continue;
21736                    }
21737
21738                    /*
21739                     * Skip packages that are not external if we're unmounting
21740                     * external storage.
21741                     */
21742                    if (externalStorage && !isMounted && !isExternal(ps)) {
21743                        continue;
21744                    }
21745
21746                    final AsecInstallArgs args = new AsecInstallArgs(cid,
21747                            getAppDexInstructionSets(ps), ps.isForwardLocked());
21748                    // The package status is changed only if the code path
21749                    // matches between settings and the container id.
21750                    if (ps.codePathString != null
21751                            && ps.codePathString.startsWith(args.getCodePath())) {
21752                        if (DEBUG_SD_INSTALL) {
21753                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
21754                                    + " at code path: " + ps.codePathString);
21755                        }
21756
21757                        // We do have a valid package installed on sdcard
21758                        processCids.put(args, ps.codePathString);
21759                        final int uid = ps.appId;
21760                        if (uid != -1) {
21761                            uidArr = ArrayUtils.appendInt(uidArr, uid);
21762                        }
21763                    } else {
21764                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
21765                                + ps.codePathString);
21766                    }
21767                }
21768            }
21769
21770            Arrays.sort(uidArr);
21771        }
21772
21773        // Process packages with valid entries.
21774        if (isMounted) {
21775            if (DEBUG_SD_INSTALL)
21776                Log.i(TAG, "Loading packages");
21777            loadMediaPackages(processCids, uidArr, externalStorage);
21778            startCleaningPackages();
21779            mInstallerService.onSecureContainersAvailable();
21780        } else {
21781            if (DEBUG_SD_INSTALL)
21782                Log.i(TAG, "Unloading packages");
21783            unloadMediaPackages(processCids, uidArr, reportStatus);
21784        }
21785    }
21786
21787    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21788            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21789        final int size = infos.size();
21790        final String[] packageNames = new String[size];
21791        final int[] packageUids = new int[size];
21792        for (int i = 0; i < size; i++) {
21793            final ApplicationInfo info = infos.get(i);
21794            packageNames[i] = info.packageName;
21795            packageUids[i] = info.uid;
21796        }
21797        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21798                finishedReceiver);
21799    }
21800
21801    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21802            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21803        sendResourcesChangedBroadcast(mediaStatus, replacing,
21804                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21805    }
21806
21807    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21808            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21809        int size = pkgList.length;
21810        if (size > 0) {
21811            // Send broadcasts here
21812            Bundle extras = new Bundle();
21813            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21814            if (uidArr != null) {
21815                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21816            }
21817            if (replacing) {
21818                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21819            }
21820            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21821                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21822            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21823        }
21824    }
21825
21826   /*
21827     * Look at potentially valid container ids from processCids If package
21828     * information doesn't match the one on record or package scanning fails,
21829     * the cid is added to list of removeCids. We currently don't delete stale
21830     * containers.
21831     */
21832    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
21833            boolean externalStorage) {
21834        ArrayList<String> pkgList = new ArrayList<String>();
21835        Set<AsecInstallArgs> keys = processCids.keySet();
21836
21837        for (AsecInstallArgs args : keys) {
21838            String codePath = processCids.get(args);
21839            if (DEBUG_SD_INSTALL)
21840                Log.i(TAG, "Loading container : " + args.cid);
21841            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
21842            try {
21843                // Make sure there are no container errors first.
21844                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
21845                    Slog.e(TAG, "Failed to mount cid : " + args.cid
21846                            + " when installing from sdcard");
21847                    continue;
21848                }
21849                // Check code path here.
21850                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
21851                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
21852                            + " does not match one in settings " + codePath);
21853                    continue;
21854                }
21855                // Parse package
21856                int parseFlags = mDefParseFlags;
21857                if (args.isExternalAsec()) {
21858                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21859                }
21860                if (args.isFwdLocked()) {
21861                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21862                }
21863
21864                synchronized (mInstallLock) {
21865                    PackageParser.Package pkg = null;
21866                    try {
21867                        // Sadly we don't know the package name yet to freeze it
21868                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21869                                SCAN_IGNORE_FROZEN, 0, null);
21870                    } catch (PackageManagerException e) {
21871                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21872                    }
21873                    // Scan the package
21874                    if (pkg != null) {
21875                        /*
21876                         * TODO why is the lock being held? doPostInstall is
21877                         * called in other places without the lock. This needs
21878                         * to be straightened out.
21879                         */
21880                        // writer
21881                        synchronized (mPackages) {
21882                            retCode = PackageManager.INSTALL_SUCCEEDED;
21883                            pkgList.add(pkg.packageName);
21884                            // Post process args
21885                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21886                                    pkg.applicationInfo.uid);
21887                        }
21888                    } else {
21889                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21890                    }
21891                }
21892
21893            } finally {
21894                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21895                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21896                }
21897            }
21898        }
21899        // writer
21900        synchronized (mPackages) {
21901            // If the platform SDK has changed since the last time we booted,
21902            // we need to re-grant app permission to catch any new ones that
21903            // appear. This is really a hack, and means that apps can in some
21904            // cases get permissions that the user didn't initially explicitly
21905            // allow... it would be nice to have some better way to handle
21906            // this situation.
21907            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21908                    : mSettings.getInternalVersion();
21909            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21910                    : StorageManager.UUID_PRIVATE_INTERNAL;
21911
21912            int updateFlags = UPDATE_PERMISSIONS_ALL;
21913            if (ver.sdkVersion != mSdkVersion) {
21914                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21915                        + mSdkVersion + "; regranting permissions for external");
21916                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21917            }
21918            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21919
21920            // Yay, everything is now upgraded
21921            ver.forceCurrent();
21922
21923            // can downgrade to reader
21924            // Persist settings
21925            mSettings.writeLPr();
21926        }
21927        // Send a broadcast to let everyone know we are done processing
21928        if (pkgList.size() > 0) {
21929            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21930        }
21931    }
21932
21933   /*
21934     * Utility method to unload a list of specified containers
21935     */
21936    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21937        // Just unmount all valid containers.
21938        for (AsecInstallArgs arg : cidArgs) {
21939            synchronized (mInstallLock) {
21940                arg.doPostDeleteLI(false);
21941           }
21942       }
21943   }
21944
21945    /*
21946     * Unload packages mounted on external media. This involves deleting package
21947     * data from internal structures, sending broadcasts about disabled packages,
21948     * gc'ing to free up references, unmounting all secure containers
21949     * corresponding to packages on external media, and posting a
21950     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21951     * that we always have to post this message if status has been requested no
21952     * matter what.
21953     */
21954    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21955            final boolean reportStatus) {
21956        if (DEBUG_SD_INSTALL)
21957            Log.i(TAG, "unloading media packages");
21958        ArrayList<String> pkgList = new ArrayList<String>();
21959        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21960        final Set<AsecInstallArgs> keys = processCids.keySet();
21961        for (AsecInstallArgs args : keys) {
21962            String pkgName = args.getPackageName();
21963            if (DEBUG_SD_INSTALL)
21964                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21965            // Delete package internally
21966            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21967            synchronized (mInstallLock) {
21968                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21969                final boolean res;
21970                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21971                        "unloadMediaPackages")) {
21972                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21973                            null);
21974                }
21975                if (res) {
21976                    pkgList.add(pkgName);
21977                } else {
21978                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21979                    failedList.add(args);
21980                }
21981            }
21982        }
21983
21984        // reader
21985        synchronized (mPackages) {
21986            // We didn't update the settings after removing each package;
21987            // write them now for all packages.
21988            mSettings.writeLPr();
21989        }
21990
21991        // We have to absolutely send UPDATED_MEDIA_STATUS only
21992        // after confirming that all the receivers processed the ordered
21993        // broadcast when packages get disabled, force a gc to clean things up.
21994        // and unload all the containers.
21995        if (pkgList.size() > 0) {
21996            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21997                    new IIntentReceiver.Stub() {
21998                public void performReceive(Intent intent, int resultCode, String data,
21999                        Bundle extras, boolean ordered, boolean sticky,
22000                        int sendingUser) throws RemoteException {
22001                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
22002                            reportStatus ? 1 : 0, 1, keys);
22003                    mHandler.sendMessage(msg);
22004                }
22005            });
22006        } else {
22007            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
22008                    keys);
22009            mHandler.sendMessage(msg);
22010        }
22011    }
22012
22013    private void loadPrivatePackages(final VolumeInfo vol) {
22014        mHandler.post(new Runnable() {
22015            @Override
22016            public void run() {
22017                loadPrivatePackagesInner(vol);
22018            }
22019        });
22020    }
22021
22022    private void loadPrivatePackagesInner(VolumeInfo vol) {
22023        final String volumeUuid = vol.fsUuid;
22024        if (TextUtils.isEmpty(volumeUuid)) {
22025            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22026            return;
22027        }
22028
22029        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22030        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22031        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22032
22033        final VersionInfo ver;
22034        final List<PackageSetting> packages;
22035        synchronized (mPackages) {
22036            ver = mSettings.findOrCreateVersion(volumeUuid);
22037            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22038        }
22039
22040        for (PackageSetting ps : packages) {
22041            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22042            synchronized (mInstallLock) {
22043                final PackageParser.Package pkg;
22044                try {
22045                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22046                    loaded.add(pkg.applicationInfo);
22047
22048                } catch (PackageManagerException e) {
22049                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22050                }
22051
22052                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22053                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22054                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22055                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22056                }
22057            }
22058        }
22059
22060        // Reconcile app data for all started/unlocked users
22061        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22062        final UserManager um = mContext.getSystemService(UserManager.class);
22063        UserManagerInternal umInternal = getUserManagerInternal();
22064        for (UserInfo user : um.getUsers()) {
22065            final int flags;
22066            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22067                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22068            } else if (umInternal.isUserRunning(user.id)) {
22069                flags = StorageManager.FLAG_STORAGE_DE;
22070            } else {
22071                continue;
22072            }
22073
22074            try {
22075                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22076                synchronized (mInstallLock) {
22077                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22078                }
22079            } catch (IllegalStateException e) {
22080                // Device was probably ejected, and we'll process that event momentarily
22081                Slog.w(TAG, "Failed to prepare storage: " + e);
22082            }
22083        }
22084
22085        synchronized (mPackages) {
22086            int updateFlags = UPDATE_PERMISSIONS_ALL;
22087            if (ver.sdkVersion != mSdkVersion) {
22088                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22089                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22090                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22091            }
22092            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22093
22094            // Yay, everything is now upgraded
22095            ver.forceCurrent();
22096
22097            mSettings.writeLPr();
22098        }
22099
22100        for (PackageFreezer freezer : freezers) {
22101            freezer.close();
22102        }
22103
22104        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22105        sendResourcesChangedBroadcast(true, false, loaded, null);
22106    }
22107
22108    private void unloadPrivatePackages(final VolumeInfo vol) {
22109        mHandler.post(new Runnable() {
22110            @Override
22111            public void run() {
22112                unloadPrivatePackagesInner(vol);
22113            }
22114        });
22115    }
22116
22117    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22118        final String volumeUuid = vol.fsUuid;
22119        if (TextUtils.isEmpty(volumeUuid)) {
22120            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22121            return;
22122        }
22123
22124        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22125        synchronized (mInstallLock) {
22126        synchronized (mPackages) {
22127            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22128            for (PackageSetting ps : packages) {
22129                if (ps.pkg == null) continue;
22130
22131                final ApplicationInfo info = ps.pkg.applicationInfo;
22132                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22133                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22134
22135                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22136                        "unloadPrivatePackagesInner")) {
22137                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22138                            false, null)) {
22139                        unloaded.add(info);
22140                    } else {
22141                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22142                    }
22143                }
22144
22145                // Try very hard to release any references to this package
22146                // so we don't risk the system server being killed due to
22147                // open FDs
22148                AttributeCache.instance().removePackage(ps.name);
22149            }
22150
22151            mSettings.writeLPr();
22152        }
22153        }
22154
22155        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22156        sendResourcesChangedBroadcast(false, false, unloaded, null);
22157
22158        // Try very hard to release any references to this path so we don't risk
22159        // the system server being killed due to open FDs
22160        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22161
22162        for (int i = 0; i < 3; i++) {
22163            System.gc();
22164            System.runFinalization();
22165        }
22166    }
22167
22168    private void assertPackageKnown(String volumeUuid, String packageName)
22169            throws PackageManagerException {
22170        synchronized (mPackages) {
22171            // Normalize package name to handle renamed packages
22172            packageName = normalizePackageNameLPr(packageName);
22173
22174            final PackageSetting ps = mSettings.mPackages.get(packageName);
22175            if (ps == null) {
22176                throw new PackageManagerException("Package " + packageName + " is unknown");
22177            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22178                throw new PackageManagerException(
22179                        "Package " + packageName + " found on unknown volume " + volumeUuid
22180                                + "; expected volume " + ps.volumeUuid);
22181            }
22182        }
22183    }
22184
22185    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22186            throws PackageManagerException {
22187        synchronized (mPackages) {
22188            // Normalize package name to handle renamed packages
22189            packageName = normalizePackageNameLPr(packageName);
22190
22191            final PackageSetting ps = mSettings.mPackages.get(packageName);
22192            if (ps == null) {
22193                throw new PackageManagerException("Package " + packageName + " is unknown");
22194            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22195                throw new PackageManagerException(
22196                        "Package " + packageName + " found on unknown volume " + volumeUuid
22197                                + "; expected volume " + ps.volumeUuid);
22198            } else if (!ps.getInstalled(userId)) {
22199                throw new PackageManagerException(
22200                        "Package " + packageName + " not installed for user " + userId);
22201            }
22202        }
22203    }
22204
22205    private List<String> collectAbsoluteCodePaths() {
22206        synchronized (mPackages) {
22207            List<String> codePaths = new ArrayList<>();
22208            final int packageCount = mSettings.mPackages.size();
22209            for (int i = 0; i < packageCount; i++) {
22210                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22211                codePaths.add(ps.codePath.getAbsolutePath());
22212            }
22213            return codePaths;
22214        }
22215    }
22216
22217    /**
22218     * Examine all apps present on given mounted volume, and destroy apps that
22219     * aren't expected, either due to uninstallation or reinstallation on
22220     * another volume.
22221     */
22222    private void reconcileApps(String volumeUuid) {
22223        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22224        List<File> filesToDelete = null;
22225
22226        final File[] files = FileUtils.listFilesOrEmpty(
22227                Environment.getDataAppDirectory(volumeUuid));
22228        for (File file : files) {
22229            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22230                    && !PackageInstallerService.isStageName(file.getName());
22231            if (!isPackage) {
22232                // Ignore entries which are not packages
22233                continue;
22234            }
22235
22236            String absolutePath = file.getAbsolutePath();
22237
22238            boolean pathValid = false;
22239            final int absoluteCodePathCount = absoluteCodePaths.size();
22240            for (int i = 0; i < absoluteCodePathCount; i++) {
22241                String absoluteCodePath = absoluteCodePaths.get(i);
22242                if (absolutePath.startsWith(absoluteCodePath)) {
22243                    pathValid = true;
22244                    break;
22245                }
22246            }
22247
22248            if (!pathValid) {
22249                if (filesToDelete == null) {
22250                    filesToDelete = new ArrayList<>();
22251                }
22252                filesToDelete.add(file);
22253            }
22254        }
22255
22256        if (filesToDelete != null) {
22257            final int fileToDeleteCount = filesToDelete.size();
22258            for (int i = 0; i < fileToDeleteCount; i++) {
22259                File fileToDelete = filesToDelete.get(i);
22260                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22261                synchronized (mInstallLock) {
22262                    removeCodePathLI(fileToDelete);
22263                }
22264            }
22265        }
22266    }
22267
22268    /**
22269     * Reconcile all app data for the given user.
22270     * <p>
22271     * Verifies that directories exist and that ownership and labeling is
22272     * correct for all installed apps on all mounted volumes.
22273     */
22274    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22275        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22276        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22277            final String volumeUuid = vol.getFsUuid();
22278            synchronized (mInstallLock) {
22279                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22280            }
22281        }
22282    }
22283
22284    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22285            boolean migrateAppData) {
22286        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22287    }
22288
22289    /**
22290     * Reconcile all app data on given mounted volume.
22291     * <p>
22292     * Destroys app data that isn't expected, either due to uninstallation or
22293     * reinstallation on another volume.
22294     * <p>
22295     * Verifies that directories exist and that ownership and labeling is
22296     * correct for all installed apps.
22297     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22298     */
22299    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22300            boolean migrateAppData, boolean onlyCoreApps) {
22301        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22302                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22303        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22304
22305        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22306        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22307
22308        // First look for stale data that doesn't belong, and check if things
22309        // have changed since we did our last restorecon
22310        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22311            if (StorageManager.isFileEncryptedNativeOrEmulated()
22312                    && !StorageManager.isUserKeyUnlocked(userId)) {
22313                throw new RuntimeException(
22314                        "Yikes, someone asked us to reconcile CE storage while " + userId
22315                                + " was still locked; this would have caused massive data loss!");
22316            }
22317
22318            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22319            for (File file : files) {
22320                final String packageName = file.getName();
22321                try {
22322                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22323                } catch (PackageManagerException e) {
22324                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22325                    try {
22326                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22327                                StorageManager.FLAG_STORAGE_CE, 0);
22328                    } catch (InstallerException e2) {
22329                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22330                    }
22331                }
22332            }
22333        }
22334        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22335            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22336            for (File file : files) {
22337                final String packageName = file.getName();
22338                try {
22339                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22340                } catch (PackageManagerException e) {
22341                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22342                    try {
22343                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22344                                StorageManager.FLAG_STORAGE_DE, 0);
22345                    } catch (InstallerException e2) {
22346                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22347                    }
22348                }
22349            }
22350        }
22351
22352        // Ensure that data directories are ready to roll for all packages
22353        // installed for this volume and user
22354        final List<PackageSetting> packages;
22355        synchronized (mPackages) {
22356            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22357        }
22358        int preparedCount = 0;
22359        for (PackageSetting ps : packages) {
22360            final String packageName = ps.name;
22361            if (ps.pkg == null) {
22362                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22363                // TODO: might be due to legacy ASEC apps; we should circle back
22364                // and reconcile again once they're scanned
22365                continue;
22366            }
22367            // Skip non-core apps if requested
22368            if (onlyCoreApps && !ps.pkg.coreApp) {
22369                result.add(packageName);
22370                continue;
22371            }
22372
22373            if (ps.getInstalled(userId)) {
22374                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22375                preparedCount++;
22376            }
22377        }
22378
22379        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22380        return result;
22381    }
22382
22383    /**
22384     * Prepare app data for the given app just after it was installed or
22385     * upgraded. This method carefully only touches users that it's installed
22386     * for, and it forces a restorecon to handle any seinfo changes.
22387     * <p>
22388     * Verifies that directories exist and that ownership and labeling is
22389     * correct for all installed apps. If there is an ownership mismatch, it
22390     * will try recovering system apps by wiping data; third-party app data is
22391     * left intact.
22392     * <p>
22393     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22394     */
22395    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22396        final PackageSetting ps;
22397        synchronized (mPackages) {
22398            ps = mSettings.mPackages.get(pkg.packageName);
22399            mSettings.writeKernelMappingLPr(ps);
22400        }
22401
22402        final UserManager um = mContext.getSystemService(UserManager.class);
22403        UserManagerInternal umInternal = getUserManagerInternal();
22404        for (UserInfo user : um.getUsers()) {
22405            final int flags;
22406            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22407                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22408            } else if (umInternal.isUserRunning(user.id)) {
22409                flags = StorageManager.FLAG_STORAGE_DE;
22410            } else {
22411                continue;
22412            }
22413
22414            if (ps.getInstalled(user.id)) {
22415                // TODO: when user data is locked, mark that we're still dirty
22416                prepareAppDataLIF(pkg, user.id, flags);
22417            }
22418        }
22419    }
22420
22421    /**
22422     * Prepare app data for the given app.
22423     * <p>
22424     * Verifies that directories exist and that ownership and labeling is
22425     * correct for all installed apps. If there is an ownership mismatch, this
22426     * will try recovering system apps by wiping data; third-party app data is
22427     * left intact.
22428     */
22429    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22430        if (pkg == null) {
22431            Slog.wtf(TAG, "Package was null!", new Throwable());
22432            return;
22433        }
22434        prepareAppDataLeafLIF(pkg, userId, flags);
22435        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22436        for (int i = 0; i < childCount; i++) {
22437            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22438        }
22439    }
22440
22441    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22442            boolean maybeMigrateAppData) {
22443        prepareAppDataLIF(pkg, userId, flags);
22444
22445        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22446            // We may have just shuffled around app data directories, so
22447            // prepare them one more time
22448            prepareAppDataLIF(pkg, userId, flags);
22449        }
22450    }
22451
22452    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22453        if (DEBUG_APP_DATA) {
22454            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22455                    + Integer.toHexString(flags));
22456        }
22457
22458        final String volumeUuid = pkg.volumeUuid;
22459        final String packageName = pkg.packageName;
22460        final ApplicationInfo app = pkg.applicationInfo;
22461        final int appId = UserHandle.getAppId(app.uid);
22462
22463        Preconditions.checkNotNull(app.seInfo);
22464
22465        long ceDataInode = -1;
22466        try {
22467            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22468                    appId, app.seInfo, app.targetSdkVersion);
22469        } catch (InstallerException e) {
22470            if (app.isSystemApp()) {
22471                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22472                        + ", but trying to recover: " + e);
22473                destroyAppDataLeafLIF(pkg, userId, flags);
22474                try {
22475                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22476                            appId, app.seInfo, app.targetSdkVersion);
22477                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22478                } catch (InstallerException e2) {
22479                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22480                }
22481            } else {
22482                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22483            }
22484        }
22485
22486        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22487            // TODO: mark this structure as dirty so we persist it!
22488            synchronized (mPackages) {
22489                final PackageSetting ps = mSettings.mPackages.get(packageName);
22490                if (ps != null) {
22491                    ps.setCeDataInode(ceDataInode, userId);
22492                }
22493            }
22494        }
22495
22496        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22497    }
22498
22499    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22500        if (pkg == null) {
22501            Slog.wtf(TAG, "Package was null!", new Throwable());
22502            return;
22503        }
22504        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22505        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22506        for (int i = 0; i < childCount; i++) {
22507            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22508        }
22509    }
22510
22511    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22512        final String volumeUuid = pkg.volumeUuid;
22513        final String packageName = pkg.packageName;
22514        final ApplicationInfo app = pkg.applicationInfo;
22515
22516        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22517            // Create a native library symlink only if we have native libraries
22518            // and if the native libraries are 32 bit libraries. We do not provide
22519            // this symlink for 64 bit libraries.
22520            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22521                final String nativeLibPath = app.nativeLibraryDir;
22522                try {
22523                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22524                            nativeLibPath, userId);
22525                } catch (InstallerException e) {
22526                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22527                }
22528            }
22529        }
22530    }
22531
22532    /**
22533     * For system apps on non-FBE devices, this method migrates any existing
22534     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22535     * requested by the app.
22536     */
22537    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22538        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
22539                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22540            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22541                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22542            try {
22543                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22544                        storageTarget);
22545            } catch (InstallerException e) {
22546                logCriticalInfo(Log.WARN,
22547                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22548            }
22549            return true;
22550        } else {
22551            return false;
22552        }
22553    }
22554
22555    public PackageFreezer freezePackage(String packageName, String killReason) {
22556        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22557    }
22558
22559    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22560        return new PackageFreezer(packageName, userId, killReason);
22561    }
22562
22563    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22564            String killReason) {
22565        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22566    }
22567
22568    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22569            String killReason) {
22570        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22571            return new PackageFreezer();
22572        } else {
22573            return freezePackage(packageName, userId, killReason);
22574        }
22575    }
22576
22577    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22578            String killReason) {
22579        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22580    }
22581
22582    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22583            String killReason) {
22584        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22585            return new PackageFreezer();
22586        } else {
22587            return freezePackage(packageName, userId, killReason);
22588        }
22589    }
22590
22591    /**
22592     * Class that freezes and kills the given package upon creation, and
22593     * unfreezes it upon closing. This is typically used when doing surgery on
22594     * app code/data to prevent the app from running while you're working.
22595     */
22596    private class PackageFreezer implements AutoCloseable {
22597        private final String mPackageName;
22598        private final PackageFreezer[] mChildren;
22599
22600        private final boolean mWeFroze;
22601
22602        private final AtomicBoolean mClosed = new AtomicBoolean();
22603        private final CloseGuard mCloseGuard = CloseGuard.get();
22604
22605        /**
22606         * Create and return a stub freezer that doesn't actually do anything,
22607         * typically used when someone requested
22608         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22609         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22610         */
22611        public PackageFreezer() {
22612            mPackageName = null;
22613            mChildren = null;
22614            mWeFroze = false;
22615            mCloseGuard.open("close");
22616        }
22617
22618        public PackageFreezer(String packageName, int userId, String killReason) {
22619            synchronized (mPackages) {
22620                mPackageName = packageName;
22621                mWeFroze = mFrozenPackages.add(mPackageName);
22622
22623                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22624                if (ps != null) {
22625                    killApplication(ps.name, ps.appId, userId, killReason);
22626                }
22627
22628                final PackageParser.Package p = mPackages.get(packageName);
22629                if (p != null && p.childPackages != null) {
22630                    final int N = p.childPackages.size();
22631                    mChildren = new PackageFreezer[N];
22632                    for (int i = 0; i < N; i++) {
22633                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22634                                userId, killReason);
22635                    }
22636                } else {
22637                    mChildren = null;
22638                }
22639            }
22640            mCloseGuard.open("close");
22641        }
22642
22643        @Override
22644        protected void finalize() throws Throwable {
22645            try {
22646                mCloseGuard.warnIfOpen();
22647                close();
22648            } finally {
22649                super.finalize();
22650            }
22651        }
22652
22653        @Override
22654        public void close() {
22655            mCloseGuard.close();
22656            if (mClosed.compareAndSet(false, true)) {
22657                synchronized (mPackages) {
22658                    if (mWeFroze) {
22659                        mFrozenPackages.remove(mPackageName);
22660                    }
22661
22662                    if (mChildren != null) {
22663                        for (PackageFreezer freezer : mChildren) {
22664                            freezer.close();
22665                        }
22666                    }
22667                }
22668            }
22669        }
22670    }
22671
22672    /**
22673     * Verify that given package is currently frozen.
22674     */
22675    private void checkPackageFrozen(String packageName) {
22676        synchronized (mPackages) {
22677            if (!mFrozenPackages.contains(packageName)) {
22678                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22679            }
22680        }
22681    }
22682
22683    @Override
22684    public int movePackage(final String packageName, final String volumeUuid) {
22685        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22686
22687        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
22688        final int moveId = mNextMoveId.getAndIncrement();
22689        mHandler.post(new Runnable() {
22690            @Override
22691            public void run() {
22692                try {
22693                    movePackageInternal(packageName, volumeUuid, moveId, user);
22694                } catch (PackageManagerException e) {
22695                    Slog.w(TAG, "Failed to move " + packageName, e);
22696                    mMoveCallbacks.notifyStatusChanged(moveId,
22697                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22698                }
22699            }
22700        });
22701        return moveId;
22702    }
22703
22704    private void movePackageInternal(final String packageName, final String volumeUuid,
22705            final int moveId, UserHandle user) throws PackageManagerException {
22706        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22707        final PackageManager pm = mContext.getPackageManager();
22708
22709        final boolean currentAsec;
22710        final String currentVolumeUuid;
22711        final File codeFile;
22712        final String installerPackageName;
22713        final String packageAbiOverride;
22714        final int appId;
22715        final String seinfo;
22716        final String label;
22717        final int targetSdkVersion;
22718        final PackageFreezer freezer;
22719        final int[] installedUserIds;
22720
22721        // reader
22722        synchronized (mPackages) {
22723            final PackageParser.Package pkg = mPackages.get(packageName);
22724            final PackageSetting ps = mSettings.mPackages.get(packageName);
22725            if (pkg == null || ps == null) {
22726                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22727            }
22728
22729            if (pkg.applicationInfo.isSystemApp()) {
22730                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22731                        "Cannot move system application");
22732            }
22733
22734            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22735            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22736                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22737            if (isInternalStorage && !allow3rdPartyOnInternal) {
22738                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22739                        "3rd party apps are not allowed on internal storage");
22740            }
22741
22742            if (pkg.applicationInfo.isExternalAsec()) {
22743                currentAsec = true;
22744                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22745            } else if (pkg.applicationInfo.isForwardLocked()) {
22746                currentAsec = true;
22747                currentVolumeUuid = "forward_locked";
22748            } else {
22749                currentAsec = false;
22750                currentVolumeUuid = ps.volumeUuid;
22751
22752                final File probe = new File(pkg.codePath);
22753                final File probeOat = new File(probe, "oat");
22754                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22755                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22756                            "Move only supported for modern cluster style installs");
22757                }
22758            }
22759
22760            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22761                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22762                        "Package already moved to " + volumeUuid);
22763            }
22764            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22765                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22766                        "Device admin cannot be moved");
22767            }
22768
22769            if (mFrozenPackages.contains(packageName)) {
22770                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22771                        "Failed to move already frozen package");
22772            }
22773
22774            codeFile = new File(pkg.codePath);
22775            installerPackageName = ps.installerPackageName;
22776            packageAbiOverride = ps.cpuAbiOverrideString;
22777            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22778            seinfo = pkg.applicationInfo.seInfo;
22779            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22780            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22781            freezer = freezePackage(packageName, "movePackageInternal");
22782            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22783        }
22784
22785        final Bundle extras = new Bundle();
22786        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22787        extras.putString(Intent.EXTRA_TITLE, label);
22788        mMoveCallbacks.notifyCreated(moveId, extras);
22789
22790        int installFlags;
22791        final boolean moveCompleteApp;
22792        final File measurePath;
22793
22794        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22795            installFlags = INSTALL_INTERNAL;
22796            moveCompleteApp = !currentAsec;
22797            measurePath = Environment.getDataAppDirectory(volumeUuid);
22798        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22799            installFlags = INSTALL_EXTERNAL;
22800            moveCompleteApp = false;
22801            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22802        } else {
22803            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22804            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22805                    || !volume.isMountedWritable()) {
22806                freezer.close();
22807                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22808                        "Move location not mounted private volume");
22809            }
22810
22811            Preconditions.checkState(!currentAsec);
22812
22813            installFlags = INSTALL_INTERNAL;
22814            moveCompleteApp = true;
22815            measurePath = Environment.getDataAppDirectory(volumeUuid);
22816        }
22817
22818        final PackageStats stats = new PackageStats(null, -1);
22819        synchronized (mInstaller) {
22820            for (int userId : installedUserIds) {
22821                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22822                    freezer.close();
22823                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22824                            "Failed to measure package size");
22825                }
22826            }
22827        }
22828
22829        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22830                + stats.dataSize);
22831
22832        final long startFreeBytes = measurePath.getUsableSpace();
22833        final long sizeBytes;
22834        if (moveCompleteApp) {
22835            sizeBytes = stats.codeSize + stats.dataSize;
22836        } else {
22837            sizeBytes = stats.codeSize;
22838        }
22839
22840        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22841            freezer.close();
22842            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22843                    "Not enough free space to move");
22844        }
22845
22846        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22847
22848        final CountDownLatch installedLatch = new CountDownLatch(1);
22849        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22850            @Override
22851            public void onUserActionRequired(Intent intent) throws RemoteException {
22852                throw new IllegalStateException();
22853            }
22854
22855            @Override
22856            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22857                    Bundle extras) throws RemoteException {
22858                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22859                        + PackageManager.installStatusToString(returnCode, msg));
22860
22861                installedLatch.countDown();
22862                freezer.close();
22863
22864                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22865                switch (status) {
22866                    case PackageInstaller.STATUS_SUCCESS:
22867                        mMoveCallbacks.notifyStatusChanged(moveId,
22868                                PackageManager.MOVE_SUCCEEDED);
22869                        break;
22870                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22871                        mMoveCallbacks.notifyStatusChanged(moveId,
22872                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22873                        break;
22874                    default:
22875                        mMoveCallbacks.notifyStatusChanged(moveId,
22876                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22877                        break;
22878                }
22879            }
22880        };
22881
22882        final MoveInfo move;
22883        if (moveCompleteApp) {
22884            // Kick off a thread to report progress estimates
22885            new Thread() {
22886                @Override
22887                public void run() {
22888                    while (true) {
22889                        try {
22890                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22891                                break;
22892                            }
22893                        } catch (InterruptedException ignored) {
22894                        }
22895
22896                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22897                        final int progress = 10 + (int) MathUtils.constrain(
22898                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22899                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22900                    }
22901                }
22902            }.start();
22903
22904            final String dataAppName = codeFile.getName();
22905            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22906                    dataAppName, appId, seinfo, targetSdkVersion);
22907        } else {
22908            move = null;
22909        }
22910
22911        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22912
22913        final Message msg = mHandler.obtainMessage(INIT_COPY);
22914        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22915        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22916                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22917                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22918                PackageManager.INSTALL_REASON_UNKNOWN);
22919        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22920        msg.obj = params;
22921
22922        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22923                System.identityHashCode(msg.obj));
22924        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22925                System.identityHashCode(msg.obj));
22926
22927        mHandler.sendMessage(msg);
22928    }
22929
22930    @Override
22931    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22932        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22933
22934        final int realMoveId = mNextMoveId.getAndIncrement();
22935        final Bundle extras = new Bundle();
22936        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22937        mMoveCallbacks.notifyCreated(realMoveId, extras);
22938
22939        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22940            @Override
22941            public void onCreated(int moveId, Bundle extras) {
22942                // Ignored
22943            }
22944
22945            @Override
22946            public void onStatusChanged(int moveId, int status, long estMillis) {
22947                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22948            }
22949        };
22950
22951        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22952        storage.setPrimaryStorageUuid(volumeUuid, callback);
22953        return realMoveId;
22954    }
22955
22956    @Override
22957    public int getMoveStatus(int moveId) {
22958        mContext.enforceCallingOrSelfPermission(
22959                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22960        return mMoveCallbacks.mLastStatus.get(moveId);
22961    }
22962
22963    @Override
22964    public void registerMoveCallback(IPackageMoveObserver callback) {
22965        mContext.enforceCallingOrSelfPermission(
22966                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22967        mMoveCallbacks.register(callback);
22968    }
22969
22970    @Override
22971    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22972        mContext.enforceCallingOrSelfPermission(
22973                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22974        mMoveCallbacks.unregister(callback);
22975    }
22976
22977    @Override
22978    public boolean setInstallLocation(int loc) {
22979        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22980                null);
22981        if (getInstallLocation() == loc) {
22982            return true;
22983        }
22984        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22985                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22986            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22987                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22988            return true;
22989        }
22990        return false;
22991   }
22992
22993    @Override
22994    public int getInstallLocation() {
22995        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22996                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22997                PackageHelper.APP_INSTALL_AUTO);
22998    }
22999
23000    /** Called by UserManagerService */
23001    void cleanUpUser(UserManagerService userManager, int userHandle) {
23002        synchronized (mPackages) {
23003            mDirtyUsers.remove(userHandle);
23004            mUserNeedsBadging.delete(userHandle);
23005            mSettings.removeUserLPw(userHandle);
23006            mPendingBroadcasts.remove(userHandle);
23007            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23008            removeUnusedPackagesLPw(userManager, userHandle);
23009        }
23010    }
23011
23012    /**
23013     * We're removing userHandle and would like to remove any downloaded packages
23014     * that are no longer in use by any other user.
23015     * @param userHandle the user being removed
23016     */
23017    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23018        final boolean DEBUG_CLEAN_APKS = false;
23019        int [] users = userManager.getUserIds();
23020        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23021        while (psit.hasNext()) {
23022            PackageSetting ps = psit.next();
23023            if (ps.pkg == null) {
23024                continue;
23025            }
23026            final String packageName = ps.pkg.packageName;
23027            // Skip over if system app
23028            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23029                continue;
23030            }
23031            if (DEBUG_CLEAN_APKS) {
23032                Slog.i(TAG, "Checking package " + packageName);
23033            }
23034            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23035            if (keep) {
23036                if (DEBUG_CLEAN_APKS) {
23037                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23038                }
23039            } else {
23040                for (int i = 0; i < users.length; i++) {
23041                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23042                        keep = true;
23043                        if (DEBUG_CLEAN_APKS) {
23044                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23045                                    + users[i]);
23046                        }
23047                        break;
23048                    }
23049                }
23050            }
23051            if (!keep) {
23052                if (DEBUG_CLEAN_APKS) {
23053                    Slog.i(TAG, "  Removing package " + packageName);
23054                }
23055                mHandler.post(new Runnable() {
23056                    public void run() {
23057                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23058                                userHandle, 0);
23059                    } //end run
23060                });
23061            }
23062        }
23063    }
23064
23065    /** Called by UserManagerService */
23066    void createNewUser(int userId, String[] disallowedPackages) {
23067        synchronized (mInstallLock) {
23068            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23069        }
23070        synchronized (mPackages) {
23071            scheduleWritePackageRestrictionsLocked(userId);
23072            scheduleWritePackageListLocked(userId);
23073            applyFactoryDefaultBrowserLPw(userId);
23074            primeDomainVerificationsLPw(userId);
23075        }
23076    }
23077
23078    void onNewUserCreated(final int userId) {
23079        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23080        // If permission review for legacy apps is required, we represent
23081        // dagerous permissions for such apps as always granted runtime
23082        // permissions to keep per user flag state whether review is needed.
23083        // Hence, if a new user is added we have to propagate dangerous
23084        // permission grants for these legacy apps.
23085        if (mPermissionReviewRequired) {
23086            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
23087                    | UPDATE_PERMISSIONS_REPLACE_ALL);
23088        }
23089    }
23090
23091    @Override
23092    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23093        mContext.enforceCallingOrSelfPermission(
23094                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23095                "Only package verification agents can read the verifier device identity");
23096
23097        synchronized (mPackages) {
23098            return mSettings.getVerifierDeviceIdentityLPw();
23099        }
23100    }
23101
23102    @Override
23103    public void setPermissionEnforced(String permission, boolean enforced) {
23104        // TODO: Now that we no longer change GID for storage, this should to away.
23105        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23106                "setPermissionEnforced");
23107        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23108            synchronized (mPackages) {
23109                if (mSettings.mReadExternalStorageEnforced == null
23110                        || mSettings.mReadExternalStorageEnforced != enforced) {
23111                    mSettings.mReadExternalStorageEnforced = enforced;
23112                    mSettings.writeLPr();
23113                }
23114            }
23115            // kill any non-foreground processes so we restart them and
23116            // grant/revoke the GID.
23117            final IActivityManager am = ActivityManager.getService();
23118            if (am != null) {
23119                final long token = Binder.clearCallingIdentity();
23120                try {
23121                    am.killProcessesBelowForeground("setPermissionEnforcement");
23122                } catch (RemoteException e) {
23123                } finally {
23124                    Binder.restoreCallingIdentity(token);
23125                }
23126            }
23127        } else {
23128            throw new IllegalArgumentException("No selective enforcement for " + permission);
23129        }
23130    }
23131
23132    @Override
23133    @Deprecated
23134    public boolean isPermissionEnforced(String permission) {
23135        return true;
23136    }
23137
23138    @Override
23139    public boolean isStorageLow() {
23140        final long token = Binder.clearCallingIdentity();
23141        try {
23142            final DeviceStorageMonitorInternal
23143                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23144            if (dsm != null) {
23145                return dsm.isMemoryLow();
23146            } else {
23147                return false;
23148            }
23149        } finally {
23150            Binder.restoreCallingIdentity(token);
23151        }
23152    }
23153
23154    @Override
23155    public IPackageInstaller getPackageInstaller() {
23156        return mInstallerService;
23157    }
23158
23159    private boolean userNeedsBadging(int userId) {
23160        int index = mUserNeedsBadging.indexOfKey(userId);
23161        if (index < 0) {
23162            final UserInfo userInfo;
23163            final long token = Binder.clearCallingIdentity();
23164            try {
23165                userInfo = sUserManager.getUserInfo(userId);
23166            } finally {
23167                Binder.restoreCallingIdentity(token);
23168            }
23169            final boolean b;
23170            if (userInfo != null && userInfo.isManagedProfile()) {
23171                b = true;
23172            } else {
23173                b = false;
23174            }
23175            mUserNeedsBadging.put(userId, b);
23176            return b;
23177        }
23178        return mUserNeedsBadging.valueAt(index);
23179    }
23180
23181    @Override
23182    public KeySet getKeySetByAlias(String packageName, String alias) {
23183        if (packageName == null || alias == null) {
23184            return null;
23185        }
23186        synchronized(mPackages) {
23187            final PackageParser.Package pkg = mPackages.get(packageName);
23188            if (pkg == null) {
23189                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23190                throw new IllegalArgumentException("Unknown package: " + packageName);
23191            }
23192            KeySetManagerService ksms = mSettings.mKeySetManagerService;
23193            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23194        }
23195    }
23196
23197    @Override
23198    public KeySet getSigningKeySet(String packageName) {
23199        if (packageName == null) {
23200            return null;
23201        }
23202        synchronized(mPackages) {
23203            final PackageParser.Package pkg = mPackages.get(packageName);
23204            if (pkg == null) {
23205                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23206                throw new IllegalArgumentException("Unknown package: " + packageName);
23207            }
23208            if (pkg.applicationInfo.uid != Binder.getCallingUid()
23209                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
23210                throw new SecurityException("May not access signing KeySet of other apps.");
23211            }
23212            KeySetManagerService ksms = mSettings.mKeySetManagerService;
23213            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23214        }
23215    }
23216
23217    @Override
23218    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23219        if (packageName == null || ks == null) {
23220            return false;
23221        }
23222        synchronized(mPackages) {
23223            final PackageParser.Package pkg = mPackages.get(packageName);
23224            if (pkg == null) {
23225                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23226                throw new IllegalArgumentException("Unknown package: " + packageName);
23227            }
23228            IBinder ksh = ks.getToken();
23229            if (ksh instanceof KeySetHandle) {
23230                KeySetManagerService ksms = mSettings.mKeySetManagerService;
23231                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23232            }
23233            return false;
23234        }
23235    }
23236
23237    @Override
23238    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23239        if (packageName == null || ks == null) {
23240            return false;
23241        }
23242        synchronized(mPackages) {
23243            final PackageParser.Package pkg = mPackages.get(packageName);
23244            if (pkg == null) {
23245                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23246                throw new IllegalArgumentException("Unknown package: " + packageName);
23247            }
23248            IBinder ksh = ks.getToken();
23249            if (ksh instanceof KeySetHandle) {
23250                KeySetManagerService ksms = mSettings.mKeySetManagerService;
23251                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23252            }
23253            return false;
23254        }
23255    }
23256
23257    private void deletePackageIfUnusedLPr(final String packageName) {
23258        PackageSetting ps = mSettings.mPackages.get(packageName);
23259        if (ps == null) {
23260            return;
23261        }
23262        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23263            // TODO Implement atomic delete if package is unused
23264            // It is currently possible that the package will be deleted even if it is installed
23265            // after this method returns.
23266            mHandler.post(new Runnable() {
23267                public void run() {
23268                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23269                            0, PackageManager.DELETE_ALL_USERS);
23270                }
23271            });
23272        }
23273    }
23274
23275    /**
23276     * Check and throw if the given before/after packages would be considered a
23277     * downgrade.
23278     */
23279    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23280            throws PackageManagerException {
23281        if (after.versionCode < before.mVersionCode) {
23282            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23283                    "Update version code " + after.versionCode + " is older than current "
23284                    + before.mVersionCode);
23285        } else if (after.versionCode == before.mVersionCode) {
23286            if (after.baseRevisionCode < before.baseRevisionCode) {
23287                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23288                        "Update base revision code " + after.baseRevisionCode
23289                        + " is older than current " + before.baseRevisionCode);
23290            }
23291
23292            if (!ArrayUtils.isEmpty(after.splitNames)) {
23293                for (int i = 0; i < after.splitNames.length; i++) {
23294                    final String splitName = after.splitNames[i];
23295                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23296                    if (j != -1) {
23297                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23298                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23299                                    "Update split " + splitName + " revision code "
23300                                    + after.splitRevisionCodes[i] + " is older than current "
23301                                    + before.splitRevisionCodes[j]);
23302                        }
23303                    }
23304                }
23305            }
23306        }
23307    }
23308
23309    private static class MoveCallbacks extends Handler {
23310        private static final int MSG_CREATED = 1;
23311        private static final int MSG_STATUS_CHANGED = 2;
23312
23313        private final RemoteCallbackList<IPackageMoveObserver>
23314                mCallbacks = new RemoteCallbackList<>();
23315
23316        private final SparseIntArray mLastStatus = new SparseIntArray();
23317
23318        public MoveCallbacks(Looper looper) {
23319            super(looper);
23320        }
23321
23322        public void register(IPackageMoveObserver callback) {
23323            mCallbacks.register(callback);
23324        }
23325
23326        public void unregister(IPackageMoveObserver callback) {
23327            mCallbacks.unregister(callback);
23328        }
23329
23330        @Override
23331        public void handleMessage(Message msg) {
23332            final SomeArgs args = (SomeArgs) msg.obj;
23333            final int n = mCallbacks.beginBroadcast();
23334            for (int i = 0; i < n; i++) {
23335                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23336                try {
23337                    invokeCallback(callback, msg.what, args);
23338                } catch (RemoteException ignored) {
23339                }
23340            }
23341            mCallbacks.finishBroadcast();
23342            args.recycle();
23343        }
23344
23345        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23346                throws RemoteException {
23347            switch (what) {
23348                case MSG_CREATED: {
23349                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23350                    break;
23351                }
23352                case MSG_STATUS_CHANGED: {
23353                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23354                    break;
23355                }
23356            }
23357        }
23358
23359        private void notifyCreated(int moveId, Bundle extras) {
23360            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23361
23362            final SomeArgs args = SomeArgs.obtain();
23363            args.argi1 = moveId;
23364            args.arg2 = extras;
23365            obtainMessage(MSG_CREATED, args).sendToTarget();
23366        }
23367
23368        private void notifyStatusChanged(int moveId, int status) {
23369            notifyStatusChanged(moveId, status, -1);
23370        }
23371
23372        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23373            Slog.v(TAG, "Move " + moveId + " status " + status);
23374
23375            final SomeArgs args = SomeArgs.obtain();
23376            args.argi1 = moveId;
23377            args.argi2 = status;
23378            args.arg3 = estMillis;
23379            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23380
23381            synchronized (mLastStatus) {
23382                mLastStatus.put(moveId, status);
23383            }
23384        }
23385    }
23386
23387    private final static class OnPermissionChangeListeners extends Handler {
23388        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23389
23390        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23391                new RemoteCallbackList<>();
23392
23393        public OnPermissionChangeListeners(Looper looper) {
23394            super(looper);
23395        }
23396
23397        @Override
23398        public void handleMessage(Message msg) {
23399            switch (msg.what) {
23400                case MSG_ON_PERMISSIONS_CHANGED: {
23401                    final int uid = msg.arg1;
23402                    handleOnPermissionsChanged(uid);
23403                } break;
23404            }
23405        }
23406
23407        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23408            mPermissionListeners.register(listener);
23409
23410        }
23411
23412        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23413            mPermissionListeners.unregister(listener);
23414        }
23415
23416        public void onPermissionsChanged(int uid) {
23417            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23418                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23419            }
23420        }
23421
23422        private void handleOnPermissionsChanged(int uid) {
23423            final int count = mPermissionListeners.beginBroadcast();
23424            try {
23425                for (int i = 0; i < count; i++) {
23426                    IOnPermissionsChangeListener callback = mPermissionListeners
23427                            .getBroadcastItem(i);
23428                    try {
23429                        callback.onPermissionsChanged(uid);
23430                    } catch (RemoteException e) {
23431                        Log.e(TAG, "Permission listener is dead", e);
23432                    }
23433                }
23434            } finally {
23435                mPermissionListeners.finishBroadcast();
23436            }
23437        }
23438    }
23439
23440    private class PackageManagerInternalImpl extends PackageManagerInternal {
23441        @Override
23442        public void setLocationPackagesProvider(PackagesProvider provider) {
23443            synchronized (mPackages) {
23444                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
23445            }
23446        }
23447
23448        @Override
23449        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23450            synchronized (mPackages) {
23451                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
23452            }
23453        }
23454
23455        @Override
23456        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23457            synchronized (mPackages) {
23458                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
23459            }
23460        }
23461
23462        @Override
23463        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23464            synchronized (mPackages) {
23465                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
23466            }
23467        }
23468
23469        @Override
23470        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23471            synchronized (mPackages) {
23472                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
23473            }
23474        }
23475
23476        @Override
23477        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23478            synchronized (mPackages) {
23479                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
23480            }
23481        }
23482
23483        @Override
23484        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23485            synchronized (mPackages) {
23486                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
23487                        packageName, userId);
23488            }
23489        }
23490
23491        @Override
23492        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23493            synchronized (mPackages) {
23494                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23495                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
23496                        packageName, userId);
23497            }
23498        }
23499
23500        @Override
23501        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23502            synchronized (mPackages) {
23503                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
23504                        packageName, userId);
23505            }
23506        }
23507
23508        @Override
23509        public void setKeepUninstalledPackages(final List<String> packageList) {
23510            Preconditions.checkNotNull(packageList);
23511            List<String> removedFromList = null;
23512            synchronized (mPackages) {
23513                if (mKeepUninstalledPackages != null) {
23514                    final int packagesCount = mKeepUninstalledPackages.size();
23515                    for (int i = 0; i < packagesCount; i++) {
23516                        String oldPackage = mKeepUninstalledPackages.get(i);
23517                        if (packageList != null && packageList.contains(oldPackage)) {
23518                            continue;
23519                        }
23520                        if (removedFromList == null) {
23521                            removedFromList = new ArrayList<>();
23522                        }
23523                        removedFromList.add(oldPackage);
23524                    }
23525                }
23526                mKeepUninstalledPackages = new ArrayList<>(packageList);
23527                if (removedFromList != null) {
23528                    final int removedCount = removedFromList.size();
23529                    for (int i = 0; i < removedCount; i++) {
23530                        deletePackageIfUnusedLPr(removedFromList.get(i));
23531                    }
23532                }
23533            }
23534        }
23535
23536        @Override
23537        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23538            synchronized (mPackages) {
23539                // If we do not support permission review, done.
23540                if (!mPermissionReviewRequired) {
23541                    return false;
23542                }
23543
23544                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
23545                if (packageSetting == null) {
23546                    return false;
23547                }
23548
23549                // Permission review applies only to apps not supporting the new permission model.
23550                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
23551                    return false;
23552                }
23553
23554                // Legacy apps have the permission and get user consent on launch.
23555                PermissionsState permissionsState = packageSetting.getPermissionsState();
23556                return permissionsState.isPermissionReviewRequired(userId);
23557            }
23558        }
23559
23560        @Override
23561        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
23562            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
23563        }
23564
23565        @Override
23566        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23567                int userId) {
23568            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23569        }
23570
23571        @Override
23572        public void setDeviceAndProfileOwnerPackages(
23573                int deviceOwnerUserId, String deviceOwnerPackage,
23574                SparseArray<String> profileOwnerPackages) {
23575            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23576                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23577        }
23578
23579        @Override
23580        public boolean isPackageDataProtected(int userId, String packageName) {
23581            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23582        }
23583
23584        @Override
23585        public boolean isPackageEphemeral(int userId, String packageName) {
23586            synchronized (mPackages) {
23587                final PackageSetting ps = mSettings.mPackages.get(packageName);
23588                return ps != null ? ps.getInstantApp(userId) : false;
23589            }
23590        }
23591
23592        @Override
23593        public boolean wasPackageEverLaunched(String packageName, int userId) {
23594            synchronized (mPackages) {
23595                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23596            }
23597        }
23598
23599        @Override
23600        public void grantRuntimePermission(String packageName, String name, int userId,
23601                boolean overridePolicy) {
23602            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
23603                    overridePolicy);
23604        }
23605
23606        @Override
23607        public void revokeRuntimePermission(String packageName, String name, int userId,
23608                boolean overridePolicy) {
23609            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
23610                    overridePolicy);
23611        }
23612
23613        @Override
23614        public String getNameForUid(int uid) {
23615            return PackageManagerService.this.getNameForUid(uid);
23616        }
23617
23618        @Override
23619        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23620                Intent origIntent, String resolvedType, String callingPackage,
23621                Bundle verificationBundle, int userId) {
23622            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23623                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23624                    userId);
23625        }
23626
23627        @Override
23628        public void grantEphemeralAccess(int userId, Intent intent,
23629                int targetAppId, int ephemeralAppId) {
23630            synchronized (mPackages) {
23631                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23632                        targetAppId, ephemeralAppId);
23633            }
23634        }
23635
23636        @Override
23637        public boolean isInstantAppInstallerComponent(ComponentName component) {
23638            synchronized (mPackages) {
23639                return mInstantAppInstallerActivity != null
23640                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23641            }
23642        }
23643
23644        @Override
23645        public void pruneInstantApps() {
23646            synchronized (mPackages) {
23647                mInstantAppRegistry.pruneInstantAppsLPw();
23648            }
23649        }
23650
23651        @Override
23652        public String getSetupWizardPackageName() {
23653            return mSetupWizardPackage;
23654        }
23655
23656        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23657            if (policy != null) {
23658                mExternalSourcesPolicy = policy;
23659            }
23660        }
23661
23662        @Override
23663        public boolean isPackagePersistent(String packageName) {
23664            synchronized (mPackages) {
23665                PackageParser.Package pkg = mPackages.get(packageName);
23666                return pkg != null
23667                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23668                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23669                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23670                        : false;
23671            }
23672        }
23673
23674        @Override
23675        public List<PackageInfo> getOverlayPackages(int userId) {
23676            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23677            synchronized (mPackages) {
23678                for (PackageParser.Package p : mPackages.values()) {
23679                    if (p.mOverlayTarget != null) {
23680                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23681                        if (pkg != null) {
23682                            overlayPackages.add(pkg);
23683                        }
23684                    }
23685                }
23686            }
23687            return overlayPackages;
23688        }
23689
23690        @Override
23691        public List<String> getTargetPackageNames(int userId) {
23692            List<String> targetPackages = new ArrayList<>();
23693            synchronized (mPackages) {
23694                for (PackageParser.Package p : mPackages.values()) {
23695                    if (p.mOverlayTarget == null) {
23696                        targetPackages.add(p.packageName);
23697                    }
23698                }
23699            }
23700            return targetPackages;
23701        }
23702
23703        @Override
23704        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23705                @Nullable List<String> overlayPackageNames) {
23706            synchronized (mPackages) {
23707                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23708                    Slog.e(TAG, "failed to find package " + targetPackageName);
23709                    return false;
23710                }
23711
23712                ArrayList<String> paths = null;
23713                if (overlayPackageNames != null) {
23714                    final int N = overlayPackageNames.size();
23715                    paths = new ArrayList<>(N);
23716                    for (int i = 0; i < N; i++) {
23717                        final String packageName = overlayPackageNames.get(i);
23718                        final PackageParser.Package pkg = mPackages.get(packageName);
23719                        if (pkg == null) {
23720                            Slog.e(TAG, "failed to find package " + packageName);
23721                            return false;
23722                        }
23723                        paths.add(pkg.baseCodePath);
23724                    }
23725                }
23726
23727                ArrayMap<String, ArrayList<String>> userSpecificOverlays =
23728                    mEnabledOverlayPaths.get(userId);
23729                if (userSpecificOverlays == null) {
23730                    userSpecificOverlays = new ArrayMap<>();
23731                    mEnabledOverlayPaths.put(userId, userSpecificOverlays);
23732                }
23733
23734                if (paths != null && paths.size() > 0) {
23735                    userSpecificOverlays.put(targetPackageName, paths);
23736                } else {
23737                    userSpecificOverlays.remove(targetPackageName);
23738                }
23739                return true;
23740            }
23741        }
23742
23743        @Override
23744        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23745                int flags, int userId) {
23746            return resolveIntentInternal(
23747                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
23748        }
23749
23750        @Override
23751        public ResolveInfo resolveService(Intent intent, String resolvedType,
23752                int flags, int userId, int callingUid) {
23753            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23754        }
23755
23756        @Override
23757        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23758            synchronized (mPackages) {
23759                mIsolatedOwners.put(isolatedUid, ownerUid);
23760            }
23761        }
23762
23763        @Override
23764        public void removeIsolatedUid(int isolatedUid) {
23765            synchronized (mPackages) {
23766                mIsolatedOwners.delete(isolatedUid);
23767            }
23768        }
23769
23770        @Override
23771        public int getUidTargetSdkVersion(int uid) {
23772            synchronized (mPackages) {
23773                return getUidTargetSdkVersionLockedLPr(uid);
23774            }
23775        }
23776    }
23777
23778    @Override
23779    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23780        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23781        synchronized (mPackages) {
23782            final long identity = Binder.clearCallingIdentity();
23783            try {
23784                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
23785                        packageNames, userId);
23786            } finally {
23787                Binder.restoreCallingIdentity(identity);
23788            }
23789        }
23790    }
23791
23792    @Override
23793    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23794        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23795        synchronized (mPackages) {
23796            final long identity = Binder.clearCallingIdentity();
23797            try {
23798                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
23799                        packageNames, userId);
23800            } finally {
23801                Binder.restoreCallingIdentity(identity);
23802            }
23803        }
23804    }
23805
23806    private static void enforceSystemOrPhoneCaller(String tag) {
23807        int callingUid = Binder.getCallingUid();
23808        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23809            throw new SecurityException(
23810                    "Cannot call " + tag + " from UID " + callingUid);
23811        }
23812    }
23813
23814    boolean isHistoricalPackageUsageAvailable() {
23815        return mPackageUsage.isHistoricalPackageUsageAvailable();
23816    }
23817
23818    /**
23819     * Return a <b>copy</b> of the collection of packages known to the package manager.
23820     * @return A copy of the values of mPackages.
23821     */
23822    Collection<PackageParser.Package> getPackages() {
23823        synchronized (mPackages) {
23824            return new ArrayList<>(mPackages.values());
23825        }
23826    }
23827
23828    /**
23829     * Logs process start information (including base APK hash) to the security log.
23830     * @hide
23831     */
23832    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23833            String apkFile, int pid) {
23834        if (!SecurityLog.isLoggingEnabled()) {
23835            return;
23836        }
23837        Bundle data = new Bundle();
23838        data.putLong("startTimestamp", System.currentTimeMillis());
23839        data.putString("processName", processName);
23840        data.putInt("uid", uid);
23841        data.putString("seinfo", seinfo);
23842        data.putString("apkFile", apkFile);
23843        data.putInt("pid", pid);
23844        Message msg = mProcessLoggingHandler.obtainMessage(
23845                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23846        msg.setData(data);
23847        mProcessLoggingHandler.sendMessage(msg);
23848    }
23849
23850    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23851        return mCompilerStats.getPackageStats(pkgName);
23852    }
23853
23854    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23855        return getOrCreateCompilerPackageStats(pkg.packageName);
23856    }
23857
23858    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23859        return mCompilerStats.getOrCreatePackageStats(pkgName);
23860    }
23861
23862    public void deleteCompilerPackageStats(String pkgName) {
23863        mCompilerStats.deletePackageStats(pkgName);
23864    }
23865
23866    @Override
23867    public int getInstallReason(String packageName, int userId) {
23868        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23869                true /* requireFullPermission */, false /* checkShell */,
23870                "get install reason");
23871        synchronized (mPackages) {
23872            final PackageSetting ps = mSettings.mPackages.get(packageName);
23873            if (ps != null) {
23874                return ps.getInstallReason(userId);
23875            }
23876        }
23877        return PackageManager.INSTALL_REASON_UNKNOWN;
23878    }
23879
23880    @Override
23881    public boolean canRequestPackageInstalls(String packageName, int userId) {
23882        int callingUid = Binder.getCallingUid();
23883        int uid = getPackageUid(packageName, 0, userId);
23884        if (callingUid != uid && callingUid != Process.ROOT_UID
23885                && callingUid != Process.SYSTEM_UID) {
23886            throw new SecurityException(
23887                    "Caller uid " + callingUid + " does not own package " + packageName);
23888        }
23889        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
23890        if (info == null) {
23891            return false;
23892        }
23893        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23894            throw new UnsupportedOperationException(
23895                    "Operation only supported on apps targeting Android O or higher");
23896        }
23897        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23898        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23899        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23900            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
23901        }
23902        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23903            return false;
23904        }
23905        if (mExternalSourcesPolicy != null) {
23906            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23907            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23908                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23909            }
23910        }
23911        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23912    }
23913
23914    @Override
23915    public ComponentName getInstantAppResolverSettingsComponent() {
23916        return mInstantAppResolverSettingsComponent;
23917    }
23918
23919    @Override
23920    public ComponentName getInstantAppInstallerComponent() {
23921        return mInstantAppInstallerActivity == null
23922                ? null : mInstantAppInstallerActivity.getComponentName();
23923    }
23924
23925    @Override
23926    public String getInstantAppAndroidId(String packageName, int userId) {
23927        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
23928                "getInstantAppAndroidId");
23929        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23930                true /* requireFullPermission */, false /* checkShell */,
23931                "getInstantAppAndroidId");
23932        // Make sure the target is an Instant App.
23933        if (!isInstantApp(packageName, userId)) {
23934            return null;
23935        }
23936        synchronized (mPackages) {
23937            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
23938        }
23939    }
23940}
23941
23942interface PackageSender {
23943    void sendPackageBroadcast(final String action, final String pkg,
23944        final Bundle extras, final int flags, final String targetPkg,
23945        final IIntentReceiver finishedReceiver, final int[] userIds);
23946    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
23947        int appId, int... userIds);
23948}
23949