PackageManagerService.java revision c0dd03a666467d03e140f3a43704b3f3f3f4d4b7
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        ResolveInfo localInstantApp = null;
6502        boolean blockResolution = false;
6503        if (!alreadyResolvedLocally) {
6504            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6505                    flags
6506                        | PackageManager.GET_RESOLVED_FILTER
6507                        | PackageManager.MATCH_INSTANT
6508                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6509                    userId);
6510            for (int i = instantApps.size() - 1; i >= 0; --i) {
6511                final ResolveInfo info = instantApps.get(i);
6512                final String packageName = info.activityInfo.packageName;
6513                final PackageSetting ps = mSettings.mPackages.get(packageName);
6514                if (ps.getInstantApp(userId)) {
6515                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6516                    final int status = (int)(packedStatus >> 32);
6517                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6518                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6519                        // there's a local instant application installed, but, the user has
6520                        // chosen to never use it; skip resolution and don't acknowledge
6521                        // an instant application is even available
6522                        if (DEBUG_EPHEMERAL) {
6523                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6524                        }
6525                        blockResolution = true;
6526                        break;
6527                    } else {
6528                        // we have a locally installed instant application; skip resolution
6529                        // but acknowledge there's an instant application available
6530                        if (DEBUG_EPHEMERAL) {
6531                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6532                        }
6533                        localInstantApp = info;
6534                        break;
6535                    }
6536                }
6537            }
6538        }
6539        // no app installed, let's see if one's available
6540        AuxiliaryResolveInfo auxiliaryResponse = null;
6541        if (!blockResolution) {
6542            if (localInstantApp == null) {
6543                // we don't have an instant app locally, resolve externally
6544                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6545                final InstantAppRequest requestObject = new InstantAppRequest(
6546                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6547                        null /*callingPackage*/, userId, null /*verificationBundle*/);
6548                auxiliaryResponse =
6549                        InstantAppResolver.doInstantAppResolutionPhaseOne(
6550                                mContext, mInstantAppResolverConnection, requestObject);
6551                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6552            } else {
6553                // we have an instant application locally, but, we can't admit that since
6554                // callers shouldn't be able to determine prior browsing. create a dummy
6555                // auxiliary response so the downstream code behaves as if there's an
6556                // instant application available externally. when it comes time to start
6557                // the instant application, we'll do the right thing.
6558                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6559                auxiliaryResponse = new AuxiliaryResolveInfo(
6560                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
6561            }
6562        }
6563        if (auxiliaryResponse != null) {
6564            if (DEBUG_EPHEMERAL) {
6565                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6566            }
6567            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6568            final PackageSetting ps =
6569                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6570            if (ps != null) {
6571                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6572                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6573                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6574                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6575                // make sure this resolver is the default
6576                ephemeralInstaller.isDefault = true;
6577                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6578                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6579                // add a non-generic filter
6580                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6581                ephemeralInstaller.filter.addDataPath(
6582                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6583                ephemeralInstaller.isInstantAppAvailable = true;
6584                result.add(ephemeralInstaller);
6585            }
6586        }
6587        return result;
6588    }
6589
6590    private static class CrossProfileDomainInfo {
6591        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6592        ResolveInfo resolveInfo;
6593        /* Best domain verification status of the activities found in the other profile */
6594        int bestDomainVerificationStatus;
6595    }
6596
6597    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6598            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6599        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6600                sourceUserId)) {
6601            return null;
6602        }
6603        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6604                resolvedType, flags, parentUserId);
6605
6606        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6607            return null;
6608        }
6609        CrossProfileDomainInfo result = null;
6610        int size = resultTargetUser.size();
6611        for (int i = 0; i < size; i++) {
6612            ResolveInfo riTargetUser = resultTargetUser.get(i);
6613            // Intent filter verification is only for filters that specify a host. So don't return
6614            // those that handle all web uris.
6615            if (riTargetUser.handleAllWebDataURI) {
6616                continue;
6617            }
6618            String packageName = riTargetUser.activityInfo.packageName;
6619            PackageSetting ps = mSettings.mPackages.get(packageName);
6620            if (ps == null) {
6621                continue;
6622            }
6623            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6624            int status = (int)(verificationState >> 32);
6625            if (result == null) {
6626                result = new CrossProfileDomainInfo();
6627                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6628                        sourceUserId, parentUserId);
6629                result.bestDomainVerificationStatus = status;
6630            } else {
6631                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6632                        result.bestDomainVerificationStatus);
6633            }
6634        }
6635        // Don't consider matches with status NEVER across profiles.
6636        if (result != null && result.bestDomainVerificationStatus
6637                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6638            return null;
6639        }
6640        return result;
6641    }
6642
6643    /**
6644     * Verification statuses are ordered from the worse to the best, except for
6645     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6646     */
6647    private int bestDomainVerificationStatus(int status1, int status2) {
6648        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6649            return status2;
6650        }
6651        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6652            return status1;
6653        }
6654        return (int) MathUtils.max(status1, status2);
6655    }
6656
6657    private boolean isUserEnabled(int userId) {
6658        long callingId = Binder.clearCallingIdentity();
6659        try {
6660            UserInfo userInfo = sUserManager.getUserInfo(userId);
6661            return userInfo != null && userInfo.isEnabled();
6662        } finally {
6663            Binder.restoreCallingIdentity(callingId);
6664        }
6665    }
6666
6667    /**
6668     * Filter out activities with systemUserOnly flag set, when current user is not System.
6669     *
6670     * @return filtered list
6671     */
6672    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6673        if (userId == UserHandle.USER_SYSTEM) {
6674            return resolveInfos;
6675        }
6676        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6677            ResolveInfo info = resolveInfos.get(i);
6678            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6679                resolveInfos.remove(i);
6680            }
6681        }
6682        return resolveInfos;
6683    }
6684
6685    /**
6686     * Filters out ephemeral activities.
6687     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6688     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6689     *
6690     * @param resolveInfos The pre-filtered list of resolved activities
6691     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6692     *          is performed.
6693     * @return A filtered list of resolved activities.
6694     */
6695    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6696            String ephemeralPkgName) {
6697        // TODO: When adding on-demand split support for non-instant apps, remove this check
6698        // and always apply post filtering
6699        if (ephemeralPkgName == null) {
6700            return resolveInfos;
6701        }
6702        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6703            final ResolveInfo info = resolveInfos.get(i);
6704            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6705            // allow activities that are defined in the provided package
6706            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6707                if (info.activityInfo.splitName != null
6708                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6709                                info.activityInfo.splitName)) {
6710                    // requested activity is defined in a split that hasn't been installed yet.
6711                    // add the installer to the resolve list
6712                    if (DEBUG_EPHEMERAL) {
6713                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6714                    }
6715                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6716                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6717                            info.activityInfo.packageName, info.activityInfo.splitName,
6718                            info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
6719                    // make sure this resolver is the default
6720                    installerInfo.isDefault = true;
6721                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6722                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6723                    // add a non-generic filter
6724                    installerInfo.filter = new IntentFilter();
6725                    // load resources from the correct package
6726                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6727                    resolveInfos.set(i, installerInfo);
6728                }
6729                continue;
6730            }
6731            // allow activities that have been explicitly exposed to ephemeral apps
6732            if (!isEphemeralApp
6733                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6734                continue;
6735            }
6736            resolveInfos.remove(i);
6737        }
6738        return resolveInfos;
6739    }
6740
6741    /**
6742     * @param resolveInfos list of resolve infos in descending priority order
6743     * @return if the list contains a resolve info with non-negative priority
6744     */
6745    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6746        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6747    }
6748
6749    private static boolean hasWebURI(Intent intent) {
6750        if (intent.getData() == null) {
6751            return false;
6752        }
6753        final String scheme = intent.getScheme();
6754        if (TextUtils.isEmpty(scheme)) {
6755            return false;
6756        }
6757        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6758    }
6759
6760    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6761            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6762            int userId) {
6763        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6764
6765        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6766            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6767                    candidates.size());
6768        }
6769
6770        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6771        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6772        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6773        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6774        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6775        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6776
6777        synchronized (mPackages) {
6778            final int count = candidates.size();
6779            // First, try to use linked apps. Partition the candidates into four lists:
6780            // one for the final results, one for the "do not use ever", one for "undefined status"
6781            // and finally one for "browser app type".
6782            for (int n=0; n<count; n++) {
6783                ResolveInfo info = candidates.get(n);
6784                String packageName = info.activityInfo.packageName;
6785                PackageSetting ps = mSettings.mPackages.get(packageName);
6786                if (ps != null) {
6787                    // Add to the special match all list (Browser use case)
6788                    if (info.handleAllWebDataURI) {
6789                        matchAllList.add(info);
6790                        continue;
6791                    }
6792                    // Try to get the status from User settings first
6793                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6794                    int status = (int)(packedStatus >> 32);
6795                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6796                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6797                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6798                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6799                                    + " : linkgen=" + linkGeneration);
6800                        }
6801                        // Use link-enabled generation as preferredOrder, i.e.
6802                        // prefer newly-enabled over earlier-enabled.
6803                        info.preferredOrder = linkGeneration;
6804                        alwaysList.add(info);
6805                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6806                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6807                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6808                        }
6809                        neverList.add(info);
6810                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6811                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6812                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6813                        }
6814                        alwaysAskList.add(info);
6815                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6816                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6817                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6818                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6819                        }
6820                        undefinedList.add(info);
6821                    }
6822                }
6823            }
6824
6825            // We'll want to include browser possibilities in a few cases
6826            boolean includeBrowser = false;
6827
6828            // First try to add the "always" resolution(s) for the current user, if any
6829            if (alwaysList.size() > 0) {
6830                result.addAll(alwaysList);
6831            } else {
6832                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6833                result.addAll(undefinedList);
6834                // Maybe add one for the other profile.
6835                if (xpDomainInfo != null && (
6836                        xpDomainInfo.bestDomainVerificationStatus
6837                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6838                    result.add(xpDomainInfo.resolveInfo);
6839                }
6840                includeBrowser = true;
6841            }
6842
6843            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6844            // If there were 'always' entries their preferred order has been set, so we also
6845            // back that off to make the alternatives equivalent
6846            if (alwaysAskList.size() > 0) {
6847                for (ResolveInfo i : result) {
6848                    i.preferredOrder = 0;
6849                }
6850                result.addAll(alwaysAskList);
6851                includeBrowser = true;
6852            }
6853
6854            if (includeBrowser) {
6855                // Also add browsers (all of them or only the default one)
6856                if (DEBUG_DOMAIN_VERIFICATION) {
6857                    Slog.v(TAG, "   ...including browsers in candidate set");
6858                }
6859                if ((matchFlags & MATCH_ALL) != 0) {
6860                    result.addAll(matchAllList);
6861                } else {
6862                    // Browser/generic handling case.  If there's a default browser, go straight
6863                    // to that (but only if there is no other higher-priority match).
6864                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6865                    int maxMatchPrio = 0;
6866                    ResolveInfo defaultBrowserMatch = null;
6867                    final int numCandidates = matchAllList.size();
6868                    for (int n = 0; n < numCandidates; n++) {
6869                        ResolveInfo info = matchAllList.get(n);
6870                        // track the highest overall match priority...
6871                        if (info.priority > maxMatchPrio) {
6872                            maxMatchPrio = info.priority;
6873                        }
6874                        // ...and the highest-priority default browser match
6875                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6876                            if (defaultBrowserMatch == null
6877                                    || (defaultBrowserMatch.priority < info.priority)) {
6878                                if (debug) {
6879                                    Slog.v(TAG, "Considering default browser match " + info);
6880                                }
6881                                defaultBrowserMatch = info;
6882                            }
6883                        }
6884                    }
6885                    if (defaultBrowserMatch != null
6886                            && defaultBrowserMatch.priority >= maxMatchPrio
6887                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6888                    {
6889                        if (debug) {
6890                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6891                        }
6892                        result.add(defaultBrowserMatch);
6893                    } else {
6894                        result.addAll(matchAllList);
6895                    }
6896                }
6897
6898                // If there is nothing selected, add all candidates and remove the ones that the user
6899                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6900                if (result.size() == 0) {
6901                    result.addAll(candidates);
6902                    result.removeAll(neverList);
6903                }
6904            }
6905        }
6906        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6907            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6908                    result.size());
6909            for (ResolveInfo info : result) {
6910                Slog.v(TAG, "  + " + info.activityInfo);
6911            }
6912        }
6913        return result;
6914    }
6915
6916    // Returns a packed value as a long:
6917    //
6918    // high 'int'-sized word: link status: undefined/ask/never/always.
6919    // low 'int'-sized word: relative priority among 'always' results.
6920    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6921        long result = ps.getDomainVerificationStatusForUser(userId);
6922        // if none available, get the master status
6923        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6924            if (ps.getIntentFilterVerificationInfo() != null) {
6925                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6926            }
6927        }
6928        return result;
6929    }
6930
6931    private ResolveInfo querySkipCurrentProfileIntents(
6932            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6933            int flags, int sourceUserId) {
6934        if (matchingFilters != null) {
6935            int size = matchingFilters.size();
6936            for (int i = 0; i < size; i ++) {
6937                CrossProfileIntentFilter filter = matchingFilters.get(i);
6938                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6939                    // Checking if there are activities in the target user that can handle the
6940                    // intent.
6941                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6942                            resolvedType, flags, sourceUserId);
6943                    if (resolveInfo != null) {
6944                        return resolveInfo;
6945                    }
6946                }
6947            }
6948        }
6949        return null;
6950    }
6951
6952    // Return matching ResolveInfo in target user if any.
6953    private ResolveInfo queryCrossProfileIntents(
6954            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6955            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6956        if (matchingFilters != null) {
6957            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6958            // match the same intent. For performance reasons, it is better not to
6959            // run queryIntent twice for the same userId
6960            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6961            int size = matchingFilters.size();
6962            for (int i = 0; i < size; i++) {
6963                CrossProfileIntentFilter filter = matchingFilters.get(i);
6964                int targetUserId = filter.getTargetUserId();
6965                boolean skipCurrentProfile =
6966                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6967                boolean skipCurrentProfileIfNoMatchFound =
6968                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6969                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6970                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6971                    // Checking if there are activities in the target user that can handle the
6972                    // intent.
6973                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6974                            resolvedType, flags, sourceUserId);
6975                    if (resolveInfo != null) return resolveInfo;
6976                    alreadyTriedUserIds.put(targetUserId, true);
6977                }
6978            }
6979        }
6980        return null;
6981    }
6982
6983    /**
6984     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6985     * will forward the intent to the filter's target user.
6986     * Otherwise, returns null.
6987     */
6988    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6989            String resolvedType, int flags, int sourceUserId) {
6990        int targetUserId = filter.getTargetUserId();
6991        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6992                resolvedType, flags, targetUserId);
6993        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6994            // If all the matches in the target profile are suspended, return null.
6995            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6996                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6997                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6998                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6999                            targetUserId);
7000                }
7001            }
7002        }
7003        return null;
7004    }
7005
7006    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7007            int sourceUserId, int targetUserId) {
7008        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7009        long ident = Binder.clearCallingIdentity();
7010        boolean targetIsProfile;
7011        try {
7012            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7013        } finally {
7014            Binder.restoreCallingIdentity(ident);
7015        }
7016        String className;
7017        if (targetIsProfile) {
7018            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7019        } else {
7020            className = FORWARD_INTENT_TO_PARENT;
7021        }
7022        ComponentName forwardingActivityComponentName = new ComponentName(
7023                mAndroidApplication.packageName, className);
7024        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7025                sourceUserId);
7026        if (!targetIsProfile) {
7027            forwardingActivityInfo.showUserIcon = targetUserId;
7028            forwardingResolveInfo.noResourceId = true;
7029        }
7030        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7031        forwardingResolveInfo.priority = 0;
7032        forwardingResolveInfo.preferredOrder = 0;
7033        forwardingResolveInfo.match = 0;
7034        forwardingResolveInfo.isDefault = true;
7035        forwardingResolveInfo.filter = filter;
7036        forwardingResolveInfo.targetUserId = targetUserId;
7037        return forwardingResolveInfo;
7038    }
7039
7040    @Override
7041    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7042            Intent[] specifics, String[] specificTypes, Intent intent,
7043            String resolvedType, int flags, int userId) {
7044        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7045                specificTypes, intent, resolvedType, flags, userId));
7046    }
7047
7048    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7049            Intent[] specifics, String[] specificTypes, Intent intent,
7050            String resolvedType, int flags, int userId) {
7051        if (!sUserManager.exists(userId)) return Collections.emptyList();
7052        final int callingUid = Binder.getCallingUid();
7053        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7054                false /*includeInstantApps*/);
7055        enforceCrossUserPermission(callingUid, userId,
7056                false /*requireFullPermission*/, false /*checkShell*/,
7057                "query intent activity options");
7058        final String resultsAction = intent.getAction();
7059
7060        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7061                | PackageManager.GET_RESOLVED_FILTER, userId);
7062
7063        if (DEBUG_INTENT_MATCHING) {
7064            Log.v(TAG, "Query " + intent + ": " + results);
7065        }
7066
7067        int specificsPos = 0;
7068        int N;
7069
7070        // todo: note that the algorithm used here is O(N^2).  This
7071        // isn't a problem in our current environment, but if we start running
7072        // into situations where we have more than 5 or 10 matches then this
7073        // should probably be changed to something smarter...
7074
7075        // First we go through and resolve each of the specific items
7076        // that were supplied, taking care of removing any corresponding
7077        // duplicate items in the generic resolve list.
7078        if (specifics != null) {
7079            for (int i=0; i<specifics.length; i++) {
7080                final Intent sintent = specifics[i];
7081                if (sintent == null) {
7082                    continue;
7083                }
7084
7085                if (DEBUG_INTENT_MATCHING) {
7086                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7087                }
7088
7089                String action = sintent.getAction();
7090                if (resultsAction != null && resultsAction.equals(action)) {
7091                    // If this action was explicitly requested, then don't
7092                    // remove things that have it.
7093                    action = null;
7094                }
7095
7096                ResolveInfo ri = null;
7097                ActivityInfo ai = null;
7098
7099                ComponentName comp = sintent.getComponent();
7100                if (comp == null) {
7101                    ri = resolveIntent(
7102                        sintent,
7103                        specificTypes != null ? specificTypes[i] : null,
7104                            flags, userId);
7105                    if (ri == null) {
7106                        continue;
7107                    }
7108                    if (ri == mResolveInfo) {
7109                        // ACK!  Must do something better with this.
7110                    }
7111                    ai = ri.activityInfo;
7112                    comp = new ComponentName(ai.applicationInfo.packageName,
7113                            ai.name);
7114                } else {
7115                    ai = getActivityInfo(comp, flags, userId);
7116                    if (ai == null) {
7117                        continue;
7118                    }
7119                }
7120
7121                // Look for any generic query activities that are duplicates
7122                // of this specific one, and remove them from the results.
7123                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7124                N = results.size();
7125                int j;
7126                for (j=specificsPos; j<N; j++) {
7127                    ResolveInfo sri = results.get(j);
7128                    if ((sri.activityInfo.name.equals(comp.getClassName())
7129                            && sri.activityInfo.applicationInfo.packageName.equals(
7130                                    comp.getPackageName()))
7131                        || (action != null && sri.filter.matchAction(action))) {
7132                        results.remove(j);
7133                        if (DEBUG_INTENT_MATCHING) Log.v(
7134                            TAG, "Removing duplicate item from " + j
7135                            + " due to specific " + specificsPos);
7136                        if (ri == null) {
7137                            ri = sri;
7138                        }
7139                        j--;
7140                        N--;
7141                    }
7142                }
7143
7144                // Add this specific item to its proper place.
7145                if (ri == null) {
7146                    ri = new ResolveInfo();
7147                    ri.activityInfo = ai;
7148                }
7149                results.add(specificsPos, ri);
7150                ri.specificIndex = i;
7151                specificsPos++;
7152            }
7153        }
7154
7155        // Now we go through the remaining generic results and remove any
7156        // duplicate actions that are found here.
7157        N = results.size();
7158        for (int i=specificsPos; i<N-1; i++) {
7159            final ResolveInfo rii = results.get(i);
7160            if (rii.filter == null) {
7161                continue;
7162            }
7163
7164            // Iterate over all of the actions of this result's intent
7165            // filter...  typically this should be just one.
7166            final Iterator<String> it = rii.filter.actionsIterator();
7167            if (it == null) {
7168                continue;
7169            }
7170            while (it.hasNext()) {
7171                final String action = it.next();
7172                if (resultsAction != null && resultsAction.equals(action)) {
7173                    // If this action was explicitly requested, then don't
7174                    // remove things that have it.
7175                    continue;
7176                }
7177                for (int j=i+1; j<N; j++) {
7178                    final ResolveInfo rij = results.get(j);
7179                    if (rij.filter != null && rij.filter.hasAction(action)) {
7180                        results.remove(j);
7181                        if (DEBUG_INTENT_MATCHING) Log.v(
7182                            TAG, "Removing duplicate item from " + j
7183                            + " due to action " + action + " at " + i);
7184                        j--;
7185                        N--;
7186                    }
7187                }
7188            }
7189
7190            // If the caller didn't request filter information, drop it now
7191            // so we don't have to marshall/unmarshall it.
7192            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7193                rii.filter = null;
7194            }
7195        }
7196
7197        // Filter out the caller activity if so requested.
7198        if (caller != null) {
7199            N = results.size();
7200            for (int i=0; i<N; i++) {
7201                ActivityInfo ainfo = results.get(i).activityInfo;
7202                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7203                        && caller.getClassName().equals(ainfo.name)) {
7204                    results.remove(i);
7205                    break;
7206                }
7207            }
7208        }
7209
7210        // If the caller didn't request filter information,
7211        // drop them now so we don't have to
7212        // marshall/unmarshall it.
7213        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7214            N = results.size();
7215            for (int i=0; i<N; i++) {
7216                results.get(i).filter = null;
7217            }
7218        }
7219
7220        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7221        return results;
7222    }
7223
7224    @Override
7225    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7226            String resolvedType, int flags, int userId) {
7227        return new ParceledListSlice<>(
7228                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7229    }
7230
7231    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7232            String resolvedType, int flags, int userId) {
7233        if (!sUserManager.exists(userId)) return Collections.emptyList();
7234        final int callingUid = Binder.getCallingUid();
7235        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7236                false /*includeInstantApps*/);
7237        ComponentName comp = intent.getComponent();
7238        if (comp == null) {
7239            if (intent.getSelector() != null) {
7240                intent = intent.getSelector();
7241                comp = intent.getComponent();
7242            }
7243        }
7244        if (comp != null) {
7245            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7246            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7247            if (ai != null) {
7248                ResolveInfo ri = new ResolveInfo();
7249                ri.activityInfo = ai;
7250                list.add(ri);
7251            }
7252            return list;
7253        }
7254
7255        // reader
7256        synchronized (mPackages) {
7257            String pkgName = intent.getPackage();
7258            if (pkgName == null) {
7259                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
7260            }
7261            final PackageParser.Package pkg = mPackages.get(pkgName);
7262            if (pkg != null) {
7263                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
7264                        userId);
7265            }
7266            return Collections.emptyList();
7267        }
7268    }
7269
7270    @Override
7271    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7272        final int callingUid = Binder.getCallingUid();
7273        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7274    }
7275
7276    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7277            int userId, int callingUid) {
7278        if (!sUserManager.exists(userId)) return null;
7279        flags = updateFlagsForResolve(
7280                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7281        List<ResolveInfo> query = queryIntentServicesInternal(
7282                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7283        if (query != null) {
7284            if (query.size() >= 1) {
7285                // If there is more than one service with the same priority,
7286                // just arbitrarily pick the first one.
7287                return query.get(0);
7288            }
7289        }
7290        return null;
7291    }
7292
7293    @Override
7294    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7295            String resolvedType, int flags, int userId) {
7296        final int callingUid = Binder.getCallingUid();
7297        return new ParceledListSlice<>(queryIntentServicesInternal(
7298                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7299    }
7300
7301    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7302            String resolvedType, int flags, int userId, int callingUid,
7303            boolean includeInstantApps) {
7304        if (!sUserManager.exists(userId)) return Collections.emptyList();
7305        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7306        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7307        ComponentName comp = intent.getComponent();
7308        if (comp == null) {
7309            if (intent.getSelector() != null) {
7310                intent = intent.getSelector();
7311                comp = intent.getComponent();
7312            }
7313        }
7314        if (comp != null) {
7315            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7316            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7317            if (si != null) {
7318                // When specifying an explicit component, we prevent the service from being
7319                // used when either 1) the service is in an instant application and the
7320                // caller is not the same instant application or 2) the calling package is
7321                // ephemeral and the activity is not visible to ephemeral applications.
7322                final boolean matchInstantApp =
7323                        (flags & PackageManager.MATCH_INSTANT) != 0;
7324                final boolean matchVisibleToInstantAppOnly =
7325                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7326                final boolean isCallerInstantApp =
7327                        instantAppPkgName != null;
7328                final boolean isTargetSameInstantApp =
7329                        comp.getPackageName().equals(instantAppPkgName);
7330                final boolean isTargetInstantApp =
7331                        (si.applicationInfo.privateFlags
7332                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7333                final boolean isTargetHiddenFromInstantApp =
7334                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7335                final boolean blockResolution =
7336                        !isTargetSameInstantApp
7337                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7338                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7339                                        && isTargetHiddenFromInstantApp));
7340                if (!blockResolution) {
7341                    final ResolveInfo ri = new ResolveInfo();
7342                    ri.serviceInfo = si;
7343                    list.add(ri);
7344                }
7345            }
7346            return list;
7347        }
7348
7349        // reader
7350        synchronized (mPackages) {
7351            String pkgName = intent.getPackage();
7352            if (pkgName == null) {
7353                return applyPostServiceResolutionFilter(
7354                        mServices.queryIntent(intent, resolvedType, flags, userId),
7355                        instantAppPkgName);
7356            }
7357            final PackageParser.Package pkg = mPackages.get(pkgName);
7358            if (pkg != null) {
7359                return applyPostServiceResolutionFilter(
7360                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7361                                userId),
7362                        instantAppPkgName);
7363            }
7364            return Collections.emptyList();
7365        }
7366    }
7367
7368    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7369            String instantAppPkgName) {
7370        // TODO: When adding on-demand split support for non-instant apps, remove this check
7371        // and always apply post filtering
7372        if (instantAppPkgName == null) {
7373            return resolveInfos;
7374        }
7375        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7376            final ResolveInfo info = resolveInfos.get(i);
7377            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7378            // allow services that are defined in the provided package
7379            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7380                if (info.serviceInfo.splitName != null
7381                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7382                                info.serviceInfo.splitName)) {
7383                    // requested service is defined in a split that hasn't been installed yet.
7384                    // add the installer to the resolve list
7385                    if (DEBUG_EPHEMERAL) {
7386                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7387                    }
7388                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7389                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7390                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7391                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
7392                    // make sure this resolver is the default
7393                    installerInfo.isDefault = true;
7394                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7395                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7396                    // add a non-generic filter
7397                    installerInfo.filter = new IntentFilter();
7398                    // load resources from the correct package
7399                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7400                    resolveInfos.set(i, installerInfo);
7401                }
7402                continue;
7403            }
7404            // allow services that have been explicitly exposed to ephemeral apps
7405            if (!isEphemeralApp
7406                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7407                continue;
7408            }
7409            resolveInfos.remove(i);
7410        }
7411        return resolveInfos;
7412    }
7413
7414    @Override
7415    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7416            String resolvedType, int flags, int userId) {
7417        return new ParceledListSlice<>(
7418                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7419    }
7420
7421    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7422            Intent intent, String resolvedType, int flags, int userId) {
7423        if (!sUserManager.exists(userId)) return Collections.emptyList();
7424        final int callingUid = Binder.getCallingUid();
7425        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7426        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7427                false /*includeInstantApps*/);
7428        ComponentName comp = intent.getComponent();
7429        if (comp == null) {
7430            if (intent.getSelector() != null) {
7431                intent = intent.getSelector();
7432                comp = intent.getComponent();
7433            }
7434        }
7435        if (comp != null) {
7436            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7437            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7438            if (pi != null) {
7439                // When specifying an explicit component, we prevent the provider from being
7440                // used when either 1) the provider is in an instant application and the
7441                // caller is not the same instant application or 2) the calling package is an
7442                // instant application and the provider is not visible to instant applications.
7443                final boolean matchInstantApp =
7444                        (flags & PackageManager.MATCH_INSTANT) != 0;
7445                final boolean matchVisibleToInstantAppOnly =
7446                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7447                final boolean isCallerInstantApp =
7448                        instantAppPkgName != null;
7449                final boolean isTargetSameInstantApp =
7450                        comp.getPackageName().equals(instantAppPkgName);
7451                final boolean isTargetInstantApp =
7452                        (pi.applicationInfo.privateFlags
7453                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7454                final boolean isTargetHiddenFromInstantApp =
7455                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7456                final boolean blockResolution =
7457                        !isTargetSameInstantApp
7458                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7459                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7460                                        && isTargetHiddenFromInstantApp));
7461                if (!blockResolution) {
7462                    final ResolveInfo ri = new ResolveInfo();
7463                    ri.providerInfo = pi;
7464                    list.add(ri);
7465                }
7466            }
7467            return list;
7468        }
7469
7470        // reader
7471        synchronized (mPackages) {
7472            String pkgName = intent.getPackage();
7473            if (pkgName == null) {
7474                return applyPostContentProviderResolutionFilter(
7475                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7476                        instantAppPkgName);
7477            }
7478            final PackageParser.Package pkg = mPackages.get(pkgName);
7479            if (pkg != null) {
7480                return applyPostContentProviderResolutionFilter(
7481                        mProviders.queryIntentForPackage(
7482                        intent, resolvedType, flags, pkg.providers, userId),
7483                        instantAppPkgName);
7484            }
7485            return Collections.emptyList();
7486        }
7487    }
7488
7489    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7490            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7491        // TODO: When adding on-demand split support for non-instant applications, remove
7492        // this check and always apply post filtering
7493        if (instantAppPkgName == null) {
7494            return resolveInfos;
7495        }
7496        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7497            final ResolveInfo info = resolveInfos.get(i);
7498            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7499            // allow providers that are defined in the provided package
7500            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7501                if (info.providerInfo.splitName != null
7502                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7503                                info.providerInfo.splitName)) {
7504                    // requested provider is defined in a split that hasn't been installed yet.
7505                    // add the installer to the resolve list
7506                    if (DEBUG_EPHEMERAL) {
7507                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7508                    }
7509                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7510                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7511                            info.providerInfo.packageName, info.providerInfo.splitName,
7512                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
7513                    // make sure this resolver is the default
7514                    installerInfo.isDefault = true;
7515                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7516                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7517                    // add a non-generic filter
7518                    installerInfo.filter = new IntentFilter();
7519                    // load resources from the correct package
7520                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7521                    resolveInfos.set(i, installerInfo);
7522                }
7523                continue;
7524            }
7525            // allow providers that have been explicitly exposed to instant applications
7526            if (!isEphemeralApp
7527                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7528                continue;
7529            }
7530            resolveInfos.remove(i);
7531        }
7532        return resolveInfos;
7533    }
7534
7535    @Override
7536    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7537        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7538        flags = updateFlagsForPackage(flags, userId, null);
7539        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7540        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7541                true /* requireFullPermission */, false /* checkShell */,
7542                "get installed packages");
7543
7544        // writer
7545        synchronized (mPackages) {
7546            ArrayList<PackageInfo> list;
7547            if (listUninstalled) {
7548                list = new ArrayList<>(mSettings.mPackages.size());
7549                for (PackageSetting ps : mSettings.mPackages.values()) {
7550                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7551                        continue;
7552                    }
7553                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7554                    if (pi != null) {
7555                        list.add(pi);
7556                    }
7557                }
7558            } else {
7559                list = new ArrayList<>(mPackages.size());
7560                for (PackageParser.Package p : mPackages.values()) {
7561                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
7562                            Binder.getCallingUid(), userId)) {
7563                        continue;
7564                    }
7565                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7566                            p.mExtras, flags, userId);
7567                    if (pi != null) {
7568                        list.add(pi);
7569                    }
7570                }
7571            }
7572
7573            return new ParceledListSlice<>(list);
7574        }
7575    }
7576
7577    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7578            String[] permissions, boolean[] tmp, int flags, int userId) {
7579        int numMatch = 0;
7580        final PermissionsState permissionsState = ps.getPermissionsState();
7581        for (int i=0; i<permissions.length; i++) {
7582            final String permission = permissions[i];
7583            if (permissionsState.hasPermission(permission, userId)) {
7584                tmp[i] = true;
7585                numMatch++;
7586            } else {
7587                tmp[i] = false;
7588            }
7589        }
7590        if (numMatch == 0) {
7591            return;
7592        }
7593        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7594
7595        // The above might return null in cases of uninstalled apps or install-state
7596        // skew across users/profiles.
7597        if (pi != null) {
7598            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7599                if (numMatch == permissions.length) {
7600                    pi.requestedPermissions = permissions;
7601                } else {
7602                    pi.requestedPermissions = new String[numMatch];
7603                    numMatch = 0;
7604                    for (int i=0; i<permissions.length; i++) {
7605                        if (tmp[i]) {
7606                            pi.requestedPermissions[numMatch] = permissions[i];
7607                            numMatch++;
7608                        }
7609                    }
7610                }
7611            }
7612            list.add(pi);
7613        }
7614    }
7615
7616    @Override
7617    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7618            String[] permissions, int flags, int userId) {
7619        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7620        flags = updateFlagsForPackage(flags, userId, permissions);
7621        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7622                true /* requireFullPermission */, false /* checkShell */,
7623                "get packages holding permissions");
7624        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7625
7626        // writer
7627        synchronized (mPackages) {
7628            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7629            boolean[] tmpBools = new boolean[permissions.length];
7630            if (listUninstalled) {
7631                for (PackageSetting ps : mSettings.mPackages.values()) {
7632                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7633                            userId);
7634                }
7635            } else {
7636                for (PackageParser.Package pkg : mPackages.values()) {
7637                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7638                    if (ps != null) {
7639                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7640                                userId);
7641                    }
7642                }
7643            }
7644
7645            return new ParceledListSlice<PackageInfo>(list);
7646        }
7647    }
7648
7649    @Override
7650    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7651        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7652        flags = updateFlagsForApplication(flags, userId, null);
7653        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7654
7655        // writer
7656        synchronized (mPackages) {
7657            ArrayList<ApplicationInfo> list;
7658            if (listUninstalled) {
7659                list = new ArrayList<>(mSettings.mPackages.size());
7660                for (PackageSetting ps : mSettings.mPackages.values()) {
7661                    ApplicationInfo ai;
7662                    int effectiveFlags = flags;
7663                    if (ps.isSystem()) {
7664                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7665                    }
7666                    if (ps.pkg != null) {
7667                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7668                            continue;
7669                        }
7670                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7671                                ps.readUserState(userId), userId);
7672                        if (ai != null) {
7673                            rebaseEnabledOverlays(ai, userId);
7674                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7675                        }
7676                    } else {
7677                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7678                        // and already converts to externally visible package name
7679                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7680                                Binder.getCallingUid(), effectiveFlags, userId);
7681                    }
7682                    if (ai != null) {
7683                        list.add(ai);
7684                    }
7685                }
7686            } else {
7687                list = new ArrayList<>(mPackages.size());
7688                for (PackageParser.Package p : mPackages.values()) {
7689                    if (p.mExtras != null) {
7690                        PackageSetting ps = (PackageSetting) p.mExtras;
7691                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7692                            continue;
7693                        }
7694                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7695                                ps.readUserState(userId), userId);
7696                        if (ai != null) {
7697                            rebaseEnabledOverlays(ai, userId);
7698                            ai.packageName = resolveExternalPackageNameLPr(p);
7699                            list.add(ai);
7700                        }
7701                    }
7702                }
7703            }
7704
7705            return new ParceledListSlice<>(list);
7706        }
7707    }
7708
7709    @Override
7710    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7711        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7712            return null;
7713        }
7714
7715        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7716                "getEphemeralApplications");
7717        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7718                true /* requireFullPermission */, false /* checkShell */,
7719                "getEphemeralApplications");
7720        synchronized (mPackages) {
7721            List<InstantAppInfo> instantApps = mInstantAppRegistry
7722                    .getInstantAppsLPr(userId);
7723            if (instantApps != null) {
7724                return new ParceledListSlice<>(instantApps);
7725            }
7726        }
7727        return null;
7728    }
7729
7730    @Override
7731    public boolean isInstantApp(String packageName, int userId) {
7732        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7733                true /* requireFullPermission */, false /* checkShell */,
7734                "isInstantApp");
7735        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7736            return false;
7737        }
7738        int uid = Binder.getCallingUid();
7739        if (Process.isIsolated(uid)) {
7740            uid = mIsolatedOwners.get(uid);
7741        }
7742
7743        synchronized (mPackages) {
7744            final PackageSetting ps = mSettings.mPackages.get(packageName);
7745            PackageParser.Package pkg = mPackages.get(packageName);
7746            final boolean returnAllowed =
7747                    ps != null
7748                    && (isCallerSameApp(packageName, uid)
7749                            || mContext.checkCallingOrSelfPermission(
7750                                    android.Manifest.permission.ACCESS_INSTANT_APPS)
7751                                            == PERMISSION_GRANTED
7752                            || mInstantAppRegistry.isInstantAccessGranted(
7753                                    userId, UserHandle.getAppId(uid), ps.appId));
7754            if (returnAllowed) {
7755                return ps.getInstantApp(userId);
7756            }
7757        }
7758        return false;
7759    }
7760
7761    @Override
7762    public byte[] getInstantAppCookie(String packageName, int userId) {
7763        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7764            return null;
7765        }
7766
7767        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7768                true /* requireFullPermission */, false /* checkShell */,
7769                "getInstantAppCookie");
7770        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7771            return null;
7772        }
7773        synchronized (mPackages) {
7774            return mInstantAppRegistry.getInstantAppCookieLPw(
7775                    packageName, userId);
7776        }
7777    }
7778
7779    @Override
7780    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7781        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7782            return true;
7783        }
7784
7785        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7786                true /* requireFullPermission */, true /* checkShell */,
7787                "setInstantAppCookie");
7788        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7789            return false;
7790        }
7791        synchronized (mPackages) {
7792            return mInstantAppRegistry.setInstantAppCookieLPw(
7793                    packageName, cookie, userId);
7794        }
7795    }
7796
7797    @Override
7798    public Bitmap getInstantAppIcon(String packageName, int userId) {
7799        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7800            return null;
7801        }
7802
7803        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7804                "getInstantAppIcon");
7805
7806        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7807                true /* requireFullPermission */, false /* checkShell */,
7808                "getInstantAppIcon");
7809
7810        synchronized (mPackages) {
7811            return mInstantAppRegistry.getInstantAppIconLPw(
7812                    packageName, userId);
7813        }
7814    }
7815
7816    private boolean isCallerSameApp(String packageName, int uid) {
7817        PackageParser.Package pkg = mPackages.get(packageName);
7818        return pkg != null
7819                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
7820    }
7821
7822    @Override
7823    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7824        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7825    }
7826
7827    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7828        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7829
7830        // reader
7831        synchronized (mPackages) {
7832            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7833            final int userId = UserHandle.getCallingUserId();
7834            while (i.hasNext()) {
7835                final PackageParser.Package p = i.next();
7836                if (p.applicationInfo == null) continue;
7837
7838                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7839                        && !p.applicationInfo.isDirectBootAware();
7840                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7841                        && p.applicationInfo.isDirectBootAware();
7842
7843                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7844                        && (!mSafeMode || isSystemApp(p))
7845                        && (matchesUnaware || matchesAware)) {
7846                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7847                    if (ps != null) {
7848                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7849                                ps.readUserState(userId), userId);
7850                        if (ai != null) {
7851                            rebaseEnabledOverlays(ai, userId);
7852                            finalList.add(ai);
7853                        }
7854                    }
7855                }
7856            }
7857        }
7858
7859        return finalList;
7860    }
7861
7862    @Override
7863    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7864        if (!sUserManager.exists(userId)) return null;
7865        flags = updateFlagsForComponent(flags, userId, name);
7866        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
7867        // reader
7868        synchronized (mPackages) {
7869            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7870            PackageSetting ps = provider != null
7871                    ? mSettings.mPackages.get(provider.owner.packageName)
7872                    : null;
7873            if (ps != null) {
7874                final boolean isInstantApp = ps.getInstantApp(userId);
7875                // normal application; filter out instant application provider
7876                if (instantAppPkgName == null && isInstantApp) {
7877                    return null;
7878                }
7879                // instant application; filter out other instant applications
7880                if (instantAppPkgName != null
7881                        && isInstantApp
7882                        && !provider.owner.packageName.equals(instantAppPkgName)) {
7883                    return null;
7884                }
7885                // instant application; filter out non-exposed provider
7886                if (instantAppPkgName != null
7887                        && !isInstantApp
7888                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
7889                    return null;
7890                }
7891                // provider not enabled
7892                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
7893                    return null;
7894                }
7895                return PackageParser.generateProviderInfo(
7896                        provider, flags, ps.readUserState(userId), userId);
7897            }
7898            return null;
7899        }
7900    }
7901
7902    /**
7903     * @deprecated
7904     */
7905    @Deprecated
7906    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7907        // reader
7908        synchronized (mPackages) {
7909            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7910                    .entrySet().iterator();
7911            final int userId = UserHandle.getCallingUserId();
7912            while (i.hasNext()) {
7913                Map.Entry<String, PackageParser.Provider> entry = i.next();
7914                PackageParser.Provider p = entry.getValue();
7915                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7916
7917                if (ps != null && p.syncable
7918                        && (!mSafeMode || (p.info.applicationInfo.flags
7919                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7920                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7921                            ps.readUserState(userId), userId);
7922                    if (info != null) {
7923                        outNames.add(entry.getKey());
7924                        outInfo.add(info);
7925                    }
7926                }
7927            }
7928        }
7929    }
7930
7931    @Override
7932    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7933            int uid, int flags, String metaDataKey) {
7934        final int userId = processName != null ? UserHandle.getUserId(uid)
7935                : UserHandle.getCallingUserId();
7936        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7937        flags = updateFlagsForComponent(flags, userId, processName);
7938
7939        ArrayList<ProviderInfo> finalList = null;
7940        // reader
7941        synchronized (mPackages) {
7942            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7943            while (i.hasNext()) {
7944                final PackageParser.Provider p = i.next();
7945                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7946                if (ps != null && p.info.authority != null
7947                        && (processName == null
7948                                || (p.info.processName.equals(processName)
7949                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7950                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7951
7952                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
7953                    // parameter.
7954                    if (metaDataKey != null
7955                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
7956                        continue;
7957                    }
7958
7959                    if (finalList == null) {
7960                        finalList = new ArrayList<ProviderInfo>(3);
7961                    }
7962                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7963                            ps.readUserState(userId), userId);
7964                    if (info != null) {
7965                        finalList.add(info);
7966                    }
7967                }
7968            }
7969        }
7970
7971        if (finalList != null) {
7972            Collections.sort(finalList, mProviderInitOrderSorter);
7973            return new ParceledListSlice<ProviderInfo>(finalList);
7974        }
7975
7976        return ParceledListSlice.emptyList();
7977    }
7978
7979    @Override
7980    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7981        // reader
7982        synchronized (mPackages) {
7983            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7984            return PackageParser.generateInstrumentationInfo(i, flags);
7985        }
7986    }
7987
7988    @Override
7989    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7990            String targetPackage, int flags) {
7991        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7992    }
7993
7994    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7995            int flags) {
7996        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7997
7998        // reader
7999        synchronized (mPackages) {
8000            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8001            while (i.hasNext()) {
8002                final PackageParser.Instrumentation p = i.next();
8003                if (targetPackage == null
8004                        || targetPackage.equals(p.info.targetPackage)) {
8005                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8006                            flags);
8007                    if (ii != null) {
8008                        finalList.add(ii);
8009                    }
8010                }
8011            }
8012        }
8013
8014        return finalList;
8015    }
8016
8017    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8018        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8019        try {
8020            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8021        } finally {
8022            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8023        }
8024    }
8025
8026    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8027        final File[] files = dir.listFiles();
8028        if (ArrayUtils.isEmpty(files)) {
8029            Log.d(TAG, "No files in app dir " + dir);
8030            return;
8031        }
8032
8033        if (DEBUG_PACKAGE_SCANNING) {
8034            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8035                    + " flags=0x" + Integer.toHexString(parseFlags));
8036        }
8037        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8038                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8039                mParallelPackageParserCallback);
8040
8041        // Submit files for parsing in parallel
8042        int fileCount = 0;
8043        for (File file : files) {
8044            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8045                    && !PackageInstallerService.isStageName(file.getName());
8046            if (!isPackage) {
8047                // Ignore entries which are not packages
8048                continue;
8049            }
8050            parallelPackageParser.submit(file, parseFlags);
8051            fileCount++;
8052        }
8053
8054        // Process results one by one
8055        for (; fileCount > 0; fileCount--) {
8056            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8057            Throwable throwable = parseResult.throwable;
8058            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8059
8060            if (throwable == null) {
8061                // Static shared libraries have synthetic package names
8062                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8063                    renameStaticSharedLibraryPackage(parseResult.pkg);
8064                }
8065                try {
8066                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8067                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8068                                currentTime, null);
8069                    }
8070                } catch (PackageManagerException e) {
8071                    errorCode = e.error;
8072                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8073                }
8074            } else if (throwable instanceof PackageParser.PackageParserException) {
8075                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8076                        throwable;
8077                errorCode = e.error;
8078                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8079            } else {
8080                throw new IllegalStateException("Unexpected exception occurred while parsing "
8081                        + parseResult.scanFile, throwable);
8082            }
8083
8084            // Delete invalid userdata apps
8085            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8086                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8087                logCriticalInfo(Log.WARN,
8088                        "Deleting invalid package at " + parseResult.scanFile);
8089                removeCodePathLI(parseResult.scanFile);
8090            }
8091        }
8092        parallelPackageParser.close();
8093    }
8094
8095    private static File getSettingsProblemFile() {
8096        File dataDir = Environment.getDataDirectory();
8097        File systemDir = new File(dataDir, "system");
8098        File fname = new File(systemDir, "uiderrors.txt");
8099        return fname;
8100    }
8101
8102    static void reportSettingsProblem(int priority, String msg) {
8103        logCriticalInfo(priority, msg);
8104    }
8105
8106    public static void logCriticalInfo(int priority, String msg) {
8107        Slog.println(priority, TAG, msg);
8108        EventLogTags.writePmCriticalInfo(msg);
8109        try {
8110            File fname = getSettingsProblemFile();
8111            FileOutputStream out = new FileOutputStream(fname, true);
8112            PrintWriter pw = new FastPrintWriter(out);
8113            SimpleDateFormat formatter = new SimpleDateFormat();
8114            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8115            pw.println(dateString + ": " + msg);
8116            pw.close();
8117            FileUtils.setPermissions(
8118                    fname.toString(),
8119                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8120                    -1, -1);
8121        } catch (java.io.IOException e) {
8122        }
8123    }
8124
8125    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8126        if (srcFile.isDirectory()) {
8127            final File baseFile = new File(pkg.baseCodePath);
8128            long maxModifiedTime = baseFile.lastModified();
8129            if (pkg.splitCodePaths != null) {
8130                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8131                    final File splitFile = new File(pkg.splitCodePaths[i]);
8132                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8133                }
8134            }
8135            return maxModifiedTime;
8136        }
8137        return srcFile.lastModified();
8138    }
8139
8140    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8141            final int policyFlags) throws PackageManagerException {
8142        // When upgrading from pre-N MR1, verify the package time stamp using the package
8143        // directory and not the APK file.
8144        final long lastModifiedTime = mIsPreNMR1Upgrade
8145                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8146        if (ps != null
8147                && ps.codePath.equals(srcFile)
8148                && ps.timeStamp == lastModifiedTime
8149                && !isCompatSignatureUpdateNeeded(pkg)
8150                && !isRecoverSignatureUpdateNeeded(pkg)) {
8151            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8152            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8153            ArraySet<PublicKey> signingKs;
8154            synchronized (mPackages) {
8155                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8156            }
8157            if (ps.signatures.mSignatures != null
8158                    && ps.signatures.mSignatures.length != 0
8159                    && signingKs != null) {
8160                // Optimization: reuse the existing cached certificates
8161                // if the package appears to be unchanged.
8162                pkg.mSignatures = ps.signatures.mSignatures;
8163                pkg.mSigningKeys = signingKs;
8164                return;
8165            }
8166
8167            Slog.w(TAG, "PackageSetting for " + ps.name
8168                    + " is missing signatures.  Collecting certs again to recover them.");
8169        } else {
8170            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8171        }
8172
8173        try {
8174            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8175            PackageParser.collectCertificates(pkg, policyFlags);
8176        } catch (PackageParserException e) {
8177            throw PackageManagerException.from(e);
8178        } finally {
8179            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8180        }
8181    }
8182
8183    /**
8184     *  Traces a package scan.
8185     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8186     */
8187    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8188            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8189        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8190        try {
8191            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8192        } finally {
8193            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8194        }
8195    }
8196
8197    /**
8198     *  Scans a package and returns the newly parsed package.
8199     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8200     */
8201    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8202            long currentTime, UserHandle user) throws PackageManagerException {
8203        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8204        PackageParser pp = new PackageParser();
8205        pp.setSeparateProcesses(mSeparateProcesses);
8206        pp.setOnlyCoreApps(mOnlyCore);
8207        pp.setDisplayMetrics(mMetrics);
8208        pp.setCallback(mPackageParserCallback);
8209
8210        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8211            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8212        }
8213
8214        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8215        final PackageParser.Package pkg;
8216        try {
8217            pkg = pp.parsePackage(scanFile, parseFlags);
8218        } catch (PackageParserException e) {
8219            throw PackageManagerException.from(e);
8220        } finally {
8221            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8222        }
8223
8224        // Static shared libraries have synthetic package names
8225        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8226            renameStaticSharedLibraryPackage(pkg);
8227        }
8228
8229        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8230    }
8231
8232    /**
8233     *  Scans a package and returns the newly parsed package.
8234     *  @throws PackageManagerException on a parse error.
8235     */
8236    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8237            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8238            throws PackageManagerException {
8239        // If the package has children and this is the first dive in the function
8240        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8241        // packages (parent and children) would be successfully scanned before the
8242        // actual scan since scanning mutates internal state and we want to atomically
8243        // install the package and its children.
8244        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8245            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8246                scanFlags |= SCAN_CHECK_ONLY;
8247            }
8248        } else {
8249            scanFlags &= ~SCAN_CHECK_ONLY;
8250        }
8251
8252        // Scan the parent
8253        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8254                scanFlags, currentTime, user);
8255
8256        // Scan the children
8257        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8258        for (int i = 0; i < childCount; i++) {
8259            PackageParser.Package childPackage = pkg.childPackages.get(i);
8260            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8261                    currentTime, user);
8262        }
8263
8264
8265        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8266            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8267        }
8268
8269        return scannedPkg;
8270    }
8271
8272    /**
8273     *  Scans a package and returns the newly parsed package.
8274     *  @throws PackageManagerException on a parse error.
8275     */
8276    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8277            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8278            throws PackageManagerException {
8279        PackageSetting ps = null;
8280        PackageSetting updatedPkg;
8281        // reader
8282        synchronized (mPackages) {
8283            // Look to see if we already know about this package.
8284            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8285            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8286                // This package has been renamed to its original name.  Let's
8287                // use that.
8288                ps = mSettings.getPackageLPr(oldName);
8289            }
8290            // If there was no original package, see one for the real package name.
8291            if (ps == null) {
8292                ps = mSettings.getPackageLPr(pkg.packageName);
8293            }
8294            // Check to see if this package could be hiding/updating a system
8295            // package.  Must look for it either under the original or real
8296            // package name depending on our state.
8297            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8298            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8299
8300            // If this is a package we don't know about on the system partition, we
8301            // may need to remove disabled child packages on the system partition
8302            // or may need to not add child packages if the parent apk is updated
8303            // on the data partition and no longer defines this child package.
8304            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8305                // If this is a parent package for an updated system app and this system
8306                // app got an OTA update which no longer defines some of the child packages
8307                // we have to prune them from the disabled system packages.
8308                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8309                if (disabledPs != null) {
8310                    final int scannedChildCount = (pkg.childPackages != null)
8311                            ? pkg.childPackages.size() : 0;
8312                    final int disabledChildCount = disabledPs.childPackageNames != null
8313                            ? disabledPs.childPackageNames.size() : 0;
8314                    for (int i = 0; i < disabledChildCount; i++) {
8315                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8316                        boolean disabledPackageAvailable = false;
8317                        for (int j = 0; j < scannedChildCount; j++) {
8318                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8319                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8320                                disabledPackageAvailable = true;
8321                                break;
8322                            }
8323                         }
8324                         if (!disabledPackageAvailable) {
8325                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8326                         }
8327                    }
8328                }
8329            }
8330        }
8331
8332        boolean updatedPkgBetter = false;
8333        // First check if this is a system package that may involve an update
8334        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8335            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8336            // it needs to drop FLAG_PRIVILEGED.
8337            if (locationIsPrivileged(scanFile)) {
8338                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8339            } else {
8340                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8341            }
8342
8343            if (ps != null && !ps.codePath.equals(scanFile)) {
8344                // The path has changed from what was last scanned...  check the
8345                // version of the new path against what we have stored to determine
8346                // what to do.
8347                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8348                if (pkg.mVersionCode <= ps.versionCode) {
8349                    // The system package has been updated and the code path does not match
8350                    // Ignore entry. Skip it.
8351                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8352                            + " ignored: updated version " + ps.versionCode
8353                            + " better than this " + pkg.mVersionCode);
8354                    if (!updatedPkg.codePath.equals(scanFile)) {
8355                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8356                                + ps.name + " changing from " + updatedPkg.codePathString
8357                                + " to " + scanFile);
8358                        updatedPkg.codePath = scanFile;
8359                        updatedPkg.codePathString = scanFile.toString();
8360                        updatedPkg.resourcePath = scanFile;
8361                        updatedPkg.resourcePathString = scanFile.toString();
8362                    }
8363                    updatedPkg.pkg = pkg;
8364                    updatedPkg.versionCode = pkg.mVersionCode;
8365
8366                    // Update the disabled system child packages to point to the package too.
8367                    final int childCount = updatedPkg.childPackageNames != null
8368                            ? updatedPkg.childPackageNames.size() : 0;
8369                    for (int i = 0; i < childCount; i++) {
8370                        String childPackageName = updatedPkg.childPackageNames.get(i);
8371                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8372                                childPackageName);
8373                        if (updatedChildPkg != null) {
8374                            updatedChildPkg.pkg = pkg;
8375                            updatedChildPkg.versionCode = pkg.mVersionCode;
8376                        }
8377                    }
8378
8379                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8380                            + scanFile + " ignored: updated version " + ps.versionCode
8381                            + " better than this " + pkg.mVersionCode);
8382                } else {
8383                    // The current app on the system partition is better than
8384                    // what we have updated to on the data partition; switch
8385                    // back to the system partition version.
8386                    // At this point, its safely assumed that package installation for
8387                    // apps in system partition will go through. If not there won't be a working
8388                    // version of the app
8389                    // writer
8390                    synchronized (mPackages) {
8391                        // Just remove the loaded entries from package lists.
8392                        mPackages.remove(ps.name);
8393                    }
8394
8395                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8396                            + " reverting from " + ps.codePathString
8397                            + ": new version " + pkg.mVersionCode
8398                            + " better than installed " + ps.versionCode);
8399
8400                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8401                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8402                    synchronized (mInstallLock) {
8403                        args.cleanUpResourcesLI();
8404                    }
8405                    synchronized (mPackages) {
8406                        mSettings.enableSystemPackageLPw(ps.name);
8407                    }
8408                    updatedPkgBetter = true;
8409                }
8410            }
8411        }
8412
8413        if (updatedPkg != null) {
8414            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8415            // initially
8416            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8417
8418            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8419            // flag set initially
8420            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8421                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8422            }
8423        }
8424
8425        // Verify certificates against what was last scanned
8426        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8427
8428        /*
8429         * A new system app appeared, but we already had a non-system one of the
8430         * same name installed earlier.
8431         */
8432        boolean shouldHideSystemApp = false;
8433        if (updatedPkg == null && ps != null
8434                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8435            /*
8436             * Check to make sure the signatures match first. If they don't,
8437             * wipe the installed application and its data.
8438             */
8439            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
8440                    != PackageManager.SIGNATURE_MATCH) {
8441                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
8442                        + " signatures don't match existing userdata copy; removing");
8443                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8444                        "scanPackageInternalLI")) {
8445                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8446                }
8447                ps = null;
8448            } else {
8449                /*
8450                 * If the newly-added system app is an older version than the
8451                 * already installed version, hide it. It will be scanned later
8452                 * and re-added like an update.
8453                 */
8454                if (pkg.mVersionCode <= ps.versionCode) {
8455                    shouldHideSystemApp = true;
8456                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8457                            + " but new version " + pkg.mVersionCode + " better than installed "
8458                            + ps.versionCode + "; hiding system");
8459                } else {
8460                    /*
8461                     * The newly found system app is a newer version that the
8462                     * one previously installed. Simply remove the
8463                     * already-installed application and replace it with our own
8464                     * while keeping the application data.
8465                     */
8466                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8467                            + " reverting from " + ps.codePathString + ": new version "
8468                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8469                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8470                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8471                    synchronized (mInstallLock) {
8472                        args.cleanUpResourcesLI();
8473                    }
8474                }
8475            }
8476        }
8477
8478        // The apk is forward locked (not public) if its code and resources
8479        // are kept in different files. (except for app in either system or
8480        // vendor path).
8481        // TODO grab this value from PackageSettings
8482        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8483            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8484                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8485            }
8486        }
8487
8488        // TODO: extend to support forward-locked splits
8489        String resourcePath = null;
8490        String baseResourcePath = null;
8491        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
8492            if (ps != null && ps.resourcePathString != null) {
8493                resourcePath = ps.resourcePathString;
8494                baseResourcePath = ps.resourcePathString;
8495            } else {
8496                // Should not happen at all. Just log an error.
8497                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8498            }
8499        } else {
8500            resourcePath = pkg.codePath;
8501            baseResourcePath = pkg.baseCodePath;
8502        }
8503
8504        // Set application objects path explicitly.
8505        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8506        pkg.setApplicationInfoCodePath(pkg.codePath);
8507        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8508        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8509        pkg.setApplicationInfoResourcePath(resourcePath);
8510        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8511        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8512
8513        final int userId = ((user == null) ? 0 : user.getIdentifier());
8514        if (ps != null && ps.getInstantApp(userId)) {
8515            scanFlags |= SCAN_AS_INSTANT_APP;
8516        }
8517
8518        // Note that we invoke the following method only if we are about to unpack an application
8519        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8520                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8521
8522        /*
8523         * If the system app should be overridden by a previously installed
8524         * data, hide the system app now and let the /data/app scan pick it up
8525         * again.
8526         */
8527        if (shouldHideSystemApp) {
8528            synchronized (mPackages) {
8529                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8530            }
8531        }
8532
8533        return scannedPkg;
8534    }
8535
8536    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8537        // Derive the new package synthetic package name
8538        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8539                + pkg.staticSharedLibVersion);
8540    }
8541
8542    private static String fixProcessName(String defProcessName,
8543            String processName) {
8544        if (processName == null) {
8545            return defProcessName;
8546        }
8547        return processName;
8548    }
8549
8550    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8551            throws PackageManagerException {
8552        if (pkgSetting.signatures.mSignatures != null) {
8553            // Already existing package. Make sure signatures match
8554            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8555                    == PackageManager.SIGNATURE_MATCH;
8556            if (!match) {
8557                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8558                        == PackageManager.SIGNATURE_MATCH;
8559            }
8560            if (!match) {
8561                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8562                        == PackageManager.SIGNATURE_MATCH;
8563            }
8564            if (!match) {
8565                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8566                        + pkg.packageName + " signatures do not match the "
8567                        + "previously installed version; ignoring!");
8568            }
8569        }
8570
8571        // Check for shared user signatures
8572        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8573            // Already existing package. Make sure signatures match
8574            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8575                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8576            if (!match) {
8577                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8578                        == PackageManager.SIGNATURE_MATCH;
8579            }
8580            if (!match) {
8581                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8582                        == PackageManager.SIGNATURE_MATCH;
8583            }
8584            if (!match) {
8585                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8586                        "Package " + pkg.packageName
8587                        + " has no signatures that match those in shared user "
8588                        + pkgSetting.sharedUser.name + "; ignoring!");
8589            }
8590        }
8591    }
8592
8593    /**
8594     * Enforces that only the system UID or root's UID can call a method exposed
8595     * via Binder.
8596     *
8597     * @param message used as message if SecurityException is thrown
8598     * @throws SecurityException if the caller is not system or root
8599     */
8600    private static final void enforceSystemOrRoot(String message) {
8601        final int uid = Binder.getCallingUid();
8602        if (uid != Process.SYSTEM_UID && uid != 0) {
8603            throw new SecurityException(message);
8604        }
8605    }
8606
8607    @Override
8608    public void performFstrimIfNeeded() {
8609        enforceSystemOrRoot("Only the system can request fstrim");
8610
8611        // Before everything else, see whether we need to fstrim.
8612        try {
8613            IStorageManager sm = PackageHelper.getStorageManager();
8614            if (sm != null) {
8615                boolean doTrim = false;
8616                final long interval = android.provider.Settings.Global.getLong(
8617                        mContext.getContentResolver(),
8618                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8619                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8620                if (interval > 0) {
8621                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8622                    if (timeSinceLast > interval) {
8623                        doTrim = true;
8624                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8625                                + "; running immediately");
8626                    }
8627                }
8628                if (doTrim) {
8629                    final boolean dexOptDialogShown;
8630                    synchronized (mPackages) {
8631                        dexOptDialogShown = mDexOptDialogShown;
8632                    }
8633                    if (!isFirstBoot() && dexOptDialogShown) {
8634                        try {
8635                            ActivityManager.getService().showBootMessage(
8636                                    mContext.getResources().getString(
8637                                            R.string.android_upgrading_fstrim), true);
8638                        } catch (RemoteException e) {
8639                        }
8640                    }
8641                    sm.runMaintenance();
8642                }
8643            } else {
8644                Slog.e(TAG, "storageManager service unavailable!");
8645            }
8646        } catch (RemoteException e) {
8647            // Can't happen; StorageManagerService is local
8648        }
8649    }
8650
8651    @Override
8652    public void updatePackagesIfNeeded() {
8653        enforceSystemOrRoot("Only the system can request package update");
8654
8655        // We need to re-extract after an OTA.
8656        boolean causeUpgrade = isUpgrade();
8657
8658        // First boot or factory reset.
8659        // Note: we also handle devices that are upgrading to N right now as if it is their
8660        //       first boot, as they do not have profile data.
8661        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8662
8663        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8664        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8665
8666        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8667            return;
8668        }
8669
8670        List<PackageParser.Package> pkgs;
8671        synchronized (mPackages) {
8672            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8673        }
8674
8675        final long startTime = System.nanoTime();
8676        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8677                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8678
8679        final int elapsedTimeSeconds =
8680                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8681
8682        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8683        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8684        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8685        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8686        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8687    }
8688
8689    /**
8690     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8691     * containing statistics about the invocation. The array consists of three elements,
8692     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8693     * and {@code numberOfPackagesFailed}.
8694     */
8695    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8696            String compilerFilter) {
8697
8698        int numberOfPackagesVisited = 0;
8699        int numberOfPackagesOptimized = 0;
8700        int numberOfPackagesSkipped = 0;
8701        int numberOfPackagesFailed = 0;
8702        final int numberOfPackagesToDexopt = pkgs.size();
8703
8704        for (PackageParser.Package pkg : pkgs) {
8705            numberOfPackagesVisited++;
8706
8707            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8708                if (DEBUG_DEXOPT) {
8709                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8710                }
8711                numberOfPackagesSkipped++;
8712                continue;
8713            }
8714
8715            if (DEBUG_DEXOPT) {
8716                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8717                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8718            }
8719
8720            if (showDialog) {
8721                try {
8722                    ActivityManager.getService().showBootMessage(
8723                            mContext.getResources().getString(R.string.android_upgrading_apk,
8724                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8725                } catch (RemoteException e) {
8726                }
8727                synchronized (mPackages) {
8728                    mDexOptDialogShown = true;
8729                }
8730            }
8731
8732            // If the OTA updates a system app which was previously preopted to a non-preopted state
8733            // the app might end up being verified at runtime. That's because by default the apps
8734            // are verify-profile but for preopted apps there's no profile.
8735            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8736            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8737            // filter (by default 'quicken').
8738            // Note that at this stage unused apps are already filtered.
8739            if (isSystemApp(pkg) &&
8740                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8741                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8742                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8743            }
8744
8745            // checkProfiles is false to avoid merging profiles during boot which
8746            // might interfere with background compilation (b/28612421).
8747            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8748            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8749            // trade-off worth doing to save boot time work.
8750            int dexOptStatus = performDexOptTraced(pkg.packageName,
8751                    false /* checkProfiles */,
8752                    compilerFilter,
8753                    false /* force */);
8754            switch (dexOptStatus) {
8755                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8756                    numberOfPackagesOptimized++;
8757                    break;
8758                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8759                    numberOfPackagesSkipped++;
8760                    break;
8761                case PackageDexOptimizer.DEX_OPT_FAILED:
8762                    numberOfPackagesFailed++;
8763                    break;
8764                default:
8765                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8766                    break;
8767            }
8768        }
8769
8770        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8771                numberOfPackagesFailed };
8772    }
8773
8774    @Override
8775    public void notifyPackageUse(String packageName, int reason) {
8776        synchronized (mPackages) {
8777            PackageParser.Package p = mPackages.get(packageName);
8778            if (p == null) {
8779                return;
8780            }
8781            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8782        }
8783    }
8784
8785    @Override
8786    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8787        int userId = UserHandle.getCallingUserId();
8788        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8789        if (ai == null) {
8790            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8791                + loadingPackageName + ", user=" + userId);
8792            return;
8793        }
8794        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8795    }
8796
8797    @Override
8798    public boolean performDexOpt(String packageName,
8799            boolean checkProfiles, int compileReason, boolean force) {
8800        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8801                getCompilerFilterForReason(compileReason), force);
8802        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8803    }
8804
8805    @Override
8806    public boolean performDexOptMode(String packageName,
8807            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8808        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8809                targetCompilerFilter, force);
8810        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8811    }
8812
8813    private int performDexOptTraced(String packageName,
8814                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8815        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8816        try {
8817            return performDexOptInternal(packageName, checkProfiles,
8818                    targetCompilerFilter, force);
8819        } finally {
8820            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8821        }
8822    }
8823
8824    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8825    // if the package can now be considered up to date for the given filter.
8826    private int performDexOptInternal(String packageName,
8827                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8828        PackageParser.Package p;
8829        synchronized (mPackages) {
8830            p = mPackages.get(packageName);
8831            if (p == null) {
8832                // Package could not be found. Report failure.
8833                return PackageDexOptimizer.DEX_OPT_FAILED;
8834            }
8835            mPackageUsage.maybeWriteAsync(mPackages);
8836            mCompilerStats.maybeWriteAsync();
8837        }
8838        long callingId = Binder.clearCallingIdentity();
8839        try {
8840            synchronized (mInstallLock) {
8841                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8842                        targetCompilerFilter, force);
8843            }
8844        } finally {
8845            Binder.restoreCallingIdentity(callingId);
8846        }
8847    }
8848
8849    public ArraySet<String> getOptimizablePackages() {
8850        ArraySet<String> pkgs = new ArraySet<String>();
8851        synchronized (mPackages) {
8852            for (PackageParser.Package p : mPackages.values()) {
8853                if (PackageDexOptimizer.canOptimizePackage(p)) {
8854                    pkgs.add(p.packageName);
8855                }
8856            }
8857        }
8858        return pkgs;
8859    }
8860
8861    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8862            boolean checkProfiles, String targetCompilerFilter,
8863            boolean force) {
8864        // Select the dex optimizer based on the force parameter.
8865        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8866        //       allocate an object here.
8867        PackageDexOptimizer pdo = force
8868                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8869                : mPackageDexOptimizer;
8870
8871        // Dexopt all dependencies first. Note: we ignore the return value and march on
8872        // on errors.
8873        // Note that we are going to call performDexOpt on those libraries as many times as
8874        // they are referenced in packages. When we do a batch of performDexOpt (for example
8875        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
8876        // and the first package that uses the library will dexopt it. The
8877        // others will see that the compiled code for the library is up to date.
8878        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8879        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8880        if (!deps.isEmpty()) {
8881            for (PackageParser.Package depPackage : deps) {
8882                // TODO: Analyze and investigate if we (should) profile libraries.
8883                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8884                        false /* checkProfiles */,
8885                        targetCompilerFilter,
8886                        getOrCreateCompilerPackageStats(depPackage),
8887                        true /* isUsedByOtherApps */);
8888            }
8889        }
8890        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8891                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
8892                mDexManager.isUsedByOtherApps(p.packageName));
8893    }
8894
8895    // Performs dexopt on the used secondary dex files belonging to the given package.
8896    // Returns true if all dex files were process successfully (which could mean either dexopt or
8897    // skip). Returns false if any of the files caused errors.
8898    @Override
8899    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8900            boolean force) {
8901        mDexManager.reconcileSecondaryDexFiles(packageName);
8902        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8903    }
8904
8905    public boolean performDexOptSecondary(String packageName, int compileReason,
8906            boolean force) {
8907        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
8908    }
8909
8910    /**
8911     * Reconcile the information we have about the secondary dex files belonging to
8912     * {@code packagName} and the actual dex files. For all dex files that were
8913     * deleted, update the internal records and delete the generated oat files.
8914     */
8915    @Override
8916    public void reconcileSecondaryDexFiles(String packageName) {
8917        mDexManager.reconcileSecondaryDexFiles(packageName);
8918    }
8919
8920    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8921    // a reference there.
8922    /*package*/ DexManager getDexManager() {
8923        return mDexManager;
8924    }
8925
8926    /**
8927     * Execute the background dexopt job immediately.
8928     */
8929    @Override
8930    public boolean runBackgroundDexoptJob() {
8931        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8932    }
8933
8934    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8935        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8936                || p.usesStaticLibraries != null) {
8937            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8938            Set<String> collectedNames = new HashSet<>();
8939            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8940
8941            retValue.remove(p);
8942
8943            return retValue;
8944        } else {
8945            return Collections.emptyList();
8946        }
8947    }
8948
8949    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8950            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8951        if (!collectedNames.contains(p.packageName)) {
8952            collectedNames.add(p.packageName);
8953            collected.add(p);
8954
8955            if (p.usesLibraries != null) {
8956                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8957                        null, collected, collectedNames);
8958            }
8959            if (p.usesOptionalLibraries != null) {
8960                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8961                        null, collected, collectedNames);
8962            }
8963            if (p.usesStaticLibraries != null) {
8964                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8965                        p.usesStaticLibrariesVersions, collected, collectedNames);
8966            }
8967        }
8968    }
8969
8970    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8971            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8972        final int libNameCount = libs.size();
8973        for (int i = 0; i < libNameCount; i++) {
8974            String libName = libs.get(i);
8975            int version = (versions != null && versions.length == libNameCount)
8976                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8977            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8978            if (libPkg != null) {
8979                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8980            }
8981        }
8982    }
8983
8984    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8985        synchronized (mPackages) {
8986            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8987            if (libEntry != null) {
8988                return mPackages.get(libEntry.apk);
8989            }
8990            return null;
8991        }
8992    }
8993
8994    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8995        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8996        if (versionedLib == null) {
8997            return null;
8998        }
8999        return versionedLib.get(version);
9000    }
9001
9002    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9003        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9004                pkg.staticSharedLibName);
9005        if (versionedLib == null) {
9006            return null;
9007        }
9008        int previousLibVersion = -1;
9009        final int versionCount = versionedLib.size();
9010        for (int i = 0; i < versionCount; i++) {
9011            final int libVersion = versionedLib.keyAt(i);
9012            if (libVersion < pkg.staticSharedLibVersion) {
9013                previousLibVersion = Math.max(previousLibVersion, libVersion);
9014            }
9015        }
9016        if (previousLibVersion >= 0) {
9017            return versionedLib.get(previousLibVersion);
9018        }
9019        return null;
9020    }
9021
9022    public void shutdown() {
9023        mPackageUsage.writeNow(mPackages);
9024        mCompilerStats.writeNow();
9025    }
9026
9027    @Override
9028    public void dumpProfiles(String packageName) {
9029        PackageParser.Package pkg;
9030        synchronized (mPackages) {
9031            pkg = mPackages.get(packageName);
9032            if (pkg == null) {
9033                throw new IllegalArgumentException("Unknown package: " + packageName);
9034            }
9035        }
9036        /* Only the shell, root, or the app user should be able to dump profiles. */
9037        int callingUid = Binder.getCallingUid();
9038        if (callingUid != Process.SHELL_UID &&
9039            callingUid != Process.ROOT_UID &&
9040            callingUid != pkg.applicationInfo.uid) {
9041            throw new SecurityException("dumpProfiles");
9042        }
9043
9044        synchronized (mInstallLock) {
9045            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9046            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9047            try {
9048                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9049                String codePaths = TextUtils.join(";", allCodePaths);
9050                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9051            } catch (InstallerException e) {
9052                Slog.w(TAG, "Failed to dump profiles", e);
9053            }
9054            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9055        }
9056    }
9057
9058    @Override
9059    public void forceDexOpt(String packageName) {
9060        enforceSystemOrRoot("forceDexOpt");
9061
9062        PackageParser.Package pkg;
9063        synchronized (mPackages) {
9064            pkg = mPackages.get(packageName);
9065            if (pkg == null) {
9066                throw new IllegalArgumentException("Unknown package: " + packageName);
9067            }
9068        }
9069
9070        synchronized (mInstallLock) {
9071            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9072
9073            // Whoever is calling forceDexOpt wants a compiled package.
9074            // Don't use profiles since that may cause compilation to be skipped.
9075            final int res = performDexOptInternalWithDependenciesLI(pkg,
9076                    false /* checkProfiles */, getDefaultCompilerFilter(),
9077                    true /* force */);
9078
9079            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9080            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9081                throw new IllegalStateException("Failed to dexopt: " + res);
9082            }
9083        }
9084    }
9085
9086    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9087        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9088            Slog.w(TAG, "Unable to update from " + oldPkg.name
9089                    + " to " + newPkg.packageName
9090                    + ": old package not in system partition");
9091            return false;
9092        } else if (mPackages.get(oldPkg.name) != null) {
9093            Slog.w(TAG, "Unable to update from " + oldPkg.name
9094                    + " to " + newPkg.packageName
9095                    + ": old package still exists");
9096            return false;
9097        }
9098        return true;
9099    }
9100
9101    void removeCodePathLI(File codePath) {
9102        if (codePath.isDirectory()) {
9103            try {
9104                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9105            } catch (InstallerException e) {
9106                Slog.w(TAG, "Failed to remove code path", e);
9107            }
9108        } else {
9109            codePath.delete();
9110        }
9111    }
9112
9113    private int[] resolveUserIds(int userId) {
9114        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9115    }
9116
9117    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9118        if (pkg == null) {
9119            Slog.wtf(TAG, "Package was null!", new Throwable());
9120            return;
9121        }
9122        clearAppDataLeafLIF(pkg, userId, flags);
9123        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9124        for (int i = 0; i < childCount; i++) {
9125            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9126        }
9127    }
9128
9129    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9130        final PackageSetting ps;
9131        synchronized (mPackages) {
9132            ps = mSettings.mPackages.get(pkg.packageName);
9133        }
9134        for (int realUserId : resolveUserIds(userId)) {
9135            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9136            try {
9137                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9138                        ceDataInode);
9139            } catch (InstallerException e) {
9140                Slog.w(TAG, String.valueOf(e));
9141            }
9142        }
9143    }
9144
9145    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9146        if (pkg == null) {
9147            Slog.wtf(TAG, "Package was null!", new Throwable());
9148            return;
9149        }
9150        destroyAppDataLeafLIF(pkg, userId, flags);
9151        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9152        for (int i = 0; i < childCount; i++) {
9153            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9154        }
9155    }
9156
9157    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9158        final PackageSetting ps;
9159        synchronized (mPackages) {
9160            ps = mSettings.mPackages.get(pkg.packageName);
9161        }
9162        for (int realUserId : resolveUserIds(userId)) {
9163            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9164            try {
9165                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9166                        ceDataInode);
9167            } catch (InstallerException e) {
9168                Slog.w(TAG, String.valueOf(e));
9169            }
9170            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9171        }
9172    }
9173
9174    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9175        if (pkg == null) {
9176            Slog.wtf(TAG, "Package was null!", new Throwable());
9177            return;
9178        }
9179        destroyAppProfilesLeafLIF(pkg);
9180        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9181        for (int i = 0; i < childCount; i++) {
9182            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9183        }
9184    }
9185
9186    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9187        try {
9188            mInstaller.destroyAppProfiles(pkg.packageName);
9189        } catch (InstallerException e) {
9190            Slog.w(TAG, String.valueOf(e));
9191        }
9192    }
9193
9194    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9195        if (pkg == null) {
9196            Slog.wtf(TAG, "Package was null!", new Throwable());
9197            return;
9198        }
9199        clearAppProfilesLeafLIF(pkg);
9200        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9201        for (int i = 0; i < childCount; i++) {
9202            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9203        }
9204    }
9205
9206    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9207        try {
9208            mInstaller.clearAppProfiles(pkg.packageName);
9209        } catch (InstallerException e) {
9210            Slog.w(TAG, String.valueOf(e));
9211        }
9212    }
9213
9214    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9215            long lastUpdateTime) {
9216        // Set parent install/update time
9217        PackageSetting ps = (PackageSetting) pkg.mExtras;
9218        if (ps != null) {
9219            ps.firstInstallTime = firstInstallTime;
9220            ps.lastUpdateTime = lastUpdateTime;
9221        }
9222        // Set children install/update time
9223        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9224        for (int i = 0; i < childCount; i++) {
9225            PackageParser.Package childPkg = pkg.childPackages.get(i);
9226            ps = (PackageSetting) childPkg.mExtras;
9227            if (ps != null) {
9228                ps.firstInstallTime = firstInstallTime;
9229                ps.lastUpdateTime = lastUpdateTime;
9230            }
9231        }
9232    }
9233
9234    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9235            PackageParser.Package changingLib) {
9236        if (file.path != null) {
9237            usesLibraryFiles.add(file.path);
9238            return;
9239        }
9240        PackageParser.Package p = mPackages.get(file.apk);
9241        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9242            // If we are doing this while in the middle of updating a library apk,
9243            // then we need to make sure to use that new apk for determining the
9244            // dependencies here.  (We haven't yet finished committing the new apk
9245            // to the package manager state.)
9246            if (p == null || p.packageName.equals(changingLib.packageName)) {
9247                p = changingLib;
9248            }
9249        }
9250        if (p != null) {
9251            usesLibraryFiles.addAll(p.getAllCodePaths());
9252        }
9253    }
9254
9255    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9256            PackageParser.Package changingLib) throws PackageManagerException {
9257        if (pkg == null) {
9258            return;
9259        }
9260        ArraySet<String> usesLibraryFiles = null;
9261        if (pkg.usesLibraries != null) {
9262            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9263                    null, null, pkg.packageName, changingLib, true, null);
9264        }
9265        if (pkg.usesStaticLibraries != null) {
9266            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9267                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9268                    pkg.packageName, changingLib, true, usesLibraryFiles);
9269        }
9270        if (pkg.usesOptionalLibraries != null) {
9271            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9272                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
9273        }
9274        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9275            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9276        } else {
9277            pkg.usesLibraryFiles = null;
9278        }
9279    }
9280
9281    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9282            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
9283            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9284            boolean required, @Nullable ArraySet<String> outUsedLibraries)
9285            throws PackageManagerException {
9286        final int libCount = requestedLibraries.size();
9287        for (int i = 0; i < libCount; i++) {
9288            final String libName = requestedLibraries.get(i);
9289            final int libVersion = requiredVersions != null ? requiredVersions[i]
9290                    : SharedLibraryInfo.VERSION_UNDEFINED;
9291            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9292            if (libEntry == null) {
9293                if (required) {
9294                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9295                            "Package " + packageName + " requires unavailable shared library "
9296                                    + libName + "; failing!");
9297                } else {
9298                    Slog.w(TAG, "Package " + packageName
9299                            + " desires unavailable shared library "
9300                            + libName + "; ignoring!");
9301                }
9302            } else {
9303                if (requiredVersions != null && requiredCertDigests != null) {
9304                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9305                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9306                            "Package " + packageName + " requires unavailable static shared"
9307                                    + " library " + libName + " version "
9308                                    + libEntry.info.getVersion() + "; failing!");
9309                    }
9310
9311                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9312                    if (libPkg == null) {
9313                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9314                                "Package " + packageName + " requires unavailable static shared"
9315                                        + " library; failing!");
9316                    }
9317
9318                    String expectedCertDigest = requiredCertDigests[i];
9319                    String libCertDigest = PackageUtils.computeCertSha256Digest(
9320                                libPkg.mSignatures[0]);
9321                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
9322                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9323                                "Package " + packageName + " requires differently signed" +
9324                                        " static shared library; failing!");
9325                    }
9326                }
9327
9328                if (outUsedLibraries == null) {
9329                    outUsedLibraries = new ArraySet<>();
9330                }
9331                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9332            }
9333        }
9334        return outUsedLibraries;
9335    }
9336
9337    private static boolean hasString(List<String> list, List<String> which) {
9338        if (list == null) {
9339            return false;
9340        }
9341        for (int i=list.size()-1; i>=0; i--) {
9342            for (int j=which.size()-1; j>=0; j--) {
9343                if (which.get(j).equals(list.get(i))) {
9344                    return true;
9345                }
9346            }
9347        }
9348        return false;
9349    }
9350
9351    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9352            PackageParser.Package changingPkg) {
9353        ArrayList<PackageParser.Package> res = null;
9354        for (PackageParser.Package pkg : mPackages.values()) {
9355            if (changingPkg != null
9356                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9357                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9358                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9359                            changingPkg.staticSharedLibName)) {
9360                return null;
9361            }
9362            if (res == null) {
9363                res = new ArrayList<>();
9364            }
9365            res.add(pkg);
9366            try {
9367                updateSharedLibrariesLPr(pkg, changingPkg);
9368            } catch (PackageManagerException e) {
9369                // If a system app update or an app and a required lib missing we
9370                // delete the package and for updated system apps keep the data as
9371                // it is better for the user to reinstall than to be in an limbo
9372                // state. Also libs disappearing under an app should never happen
9373                // - just in case.
9374                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
9375                    final int flags = pkg.isUpdatedSystemApp()
9376                            ? PackageManager.DELETE_KEEP_DATA : 0;
9377                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9378                            flags , null, true, null);
9379                }
9380                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9381            }
9382        }
9383        return res;
9384    }
9385
9386    /**
9387     * Derive the value of the {@code cpuAbiOverride} based on the provided
9388     * value and an optional stored value from the package settings.
9389     */
9390    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
9391        String cpuAbiOverride = null;
9392
9393        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
9394            cpuAbiOverride = null;
9395        } else if (abiOverride != null) {
9396            cpuAbiOverride = abiOverride;
9397        } else if (settings != null) {
9398            cpuAbiOverride = settings.cpuAbiOverrideString;
9399        }
9400
9401        return cpuAbiOverride;
9402    }
9403
9404    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9405            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9406                    throws PackageManagerException {
9407        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9408        // If the package has children and this is the first dive in the function
9409        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9410        // whether all packages (parent and children) would be successfully scanned
9411        // before the actual scan since scanning mutates internal state and we want
9412        // to atomically install the package and its children.
9413        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9414            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9415                scanFlags |= SCAN_CHECK_ONLY;
9416            }
9417        } else {
9418            scanFlags &= ~SCAN_CHECK_ONLY;
9419        }
9420
9421        final PackageParser.Package scannedPkg;
9422        try {
9423            // Scan the parent
9424            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
9425            // Scan the children
9426            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9427            for (int i = 0; i < childCount; i++) {
9428                PackageParser.Package childPkg = pkg.childPackages.get(i);
9429                scanPackageLI(childPkg, policyFlags,
9430                        scanFlags, currentTime, user);
9431            }
9432        } finally {
9433            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9434        }
9435
9436        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9437            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
9438        }
9439
9440        return scannedPkg;
9441    }
9442
9443    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
9444            int scanFlags, long currentTime, @Nullable UserHandle user)
9445                    throws PackageManagerException {
9446        boolean success = false;
9447        try {
9448            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9449                    currentTime, user);
9450            success = true;
9451            return res;
9452        } finally {
9453            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9454                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9455                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9456                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9457                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9458            }
9459        }
9460    }
9461
9462    /**
9463     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9464     */
9465    private static boolean apkHasCode(String fileName) {
9466        StrictJarFile jarFile = null;
9467        try {
9468            jarFile = new StrictJarFile(fileName,
9469                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9470            return jarFile.findEntry("classes.dex") != null;
9471        } catch (IOException ignore) {
9472        } finally {
9473            try {
9474                if (jarFile != null) {
9475                    jarFile.close();
9476                }
9477            } catch (IOException ignore) {}
9478        }
9479        return false;
9480    }
9481
9482    /**
9483     * Enforces code policy for the package. This ensures that if an APK has
9484     * declared hasCode="true" in its manifest that the APK actually contains
9485     * code.
9486     *
9487     * @throws PackageManagerException If bytecode could not be found when it should exist
9488     */
9489    private static void assertCodePolicy(PackageParser.Package pkg)
9490            throws PackageManagerException {
9491        final boolean shouldHaveCode =
9492                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9493        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9494            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9495                    "Package " + pkg.baseCodePath + " code is missing");
9496        }
9497
9498        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9499            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9500                final boolean splitShouldHaveCode =
9501                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9502                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9503                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9504                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9505                }
9506            }
9507        }
9508    }
9509
9510    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9511            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
9512                    throws PackageManagerException {
9513        if (DEBUG_PACKAGE_SCANNING) {
9514            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9515                Log.d(TAG, "Scanning package " + pkg.packageName);
9516        }
9517
9518        applyPolicy(pkg, policyFlags);
9519
9520        assertPackageIsValid(pkg, policyFlags, scanFlags);
9521
9522        // Initialize package source and resource directories
9523        final File scanFile = new File(pkg.codePath);
9524        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9525        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9526
9527        SharedUserSetting suid = null;
9528        PackageSetting pkgSetting = null;
9529
9530        // Getting the package setting may have a side-effect, so if we
9531        // are only checking if scan would succeed, stash a copy of the
9532        // old setting to restore at the end.
9533        PackageSetting nonMutatedPs = null;
9534
9535        // We keep references to the derived CPU Abis from settings in oder to reuse
9536        // them in the case where we're not upgrading or booting for the first time.
9537        String primaryCpuAbiFromSettings = null;
9538        String secondaryCpuAbiFromSettings = null;
9539
9540        // writer
9541        synchronized (mPackages) {
9542            if (pkg.mSharedUserId != null) {
9543                // SIDE EFFECTS; may potentially allocate a new shared user
9544                suid = mSettings.getSharedUserLPw(
9545                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9546                if (DEBUG_PACKAGE_SCANNING) {
9547                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9548                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9549                                + "): packages=" + suid.packages);
9550                }
9551            }
9552
9553            // Check if we are renaming from an original package name.
9554            PackageSetting origPackage = null;
9555            String realName = null;
9556            if (pkg.mOriginalPackages != null) {
9557                // This package may need to be renamed to a previously
9558                // installed name.  Let's check on that...
9559                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9560                if (pkg.mOriginalPackages.contains(renamed)) {
9561                    // This package had originally been installed as the
9562                    // original name, and we have already taken care of
9563                    // transitioning to the new one.  Just update the new
9564                    // one to continue using the old name.
9565                    realName = pkg.mRealPackage;
9566                    if (!pkg.packageName.equals(renamed)) {
9567                        // Callers into this function may have already taken
9568                        // care of renaming the package; only do it here if
9569                        // it is not already done.
9570                        pkg.setPackageName(renamed);
9571                    }
9572                } else {
9573                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9574                        if ((origPackage = mSettings.getPackageLPr(
9575                                pkg.mOriginalPackages.get(i))) != null) {
9576                            // We do have the package already installed under its
9577                            // original name...  should we use it?
9578                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9579                                // New package is not compatible with original.
9580                                origPackage = null;
9581                                continue;
9582                            } else if (origPackage.sharedUser != null) {
9583                                // Make sure uid is compatible between packages.
9584                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9585                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9586                                            + " to " + pkg.packageName + ": old uid "
9587                                            + origPackage.sharedUser.name
9588                                            + " differs from " + pkg.mSharedUserId);
9589                                    origPackage = null;
9590                                    continue;
9591                                }
9592                                // TODO: Add case when shared user id is added [b/28144775]
9593                            } else {
9594                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9595                                        + pkg.packageName + " to old name " + origPackage.name);
9596                            }
9597                            break;
9598                        }
9599                    }
9600                }
9601            }
9602
9603            if (mTransferedPackages.contains(pkg.packageName)) {
9604                Slog.w(TAG, "Package " + pkg.packageName
9605                        + " was transferred to another, but its .apk remains");
9606            }
9607
9608            // See comments in nonMutatedPs declaration
9609            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9610                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9611                if (foundPs != null) {
9612                    nonMutatedPs = new PackageSetting(foundPs);
9613                }
9614            }
9615
9616            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9617                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9618                if (foundPs != null) {
9619                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9620                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9621                }
9622            }
9623
9624            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9625            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9626                PackageManagerService.reportSettingsProblem(Log.WARN,
9627                        "Package " + pkg.packageName + " shared user changed from "
9628                                + (pkgSetting.sharedUser != null
9629                                        ? pkgSetting.sharedUser.name : "<nothing>")
9630                                + " to "
9631                                + (suid != null ? suid.name : "<nothing>")
9632                                + "; replacing with new");
9633                pkgSetting = null;
9634            }
9635            final PackageSetting oldPkgSetting =
9636                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9637            final PackageSetting disabledPkgSetting =
9638                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9639
9640            String[] usesStaticLibraries = null;
9641            if (pkg.usesStaticLibraries != null) {
9642                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9643                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9644            }
9645
9646            if (pkgSetting == null) {
9647                final String parentPackageName = (pkg.parentPackage != null)
9648                        ? pkg.parentPackage.packageName : null;
9649                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9650                // REMOVE SharedUserSetting from method; update in a separate call
9651                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9652                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9653                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9654                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9655                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9656                        true /*allowInstall*/, instantApp, parentPackageName,
9657                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
9658                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
9659                // SIDE EFFECTS; updates system state; move elsewhere
9660                if (origPackage != null) {
9661                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9662                }
9663                mSettings.addUserToSettingLPw(pkgSetting);
9664            } else {
9665                // REMOVE SharedUserSetting from method; update in a separate call.
9666                //
9667                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9668                // secondaryCpuAbi are not known at this point so we always update them
9669                // to null here, only to reset them at a later point.
9670                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9671                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9672                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9673                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9674                        UserManagerService.getInstance(), usesStaticLibraries,
9675                        pkg.usesStaticLibrariesVersions);
9676            }
9677            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9678            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9679
9680            // SIDE EFFECTS; modifies system state; move elsewhere
9681            if (pkgSetting.origPackage != null) {
9682                // If we are first transitioning from an original package,
9683                // fix up the new package's name now.  We need to do this after
9684                // looking up the package under its new name, so getPackageLP
9685                // can take care of fiddling things correctly.
9686                pkg.setPackageName(origPackage.name);
9687
9688                // File a report about this.
9689                String msg = "New package " + pkgSetting.realName
9690                        + " renamed to replace old package " + pkgSetting.name;
9691                reportSettingsProblem(Log.WARN, msg);
9692
9693                // Make a note of it.
9694                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9695                    mTransferedPackages.add(origPackage.name);
9696                }
9697
9698                // No longer need to retain this.
9699                pkgSetting.origPackage = null;
9700            }
9701
9702            // SIDE EFFECTS; modifies system state; move elsewhere
9703            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9704                // Make a note of it.
9705                mTransferedPackages.add(pkg.packageName);
9706            }
9707
9708            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9709                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9710            }
9711
9712            if ((scanFlags & SCAN_BOOTING) == 0
9713                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9714                // Check all shared libraries and map to their actual file path.
9715                // We only do this here for apps not on a system dir, because those
9716                // are the only ones that can fail an install due to this.  We
9717                // will take care of the system apps by updating all of their
9718                // library paths after the scan is done. Also during the initial
9719                // scan don't update any libs as we do this wholesale after all
9720                // apps are scanned to avoid dependency based scanning.
9721                updateSharedLibrariesLPr(pkg, null);
9722            }
9723
9724            if (mFoundPolicyFile) {
9725                SELinuxMMAC.assignSeInfoValue(pkg);
9726            }
9727            pkg.applicationInfo.uid = pkgSetting.appId;
9728            pkg.mExtras = pkgSetting;
9729
9730
9731            // Static shared libs have same package with different versions where
9732            // we internally use a synthetic package name to allow multiple versions
9733            // of the same package, therefore we need to compare signatures against
9734            // the package setting for the latest library version.
9735            PackageSetting signatureCheckPs = pkgSetting;
9736            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9737                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9738                if (libraryEntry != null) {
9739                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9740                }
9741            }
9742
9743            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9744                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9745                    // We just determined the app is signed correctly, so bring
9746                    // over the latest parsed certs.
9747                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9748                } else {
9749                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9750                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9751                                "Package " + pkg.packageName + " upgrade keys do not match the "
9752                                + "previously installed version");
9753                    } else {
9754                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9755                        String msg = "System package " + pkg.packageName
9756                                + " signature changed; retaining data.";
9757                        reportSettingsProblem(Log.WARN, msg);
9758                    }
9759                }
9760            } else {
9761                try {
9762                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9763                    verifySignaturesLP(signatureCheckPs, pkg);
9764                    // We just determined the app is signed correctly, so bring
9765                    // over the latest parsed certs.
9766                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9767                } catch (PackageManagerException e) {
9768                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9769                        throw e;
9770                    }
9771                    // The signature has changed, but this package is in the system
9772                    // image...  let's recover!
9773                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9774                    // However...  if this package is part of a shared user, but it
9775                    // doesn't match the signature of the shared user, let's fail.
9776                    // What this means is that you can't change the signatures
9777                    // associated with an overall shared user, which doesn't seem all
9778                    // that unreasonable.
9779                    if (signatureCheckPs.sharedUser != null) {
9780                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9781                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9782                            throw new PackageManagerException(
9783                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9784                                    "Signature mismatch for shared user: "
9785                                            + pkgSetting.sharedUser);
9786                        }
9787                    }
9788                    // File a report about this.
9789                    String msg = "System package " + pkg.packageName
9790                            + " signature changed; retaining data.";
9791                    reportSettingsProblem(Log.WARN, msg);
9792                }
9793            }
9794
9795            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9796                // This package wants to adopt ownership of permissions from
9797                // another package.
9798                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9799                    final String origName = pkg.mAdoptPermissions.get(i);
9800                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9801                    if (orig != null) {
9802                        if (verifyPackageUpdateLPr(orig, pkg)) {
9803                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9804                                    + pkg.packageName);
9805                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9806                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9807                        }
9808                    }
9809                }
9810            }
9811        }
9812
9813        pkg.applicationInfo.processName = fixProcessName(
9814                pkg.applicationInfo.packageName,
9815                pkg.applicationInfo.processName);
9816
9817        if (pkg != mPlatformPackage) {
9818            // Get all of our default paths setup
9819            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9820        }
9821
9822        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9823
9824        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9825            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9826                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9827                derivePackageAbi(
9828                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9829                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9830
9831                // Some system apps still use directory structure for native libraries
9832                // in which case we might end up not detecting abi solely based on apk
9833                // structure. Try to detect abi based on directory structure.
9834                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9835                        pkg.applicationInfo.primaryCpuAbi == null) {
9836                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9837                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9838                }
9839            } else {
9840                // This is not a first boot or an upgrade, don't bother deriving the
9841                // ABI during the scan. Instead, trust the value that was stored in the
9842                // package setting.
9843                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9844                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9845
9846                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9847
9848                if (DEBUG_ABI_SELECTION) {
9849                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9850                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9851                        pkg.applicationInfo.secondaryCpuAbi);
9852                }
9853            }
9854        } else {
9855            if ((scanFlags & SCAN_MOVE) != 0) {
9856                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9857                // but we already have this packages package info in the PackageSetting. We just
9858                // use that and derive the native library path based on the new codepath.
9859                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9860                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9861            }
9862
9863            // Set native library paths again. For moves, the path will be updated based on the
9864            // ABIs we've determined above. For non-moves, the path will be updated based on the
9865            // ABIs we determined during compilation, but the path will depend on the final
9866            // package path (after the rename away from the stage path).
9867            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9868        }
9869
9870        // This is a special case for the "system" package, where the ABI is
9871        // dictated by the zygote configuration (and init.rc). We should keep track
9872        // of this ABI so that we can deal with "normal" applications that run under
9873        // the same UID correctly.
9874        if (mPlatformPackage == pkg) {
9875            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9876                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9877        }
9878
9879        // If there's a mismatch between the abi-override in the package setting
9880        // and the abiOverride specified for the install. Warn about this because we
9881        // would've already compiled the app without taking the package setting into
9882        // account.
9883        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9884            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9885                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9886                        " for package " + pkg.packageName);
9887            }
9888        }
9889
9890        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9891        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9892        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9893
9894        // Copy the derived override back to the parsed package, so that we can
9895        // update the package settings accordingly.
9896        pkg.cpuAbiOverride = cpuAbiOverride;
9897
9898        if (DEBUG_ABI_SELECTION) {
9899            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9900                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9901                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9902        }
9903
9904        // Push the derived path down into PackageSettings so we know what to
9905        // clean up at uninstall time.
9906        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9907
9908        if (DEBUG_ABI_SELECTION) {
9909            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9910                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9911                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9912        }
9913
9914        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9915        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9916            // We don't do this here during boot because we can do it all
9917            // at once after scanning all existing packages.
9918            //
9919            // We also do this *before* we perform dexopt on this package, so that
9920            // we can avoid redundant dexopts, and also to make sure we've got the
9921            // code and package path correct.
9922            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9923        }
9924
9925        if (mFactoryTest && pkg.requestedPermissions.contains(
9926                android.Manifest.permission.FACTORY_TEST)) {
9927            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9928        }
9929
9930        if (isSystemApp(pkg)) {
9931            pkgSetting.isOrphaned = true;
9932        }
9933
9934        // Take care of first install / last update times.
9935        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9936        if (currentTime != 0) {
9937            if (pkgSetting.firstInstallTime == 0) {
9938                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9939            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9940                pkgSetting.lastUpdateTime = currentTime;
9941            }
9942        } else if (pkgSetting.firstInstallTime == 0) {
9943            // We need *something*.  Take time time stamp of the file.
9944            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9945        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9946            if (scanFileTime != pkgSetting.timeStamp) {
9947                // A package on the system image has changed; consider this
9948                // to be an update.
9949                pkgSetting.lastUpdateTime = scanFileTime;
9950            }
9951        }
9952        pkgSetting.setTimeStamp(scanFileTime);
9953
9954        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9955            if (nonMutatedPs != null) {
9956                synchronized (mPackages) {
9957                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9958                }
9959            }
9960        } else {
9961            final int userId = user == null ? 0 : user.getIdentifier();
9962            // Modify state for the given package setting
9963            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9964                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9965            if (pkgSetting.getInstantApp(userId)) {
9966                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9967            }
9968        }
9969        return pkg;
9970    }
9971
9972    /**
9973     * Applies policy to the parsed package based upon the given policy flags.
9974     * Ensures the package is in a good state.
9975     * <p>
9976     * Implementation detail: This method must NOT have any side effect. It would
9977     * ideally be static, but, it requires locks to read system state.
9978     */
9979    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9980        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9981            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9982            if (pkg.applicationInfo.isDirectBootAware()) {
9983                // we're direct boot aware; set for all components
9984                for (PackageParser.Service s : pkg.services) {
9985                    s.info.encryptionAware = s.info.directBootAware = true;
9986                }
9987                for (PackageParser.Provider p : pkg.providers) {
9988                    p.info.encryptionAware = p.info.directBootAware = true;
9989                }
9990                for (PackageParser.Activity a : pkg.activities) {
9991                    a.info.encryptionAware = a.info.directBootAware = true;
9992                }
9993                for (PackageParser.Activity r : pkg.receivers) {
9994                    r.info.encryptionAware = r.info.directBootAware = true;
9995                }
9996            }
9997        } else {
9998            // Only allow system apps to be flagged as core apps.
9999            pkg.coreApp = false;
10000            // clear flags not applicable to regular apps
10001            pkg.applicationInfo.privateFlags &=
10002                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10003            pkg.applicationInfo.privateFlags &=
10004                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10005        }
10006        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10007
10008        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10009            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10010        }
10011
10012        if (!isSystemApp(pkg)) {
10013            // Only system apps can use these features.
10014            pkg.mOriginalPackages = null;
10015            pkg.mRealPackage = null;
10016            pkg.mAdoptPermissions = null;
10017        }
10018    }
10019
10020    /**
10021     * Asserts the parsed package is valid according to the given policy. If the
10022     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10023     * <p>
10024     * Implementation detail: This method must NOT have any side effects. It would
10025     * ideally be static, but, it requires locks to read system state.
10026     *
10027     * @throws PackageManagerException If the package fails any of the validation checks
10028     */
10029    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10030            throws PackageManagerException {
10031        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10032            assertCodePolicy(pkg);
10033        }
10034
10035        if (pkg.applicationInfo.getCodePath() == null ||
10036                pkg.applicationInfo.getResourcePath() == null) {
10037            // Bail out. The resource and code paths haven't been set.
10038            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10039                    "Code and resource paths haven't been set correctly");
10040        }
10041
10042        // Make sure we're not adding any bogus keyset info
10043        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10044        ksms.assertScannedPackageValid(pkg);
10045
10046        synchronized (mPackages) {
10047            // The special "android" package can only be defined once
10048            if (pkg.packageName.equals("android")) {
10049                if (mAndroidApplication != null) {
10050                    Slog.w(TAG, "*************************************************");
10051                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10052                    Slog.w(TAG, " codePath=" + pkg.codePath);
10053                    Slog.w(TAG, "*************************************************");
10054                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10055                            "Core android package being redefined.  Skipping.");
10056                }
10057            }
10058
10059            // A package name must be unique; don't allow duplicates
10060            if (mPackages.containsKey(pkg.packageName)) {
10061                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10062                        "Application package " + pkg.packageName
10063                        + " already installed.  Skipping duplicate.");
10064            }
10065
10066            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10067                // Static libs have a synthetic package name containing the version
10068                // but we still want the base name to be unique.
10069                if (mPackages.containsKey(pkg.manifestPackageName)) {
10070                    throw new PackageManagerException(
10071                            "Duplicate static shared lib provider package");
10072                }
10073
10074                // Static shared libraries should have at least O target SDK
10075                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10076                    throw new PackageManagerException(
10077                            "Packages declaring static-shared libs must target O SDK or higher");
10078                }
10079
10080                // Package declaring static a shared lib cannot be instant apps
10081                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10082                    throw new PackageManagerException(
10083                            "Packages declaring static-shared libs cannot be instant apps");
10084                }
10085
10086                // Package declaring static a shared lib cannot be renamed since the package
10087                // name is synthetic and apps can't code around package manager internals.
10088                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10089                    throw new PackageManagerException(
10090                            "Packages declaring static-shared libs cannot be renamed");
10091                }
10092
10093                // Package declaring static a shared lib cannot declare child packages
10094                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10095                    throw new PackageManagerException(
10096                            "Packages declaring static-shared libs cannot have child packages");
10097                }
10098
10099                // Package declaring static a shared lib cannot declare dynamic libs
10100                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10101                    throw new PackageManagerException(
10102                            "Packages declaring static-shared libs cannot declare dynamic libs");
10103                }
10104
10105                // Package declaring static a shared lib cannot declare shared users
10106                if (pkg.mSharedUserId != null) {
10107                    throw new PackageManagerException(
10108                            "Packages declaring static-shared libs cannot declare shared users");
10109                }
10110
10111                // Static shared libs cannot declare activities
10112                if (!pkg.activities.isEmpty()) {
10113                    throw new PackageManagerException(
10114                            "Static shared libs cannot declare activities");
10115                }
10116
10117                // Static shared libs cannot declare services
10118                if (!pkg.services.isEmpty()) {
10119                    throw new PackageManagerException(
10120                            "Static shared libs cannot declare services");
10121                }
10122
10123                // Static shared libs cannot declare providers
10124                if (!pkg.providers.isEmpty()) {
10125                    throw new PackageManagerException(
10126                            "Static shared libs cannot declare content providers");
10127                }
10128
10129                // Static shared libs cannot declare receivers
10130                if (!pkg.receivers.isEmpty()) {
10131                    throw new PackageManagerException(
10132                            "Static shared libs cannot declare broadcast receivers");
10133                }
10134
10135                // Static shared libs cannot declare permission groups
10136                if (!pkg.permissionGroups.isEmpty()) {
10137                    throw new PackageManagerException(
10138                            "Static shared libs cannot declare permission groups");
10139                }
10140
10141                // Static shared libs cannot declare permissions
10142                if (!pkg.permissions.isEmpty()) {
10143                    throw new PackageManagerException(
10144                            "Static shared libs cannot declare permissions");
10145                }
10146
10147                // Static shared libs cannot declare protected broadcasts
10148                if (pkg.protectedBroadcasts != null) {
10149                    throw new PackageManagerException(
10150                            "Static shared libs cannot declare protected broadcasts");
10151                }
10152
10153                // Static shared libs cannot be overlay targets
10154                if (pkg.mOverlayTarget != null) {
10155                    throw new PackageManagerException(
10156                            "Static shared libs cannot be overlay targets");
10157                }
10158
10159                // The version codes must be ordered as lib versions
10160                int minVersionCode = Integer.MIN_VALUE;
10161                int maxVersionCode = Integer.MAX_VALUE;
10162
10163                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10164                        pkg.staticSharedLibName);
10165                if (versionedLib != null) {
10166                    final int versionCount = versionedLib.size();
10167                    for (int i = 0; i < versionCount; i++) {
10168                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10169                        // TODO: We will change version code to long, so in the new API it is long
10170                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
10171                                .getVersionCode();
10172                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10173                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10174                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10175                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10176                        } else {
10177                            minVersionCode = maxVersionCode = libVersionCode;
10178                            break;
10179                        }
10180                    }
10181                }
10182                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10183                    throw new PackageManagerException("Static shared"
10184                            + " lib version codes must be ordered as lib versions");
10185                }
10186            }
10187
10188            // Only privileged apps and updated privileged apps can add child packages.
10189            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10190                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10191                    throw new PackageManagerException("Only privileged apps can add child "
10192                            + "packages. Ignoring package " + pkg.packageName);
10193                }
10194                final int childCount = pkg.childPackages.size();
10195                for (int i = 0; i < childCount; i++) {
10196                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10197                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10198                            childPkg.packageName)) {
10199                        throw new PackageManagerException("Can't override child of "
10200                                + "another disabled app. Ignoring package " + pkg.packageName);
10201                    }
10202                }
10203            }
10204
10205            // If we're only installing presumed-existing packages, require that the
10206            // scanned APK is both already known and at the path previously established
10207            // for it.  Previously unknown packages we pick up normally, but if we have an
10208            // a priori expectation about this package's install presence, enforce it.
10209            // With a singular exception for new system packages. When an OTA contains
10210            // a new system package, we allow the codepath to change from a system location
10211            // to the user-installed location. If we don't allow this change, any newer,
10212            // user-installed version of the application will be ignored.
10213            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10214                if (mExpectingBetter.containsKey(pkg.packageName)) {
10215                    logCriticalInfo(Log.WARN,
10216                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10217                } else {
10218                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10219                    if (known != null) {
10220                        if (DEBUG_PACKAGE_SCANNING) {
10221                            Log.d(TAG, "Examining " + pkg.codePath
10222                                    + " and requiring known paths " + known.codePathString
10223                                    + " & " + known.resourcePathString);
10224                        }
10225                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10226                                || !pkg.applicationInfo.getResourcePath().equals(
10227                                        known.resourcePathString)) {
10228                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10229                                    "Application package " + pkg.packageName
10230                                    + " found at " + pkg.applicationInfo.getCodePath()
10231                                    + " but expected at " + known.codePathString
10232                                    + "; ignoring.");
10233                        }
10234                    }
10235                }
10236            }
10237
10238            // Verify that this new package doesn't have any content providers
10239            // that conflict with existing packages.  Only do this if the
10240            // package isn't already installed, since we don't want to break
10241            // things that are installed.
10242            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10243                final int N = pkg.providers.size();
10244                int i;
10245                for (i=0; i<N; i++) {
10246                    PackageParser.Provider p = pkg.providers.get(i);
10247                    if (p.info.authority != null) {
10248                        String names[] = p.info.authority.split(";");
10249                        for (int j = 0; j < names.length; j++) {
10250                            if (mProvidersByAuthority.containsKey(names[j])) {
10251                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10252                                final String otherPackageName =
10253                                        ((other != null && other.getComponentName() != null) ?
10254                                                other.getComponentName().getPackageName() : "?");
10255                                throw new PackageManagerException(
10256                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10257                                        "Can't install because provider name " + names[j]
10258                                                + " (in package " + pkg.applicationInfo.packageName
10259                                                + ") is already used by " + otherPackageName);
10260                            }
10261                        }
10262                    }
10263                }
10264            }
10265        }
10266    }
10267
10268    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10269            int type, String declaringPackageName, int declaringVersionCode) {
10270        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10271        if (versionedLib == null) {
10272            versionedLib = new SparseArray<>();
10273            mSharedLibraries.put(name, versionedLib);
10274            if (type == SharedLibraryInfo.TYPE_STATIC) {
10275                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10276            }
10277        } else if (versionedLib.indexOfKey(version) >= 0) {
10278            return false;
10279        }
10280        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10281                version, type, declaringPackageName, declaringVersionCode);
10282        versionedLib.put(version, libEntry);
10283        return true;
10284    }
10285
10286    private boolean removeSharedLibraryLPw(String name, int version) {
10287        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10288        if (versionedLib == null) {
10289            return false;
10290        }
10291        final int libIdx = versionedLib.indexOfKey(version);
10292        if (libIdx < 0) {
10293            return false;
10294        }
10295        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10296        versionedLib.remove(version);
10297        if (versionedLib.size() <= 0) {
10298            mSharedLibraries.remove(name);
10299            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10300                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10301                        .getPackageName());
10302            }
10303        }
10304        return true;
10305    }
10306
10307    /**
10308     * Adds a scanned package to the system. When this method is finished, the package will
10309     * be available for query, resolution, etc...
10310     */
10311    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10312            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
10313        final String pkgName = pkg.packageName;
10314        if (mCustomResolverComponentName != null &&
10315                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10316            setUpCustomResolverActivity(pkg);
10317        }
10318
10319        if (pkg.packageName.equals("android")) {
10320            synchronized (mPackages) {
10321                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10322                    // Set up information for our fall-back user intent resolution activity.
10323                    mPlatformPackage = pkg;
10324                    pkg.mVersionCode = mSdkVersion;
10325                    mAndroidApplication = pkg.applicationInfo;
10326                    if (!mResolverReplaced) {
10327                        mResolveActivity.applicationInfo = mAndroidApplication;
10328                        mResolveActivity.name = ResolverActivity.class.getName();
10329                        mResolveActivity.packageName = mAndroidApplication.packageName;
10330                        mResolveActivity.processName = "system:ui";
10331                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10332                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10333                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10334                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
10335                        mResolveActivity.exported = true;
10336                        mResolveActivity.enabled = true;
10337                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
10338                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
10339                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
10340                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
10341                                | ActivityInfo.CONFIG_ORIENTATION
10342                                | ActivityInfo.CONFIG_KEYBOARD
10343                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
10344                        mResolveInfo.activityInfo = mResolveActivity;
10345                        mResolveInfo.priority = 0;
10346                        mResolveInfo.preferredOrder = 0;
10347                        mResolveInfo.match = 0;
10348                        mResolveComponentName = new ComponentName(
10349                                mAndroidApplication.packageName, mResolveActivity.name);
10350                    }
10351                }
10352            }
10353        }
10354
10355        ArrayList<PackageParser.Package> clientLibPkgs = null;
10356        // writer
10357        synchronized (mPackages) {
10358            boolean hasStaticSharedLibs = false;
10359
10360            // Any app can add new static shared libraries
10361            if (pkg.staticSharedLibName != null) {
10362                // Static shared libs don't allow renaming as they have synthetic package
10363                // names to allow install of multiple versions, so use name from manifest.
10364                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10365                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10366                        pkg.manifestPackageName, pkg.mVersionCode)) {
10367                    hasStaticSharedLibs = true;
10368                } else {
10369                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10370                                + pkg.staticSharedLibName + " already exists; skipping");
10371                }
10372                // Static shared libs cannot be updated once installed since they
10373                // use synthetic package name which includes the version code, so
10374                // not need to update other packages's shared lib dependencies.
10375            }
10376
10377            if (!hasStaticSharedLibs
10378                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10379                // Only system apps can add new dynamic shared libraries.
10380                if (pkg.libraryNames != null) {
10381                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10382                        String name = pkg.libraryNames.get(i);
10383                        boolean allowed = false;
10384                        if (pkg.isUpdatedSystemApp()) {
10385                            // New library entries can only be added through the
10386                            // system image.  This is important to get rid of a lot
10387                            // of nasty edge cases: for example if we allowed a non-
10388                            // system update of the app to add a library, then uninstalling
10389                            // the update would make the library go away, and assumptions
10390                            // we made such as through app install filtering would now
10391                            // have allowed apps on the device which aren't compatible
10392                            // with it.  Better to just have the restriction here, be
10393                            // conservative, and create many fewer cases that can negatively
10394                            // impact the user experience.
10395                            final PackageSetting sysPs = mSettings
10396                                    .getDisabledSystemPkgLPr(pkg.packageName);
10397                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
10398                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
10399                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
10400                                        allowed = true;
10401                                        break;
10402                                    }
10403                                }
10404                            }
10405                        } else {
10406                            allowed = true;
10407                        }
10408                        if (allowed) {
10409                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10410                                    SharedLibraryInfo.VERSION_UNDEFINED,
10411                                    SharedLibraryInfo.TYPE_DYNAMIC,
10412                                    pkg.packageName, pkg.mVersionCode)) {
10413                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10414                                        + name + " already exists; skipping");
10415                            }
10416                        } else {
10417                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10418                                    + name + " that is not declared on system image; skipping");
10419                        }
10420                    }
10421
10422                    if ((scanFlags & SCAN_BOOTING) == 0) {
10423                        // If we are not booting, we need to update any applications
10424                        // that are clients of our shared library.  If we are booting,
10425                        // this will all be done once the scan is complete.
10426                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10427                    }
10428                }
10429            }
10430        }
10431
10432        if ((scanFlags & SCAN_BOOTING) != 0) {
10433            // No apps can run during boot scan, so they don't need to be frozen
10434        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10435            // Caller asked to not kill app, so it's probably not frozen
10436        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10437            // Caller asked us to ignore frozen check for some reason; they
10438            // probably didn't know the package name
10439        } else {
10440            // We're doing major surgery on this package, so it better be frozen
10441            // right now to keep it from launching
10442            checkPackageFrozen(pkgName);
10443        }
10444
10445        // Also need to kill any apps that are dependent on the library.
10446        if (clientLibPkgs != null) {
10447            for (int i=0; i<clientLibPkgs.size(); i++) {
10448                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10449                killApplication(clientPkg.applicationInfo.packageName,
10450                        clientPkg.applicationInfo.uid, "update lib");
10451            }
10452        }
10453
10454        // writer
10455        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10456
10457        synchronized (mPackages) {
10458            // We don't expect installation to fail beyond this point
10459
10460            // Add the new setting to mSettings
10461            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10462            // Add the new setting to mPackages
10463            mPackages.put(pkg.applicationInfo.packageName, pkg);
10464            // Make sure we don't accidentally delete its data.
10465            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10466            while (iter.hasNext()) {
10467                PackageCleanItem item = iter.next();
10468                if (pkgName.equals(item.packageName)) {
10469                    iter.remove();
10470                }
10471            }
10472
10473            // Add the package's KeySets to the global KeySetManagerService
10474            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10475            ksms.addScannedPackageLPw(pkg);
10476
10477            int N = pkg.providers.size();
10478            StringBuilder r = null;
10479            int i;
10480            for (i=0; i<N; i++) {
10481                PackageParser.Provider p = pkg.providers.get(i);
10482                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10483                        p.info.processName);
10484                mProviders.addProvider(p);
10485                p.syncable = p.info.isSyncable;
10486                if (p.info.authority != null) {
10487                    String names[] = p.info.authority.split(";");
10488                    p.info.authority = null;
10489                    for (int j = 0; j < names.length; j++) {
10490                        if (j == 1 && p.syncable) {
10491                            // We only want the first authority for a provider to possibly be
10492                            // syncable, so if we already added this provider using a different
10493                            // authority clear the syncable flag. We copy the provider before
10494                            // changing it because the mProviders object contains a reference
10495                            // to a provider that we don't want to change.
10496                            // Only do this for the second authority since the resulting provider
10497                            // object can be the same for all future authorities for this provider.
10498                            p = new PackageParser.Provider(p);
10499                            p.syncable = false;
10500                        }
10501                        if (!mProvidersByAuthority.containsKey(names[j])) {
10502                            mProvidersByAuthority.put(names[j], p);
10503                            if (p.info.authority == null) {
10504                                p.info.authority = names[j];
10505                            } else {
10506                                p.info.authority = p.info.authority + ";" + names[j];
10507                            }
10508                            if (DEBUG_PACKAGE_SCANNING) {
10509                                if (chatty)
10510                                    Log.d(TAG, "Registered content provider: " + names[j]
10511                                            + ", className = " + p.info.name + ", isSyncable = "
10512                                            + p.info.isSyncable);
10513                            }
10514                        } else {
10515                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10516                            Slog.w(TAG, "Skipping provider name " + names[j] +
10517                                    " (in package " + pkg.applicationInfo.packageName +
10518                                    "): name already used by "
10519                                    + ((other != null && other.getComponentName() != null)
10520                                            ? other.getComponentName().getPackageName() : "?"));
10521                        }
10522                    }
10523                }
10524                if (chatty) {
10525                    if (r == null) {
10526                        r = new StringBuilder(256);
10527                    } else {
10528                        r.append(' ');
10529                    }
10530                    r.append(p.info.name);
10531                }
10532            }
10533            if (r != null) {
10534                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10535            }
10536
10537            N = pkg.services.size();
10538            r = null;
10539            for (i=0; i<N; i++) {
10540                PackageParser.Service s = pkg.services.get(i);
10541                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10542                        s.info.processName);
10543                mServices.addService(s);
10544                if (chatty) {
10545                    if (r == null) {
10546                        r = new StringBuilder(256);
10547                    } else {
10548                        r.append(' ');
10549                    }
10550                    r.append(s.info.name);
10551                }
10552            }
10553            if (r != null) {
10554                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10555            }
10556
10557            N = pkg.receivers.size();
10558            r = null;
10559            for (i=0; i<N; i++) {
10560                PackageParser.Activity a = pkg.receivers.get(i);
10561                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10562                        a.info.processName);
10563                mReceivers.addActivity(a, "receiver");
10564                if (chatty) {
10565                    if (r == null) {
10566                        r = new StringBuilder(256);
10567                    } else {
10568                        r.append(' ');
10569                    }
10570                    r.append(a.info.name);
10571                }
10572            }
10573            if (r != null) {
10574                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10575            }
10576
10577            N = pkg.activities.size();
10578            r = null;
10579            for (i=0; i<N; i++) {
10580                PackageParser.Activity a = pkg.activities.get(i);
10581                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10582                        a.info.processName);
10583                mActivities.addActivity(a, "activity");
10584                if (chatty) {
10585                    if (r == null) {
10586                        r = new StringBuilder(256);
10587                    } else {
10588                        r.append(' ');
10589                    }
10590                    r.append(a.info.name);
10591                }
10592            }
10593            if (r != null) {
10594                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10595            }
10596
10597            N = pkg.permissionGroups.size();
10598            r = null;
10599            for (i=0; i<N; i++) {
10600                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10601                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10602                final String curPackageName = cur == null ? null : cur.info.packageName;
10603                // Dont allow ephemeral apps to define new permission groups.
10604                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10605                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10606                            + pg.info.packageName
10607                            + " ignored: instant apps cannot define new permission groups.");
10608                    continue;
10609                }
10610                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10611                if (cur == null || isPackageUpdate) {
10612                    mPermissionGroups.put(pg.info.name, pg);
10613                    if (chatty) {
10614                        if (r == null) {
10615                            r = new StringBuilder(256);
10616                        } else {
10617                            r.append(' ');
10618                        }
10619                        if (isPackageUpdate) {
10620                            r.append("UPD:");
10621                        }
10622                        r.append(pg.info.name);
10623                    }
10624                } else {
10625                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10626                            + pg.info.packageName + " ignored: original from "
10627                            + cur.info.packageName);
10628                    if (chatty) {
10629                        if (r == null) {
10630                            r = new StringBuilder(256);
10631                        } else {
10632                            r.append(' ');
10633                        }
10634                        r.append("DUP:");
10635                        r.append(pg.info.name);
10636                    }
10637                }
10638            }
10639            if (r != null) {
10640                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10641            }
10642
10643            N = pkg.permissions.size();
10644            r = null;
10645            for (i=0; i<N; i++) {
10646                PackageParser.Permission p = pkg.permissions.get(i);
10647
10648                // Dont allow ephemeral apps to define new permissions.
10649                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10650                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10651                            + p.info.packageName
10652                            + " ignored: instant apps cannot define new permissions.");
10653                    continue;
10654                }
10655
10656                // Assume by default that we did not install this permission into the system.
10657                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10658
10659                // Now that permission groups have a special meaning, we ignore permission
10660                // groups for legacy apps to prevent unexpected behavior. In particular,
10661                // permissions for one app being granted to someone just becase they happen
10662                // to be in a group defined by another app (before this had no implications).
10663                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10664                    p.group = mPermissionGroups.get(p.info.group);
10665                    // Warn for a permission in an unknown group.
10666                    if (p.info.group != null && p.group == null) {
10667                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10668                                + p.info.packageName + " in an unknown group " + p.info.group);
10669                    }
10670                }
10671
10672                ArrayMap<String, BasePermission> permissionMap =
10673                        p.tree ? mSettings.mPermissionTrees
10674                                : mSettings.mPermissions;
10675                BasePermission bp = permissionMap.get(p.info.name);
10676
10677                // Allow system apps to redefine non-system permissions
10678                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10679                    final boolean currentOwnerIsSystem = (bp.perm != null
10680                            && isSystemApp(bp.perm.owner));
10681                    if (isSystemApp(p.owner)) {
10682                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10683                            // It's a built-in permission and no owner, take ownership now
10684                            bp.packageSetting = pkgSetting;
10685                            bp.perm = p;
10686                            bp.uid = pkg.applicationInfo.uid;
10687                            bp.sourcePackage = p.info.packageName;
10688                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10689                        } else if (!currentOwnerIsSystem) {
10690                            String msg = "New decl " + p.owner + " of permission  "
10691                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10692                            reportSettingsProblem(Log.WARN, msg);
10693                            bp = null;
10694                        }
10695                    }
10696                }
10697
10698                if (bp == null) {
10699                    bp = new BasePermission(p.info.name, p.info.packageName,
10700                            BasePermission.TYPE_NORMAL);
10701                    permissionMap.put(p.info.name, bp);
10702                }
10703
10704                if (bp.perm == null) {
10705                    if (bp.sourcePackage == null
10706                            || bp.sourcePackage.equals(p.info.packageName)) {
10707                        BasePermission tree = findPermissionTreeLP(p.info.name);
10708                        if (tree == null
10709                                || tree.sourcePackage.equals(p.info.packageName)) {
10710                            bp.packageSetting = pkgSetting;
10711                            bp.perm = p;
10712                            bp.uid = pkg.applicationInfo.uid;
10713                            bp.sourcePackage = p.info.packageName;
10714                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10715                            if (chatty) {
10716                                if (r == null) {
10717                                    r = new StringBuilder(256);
10718                                } else {
10719                                    r.append(' ');
10720                                }
10721                                r.append(p.info.name);
10722                            }
10723                        } else {
10724                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10725                                    + p.info.packageName + " ignored: base tree "
10726                                    + tree.name + " is from package "
10727                                    + tree.sourcePackage);
10728                        }
10729                    } else {
10730                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10731                                + p.info.packageName + " ignored: original from "
10732                                + bp.sourcePackage);
10733                    }
10734                } else if (chatty) {
10735                    if (r == null) {
10736                        r = new StringBuilder(256);
10737                    } else {
10738                        r.append(' ');
10739                    }
10740                    r.append("DUP:");
10741                    r.append(p.info.name);
10742                }
10743                if (bp.perm == p) {
10744                    bp.protectionLevel = p.info.protectionLevel;
10745                }
10746            }
10747
10748            if (r != null) {
10749                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10750            }
10751
10752            N = pkg.instrumentation.size();
10753            r = null;
10754            for (i=0; i<N; i++) {
10755                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10756                a.info.packageName = pkg.applicationInfo.packageName;
10757                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10758                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10759                a.info.splitNames = pkg.splitNames;
10760                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10761                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10762                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10763                a.info.dataDir = pkg.applicationInfo.dataDir;
10764                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10765                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10766                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10767                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10768                mInstrumentation.put(a.getComponentName(), a);
10769                if (chatty) {
10770                    if (r == null) {
10771                        r = new StringBuilder(256);
10772                    } else {
10773                        r.append(' ');
10774                    }
10775                    r.append(a.info.name);
10776                }
10777            }
10778            if (r != null) {
10779                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10780            }
10781
10782            if (pkg.protectedBroadcasts != null) {
10783                N = pkg.protectedBroadcasts.size();
10784                for (i=0; i<N; i++) {
10785                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10786                }
10787            }
10788        }
10789
10790        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10791    }
10792
10793    /**
10794     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10795     * is derived purely on the basis of the contents of {@code scanFile} and
10796     * {@code cpuAbiOverride}.
10797     *
10798     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10799     */
10800    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10801                                 String cpuAbiOverride, boolean extractLibs,
10802                                 File appLib32InstallDir)
10803            throws PackageManagerException {
10804        // Give ourselves some initial paths; we'll come back for another
10805        // pass once we've determined ABI below.
10806        setNativeLibraryPaths(pkg, appLib32InstallDir);
10807
10808        // We would never need to extract libs for forward-locked and external packages,
10809        // since the container service will do it for us. We shouldn't attempt to
10810        // extract libs from system app when it was not updated.
10811        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10812                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10813            extractLibs = false;
10814        }
10815
10816        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10817        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10818
10819        NativeLibraryHelper.Handle handle = null;
10820        try {
10821            handle = NativeLibraryHelper.Handle.create(pkg);
10822            // TODO(multiArch): This can be null for apps that didn't go through the
10823            // usual installation process. We can calculate it again, like we
10824            // do during install time.
10825            //
10826            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10827            // unnecessary.
10828            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10829
10830            // Null out the abis so that they can be recalculated.
10831            pkg.applicationInfo.primaryCpuAbi = null;
10832            pkg.applicationInfo.secondaryCpuAbi = null;
10833            if (isMultiArch(pkg.applicationInfo)) {
10834                // Warn if we've set an abiOverride for multi-lib packages..
10835                // By definition, we need to copy both 32 and 64 bit libraries for
10836                // such packages.
10837                if (pkg.cpuAbiOverride != null
10838                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10839                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10840                }
10841
10842                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10843                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10844                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10845                    if (extractLibs) {
10846                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10847                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10848                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10849                                useIsaSpecificSubdirs);
10850                    } else {
10851                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10852                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10853                    }
10854                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10855                }
10856
10857                maybeThrowExceptionForMultiArchCopy(
10858                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10859
10860                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10861                    if (extractLibs) {
10862                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10863                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10864                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10865                                useIsaSpecificSubdirs);
10866                    } else {
10867                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10868                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10869                    }
10870                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10871                }
10872
10873                maybeThrowExceptionForMultiArchCopy(
10874                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10875
10876                if (abi64 >= 0) {
10877                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10878                }
10879
10880                if (abi32 >= 0) {
10881                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10882                    if (abi64 >= 0) {
10883                        if (pkg.use32bitAbi) {
10884                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10885                            pkg.applicationInfo.primaryCpuAbi = abi;
10886                        } else {
10887                            pkg.applicationInfo.secondaryCpuAbi = abi;
10888                        }
10889                    } else {
10890                        pkg.applicationInfo.primaryCpuAbi = abi;
10891                    }
10892                }
10893
10894            } else {
10895                String[] abiList = (cpuAbiOverride != null) ?
10896                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10897
10898                // Enable gross and lame hacks for apps that are built with old
10899                // SDK tools. We must scan their APKs for renderscript bitcode and
10900                // not launch them if it's present. Don't bother checking on devices
10901                // that don't have 64 bit support.
10902                boolean needsRenderScriptOverride = false;
10903                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10904                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10905                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10906                    needsRenderScriptOverride = true;
10907                }
10908
10909                final int copyRet;
10910                if (extractLibs) {
10911                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10912                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10913                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10914                } else {
10915                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10916                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10917                }
10918                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10919
10920                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10921                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10922                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10923                }
10924
10925                if (copyRet >= 0) {
10926                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10927                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10928                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10929                } else if (needsRenderScriptOverride) {
10930                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10931                }
10932            }
10933        } catch (IOException ioe) {
10934            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10935        } finally {
10936            IoUtils.closeQuietly(handle);
10937        }
10938
10939        // Now that we've calculated the ABIs and determined if it's an internal app,
10940        // we will go ahead and populate the nativeLibraryPath.
10941        setNativeLibraryPaths(pkg, appLib32InstallDir);
10942    }
10943
10944    /**
10945     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10946     * i.e, so that all packages can be run inside a single process if required.
10947     *
10948     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10949     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10950     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10951     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10952     * updating a package that belongs to a shared user.
10953     *
10954     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10955     * adds unnecessary complexity.
10956     */
10957    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10958            PackageParser.Package scannedPackage) {
10959        String requiredInstructionSet = null;
10960        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10961            requiredInstructionSet = VMRuntime.getInstructionSet(
10962                     scannedPackage.applicationInfo.primaryCpuAbi);
10963        }
10964
10965        PackageSetting requirer = null;
10966        for (PackageSetting ps : packagesForUser) {
10967            // If packagesForUser contains scannedPackage, we skip it. This will happen
10968            // when scannedPackage is an update of an existing package. Without this check,
10969            // we will never be able to change the ABI of any package belonging to a shared
10970            // user, even if it's compatible with other packages.
10971            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10972                if (ps.primaryCpuAbiString == null) {
10973                    continue;
10974                }
10975
10976                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10977                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10978                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10979                    // this but there's not much we can do.
10980                    String errorMessage = "Instruction set mismatch, "
10981                            + ((requirer == null) ? "[caller]" : requirer)
10982                            + " requires " + requiredInstructionSet + " whereas " + ps
10983                            + " requires " + instructionSet;
10984                    Slog.w(TAG, errorMessage);
10985                }
10986
10987                if (requiredInstructionSet == null) {
10988                    requiredInstructionSet = instructionSet;
10989                    requirer = ps;
10990                }
10991            }
10992        }
10993
10994        if (requiredInstructionSet != null) {
10995            String adjustedAbi;
10996            if (requirer != null) {
10997                // requirer != null implies that either scannedPackage was null or that scannedPackage
10998                // did not require an ABI, in which case we have to adjust scannedPackage to match
10999                // the ABI of the set (which is the same as requirer's ABI)
11000                adjustedAbi = requirer.primaryCpuAbiString;
11001                if (scannedPackage != null) {
11002                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11003                }
11004            } else {
11005                // requirer == null implies that we're updating all ABIs in the set to
11006                // match scannedPackage.
11007                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11008            }
11009
11010            for (PackageSetting ps : packagesForUser) {
11011                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11012                    if (ps.primaryCpuAbiString != null) {
11013                        continue;
11014                    }
11015
11016                    ps.primaryCpuAbiString = adjustedAbi;
11017                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11018                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11019                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11020                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11021                                + " (requirer="
11022                                + (requirer != null ? requirer.pkg : "null")
11023                                + ", scannedPackage="
11024                                + (scannedPackage != null ? scannedPackage : "null")
11025                                + ")");
11026                        try {
11027                            mInstaller.rmdex(ps.codePathString,
11028                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11029                        } catch (InstallerException ignored) {
11030                        }
11031                    }
11032                }
11033            }
11034        }
11035    }
11036
11037    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11038        synchronized (mPackages) {
11039            mResolverReplaced = true;
11040            // Set up information for custom user intent resolution activity.
11041            mResolveActivity.applicationInfo = pkg.applicationInfo;
11042            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11043            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11044            mResolveActivity.processName = pkg.applicationInfo.packageName;
11045            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11046            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11047                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11048            mResolveActivity.theme = 0;
11049            mResolveActivity.exported = true;
11050            mResolveActivity.enabled = true;
11051            mResolveInfo.activityInfo = mResolveActivity;
11052            mResolveInfo.priority = 0;
11053            mResolveInfo.preferredOrder = 0;
11054            mResolveInfo.match = 0;
11055            mResolveComponentName = mCustomResolverComponentName;
11056            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11057                    mResolveComponentName);
11058        }
11059    }
11060
11061    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11062        if (installerActivity == null) {
11063            if (DEBUG_EPHEMERAL) {
11064                Slog.d(TAG, "Clear ephemeral installer activity");
11065            }
11066            mInstantAppInstallerActivity = null;
11067            return;
11068        }
11069
11070        if (DEBUG_EPHEMERAL) {
11071            Slog.d(TAG, "Set ephemeral installer activity: "
11072                    + installerActivity.getComponentName());
11073        }
11074        // Set up information for ephemeral installer activity
11075        mInstantAppInstallerActivity = installerActivity;
11076        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11077                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11078        mInstantAppInstallerActivity.exported = true;
11079        mInstantAppInstallerActivity.enabled = true;
11080        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11081        mInstantAppInstallerInfo.priority = 0;
11082        mInstantAppInstallerInfo.preferredOrder = 1;
11083        mInstantAppInstallerInfo.isDefault = true;
11084        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11085                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11086    }
11087
11088    private static String calculateBundledApkRoot(final String codePathString) {
11089        final File codePath = new File(codePathString);
11090        final File codeRoot;
11091        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11092            codeRoot = Environment.getRootDirectory();
11093        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11094            codeRoot = Environment.getOemDirectory();
11095        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11096            codeRoot = Environment.getVendorDirectory();
11097        } else {
11098            // Unrecognized code path; take its top real segment as the apk root:
11099            // e.g. /something/app/blah.apk => /something
11100            try {
11101                File f = codePath.getCanonicalFile();
11102                File parent = f.getParentFile();    // non-null because codePath is a file
11103                File tmp;
11104                while ((tmp = parent.getParentFile()) != null) {
11105                    f = parent;
11106                    parent = tmp;
11107                }
11108                codeRoot = f;
11109                Slog.w(TAG, "Unrecognized code path "
11110                        + codePath + " - using " + codeRoot);
11111            } catch (IOException e) {
11112                // Can't canonicalize the code path -- shenanigans?
11113                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11114                return Environment.getRootDirectory().getPath();
11115            }
11116        }
11117        return codeRoot.getPath();
11118    }
11119
11120    /**
11121     * Derive and set the location of native libraries for the given package,
11122     * which varies depending on where and how the package was installed.
11123     */
11124    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11125        final ApplicationInfo info = pkg.applicationInfo;
11126        final String codePath = pkg.codePath;
11127        final File codeFile = new File(codePath);
11128        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11129        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11130
11131        info.nativeLibraryRootDir = null;
11132        info.nativeLibraryRootRequiresIsa = false;
11133        info.nativeLibraryDir = null;
11134        info.secondaryNativeLibraryDir = null;
11135
11136        if (isApkFile(codeFile)) {
11137            // Monolithic install
11138            if (bundledApp) {
11139                // If "/system/lib64/apkname" exists, assume that is the per-package
11140                // native library directory to use; otherwise use "/system/lib/apkname".
11141                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11142                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11143                        getPrimaryInstructionSet(info));
11144
11145                // This is a bundled system app so choose the path based on the ABI.
11146                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11147                // is just the default path.
11148                final String apkName = deriveCodePathName(codePath);
11149                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11150                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11151                        apkName).getAbsolutePath();
11152
11153                if (info.secondaryCpuAbi != null) {
11154                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11155                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11156                            secondaryLibDir, apkName).getAbsolutePath();
11157                }
11158            } else if (asecApp) {
11159                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11160                        .getAbsolutePath();
11161            } else {
11162                final String apkName = deriveCodePathName(codePath);
11163                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11164                        .getAbsolutePath();
11165            }
11166
11167            info.nativeLibraryRootRequiresIsa = false;
11168            info.nativeLibraryDir = info.nativeLibraryRootDir;
11169        } else {
11170            // Cluster install
11171            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11172            info.nativeLibraryRootRequiresIsa = true;
11173
11174            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11175                    getPrimaryInstructionSet(info)).getAbsolutePath();
11176
11177            if (info.secondaryCpuAbi != null) {
11178                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11179                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11180            }
11181        }
11182    }
11183
11184    /**
11185     * Calculate the abis and roots for a bundled app. These can uniquely
11186     * be determined from the contents of the system partition, i.e whether
11187     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11188     * of this information, and instead assume that the system was built
11189     * sensibly.
11190     */
11191    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11192                                           PackageSetting pkgSetting) {
11193        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11194
11195        // If "/system/lib64/apkname" exists, assume that is the per-package
11196        // native library directory to use; otherwise use "/system/lib/apkname".
11197        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11198        setBundledAppAbi(pkg, apkRoot, apkName);
11199        // pkgSetting might be null during rescan following uninstall of updates
11200        // to a bundled app, so accommodate that possibility.  The settings in
11201        // that case will be established later from the parsed package.
11202        //
11203        // If the settings aren't null, sync them up with what we've just derived.
11204        // note that apkRoot isn't stored in the package settings.
11205        if (pkgSetting != null) {
11206            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11207            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11208        }
11209    }
11210
11211    /**
11212     * Deduces the ABI of a bundled app and sets the relevant fields on the
11213     * parsed pkg object.
11214     *
11215     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11216     *        under which system libraries are installed.
11217     * @param apkName the name of the installed package.
11218     */
11219    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11220        final File codeFile = new File(pkg.codePath);
11221
11222        final boolean has64BitLibs;
11223        final boolean has32BitLibs;
11224        if (isApkFile(codeFile)) {
11225            // Monolithic install
11226            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11227            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11228        } else {
11229            // Cluster install
11230            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11231            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11232                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11233                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11234                has64BitLibs = (new File(rootDir, isa)).exists();
11235            } else {
11236                has64BitLibs = false;
11237            }
11238            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11239                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11240                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11241                has32BitLibs = (new File(rootDir, isa)).exists();
11242            } else {
11243                has32BitLibs = false;
11244            }
11245        }
11246
11247        if (has64BitLibs && !has32BitLibs) {
11248            // The package has 64 bit libs, but not 32 bit libs. Its primary
11249            // ABI should be 64 bit. We can safely assume here that the bundled
11250            // native libraries correspond to the most preferred ABI in the list.
11251
11252            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11253            pkg.applicationInfo.secondaryCpuAbi = null;
11254        } else if (has32BitLibs && !has64BitLibs) {
11255            // The package has 32 bit libs but not 64 bit libs. Its primary
11256            // ABI should be 32 bit.
11257
11258            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11259            pkg.applicationInfo.secondaryCpuAbi = null;
11260        } else if (has32BitLibs && has64BitLibs) {
11261            // The application has both 64 and 32 bit bundled libraries. We check
11262            // here that the app declares multiArch support, and warn if it doesn't.
11263            //
11264            // We will be lenient here and record both ABIs. The primary will be the
11265            // ABI that's higher on the list, i.e, a device that's configured to prefer
11266            // 64 bit apps will see a 64 bit primary ABI,
11267
11268            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11269                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11270            }
11271
11272            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11273                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11274                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11275            } else {
11276                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11277                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11278            }
11279        } else {
11280            pkg.applicationInfo.primaryCpuAbi = null;
11281            pkg.applicationInfo.secondaryCpuAbi = null;
11282        }
11283    }
11284
11285    private void killApplication(String pkgName, int appId, String reason) {
11286        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11287    }
11288
11289    private void killApplication(String pkgName, int appId, int userId, String reason) {
11290        // Request the ActivityManager to kill the process(only for existing packages)
11291        // so that we do not end up in a confused state while the user is still using the older
11292        // version of the application while the new one gets installed.
11293        final long token = Binder.clearCallingIdentity();
11294        try {
11295            IActivityManager am = ActivityManager.getService();
11296            if (am != null) {
11297                try {
11298                    am.killApplication(pkgName, appId, userId, reason);
11299                } catch (RemoteException e) {
11300                }
11301            }
11302        } finally {
11303            Binder.restoreCallingIdentity(token);
11304        }
11305    }
11306
11307    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11308        // Remove the parent package setting
11309        PackageSetting ps = (PackageSetting) pkg.mExtras;
11310        if (ps != null) {
11311            removePackageLI(ps, chatty);
11312        }
11313        // Remove the child package setting
11314        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11315        for (int i = 0; i < childCount; i++) {
11316            PackageParser.Package childPkg = pkg.childPackages.get(i);
11317            ps = (PackageSetting) childPkg.mExtras;
11318            if (ps != null) {
11319                removePackageLI(ps, chatty);
11320            }
11321        }
11322    }
11323
11324    void removePackageLI(PackageSetting ps, boolean chatty) {
11325        if (DEBUG_INSTALL) {
11326            if (chatty)
11327                Log.d(TAG, "Removing package " + ps.name);
11328        }
11329
11330        // writer
11331        synchronized (mPackages) {
11332            mPackages.remove(ps.name);
11333            final PackageParser.Package pkg = ps.pkg;
11334            if (pkg != null) {
11335                cleanPackageDataStructuresLILPw(pkg, chatty);
11336            }
11337        }
11338    }
11339
11340    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
11341        if (DEBUG_INSTALL) {
11342            if (chatty)
11343                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
11344        }
11345
11346        // writer
11347        synchronized (mPackages) {
11348            // Remove the parent package
11349            mPackages.remove(pkg.applicationInfo.packageName);
11350            cleanPackageDataStructuresLILPw(pkg, chatty);
11351
11352            // Remove the child packages
11353            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11354            for (int i = 0; i < childCount; i++) {
11355                PackageParser.Package childPkg = pkg.childPackages.get(i);
11356                mPackages.remove(childPkg.applicationInfo.packageName);
11357                cleanPackageDataStructuresLILPw(childPkg, chatty);
11358            }
11359        }
11360    }
11361
11362    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11363        int N = pkg.providers.size();
11364        StringBuilder r = null;
11365        int i;
11366        for (i=0; i<N; i++) {
11367            PackageParser.Provider p = pkg.providers.get(i);
11368            mProviders.removeProvider(p);
11369            if (p.info.authority == null) {
11370
11371                /* There was another ContentProvider with this authority when
11372                 * this app was installed so this authority is null,
11373                 * Ignore it as we don't have to unregister the provider.
11374                 */
11375                continue;
11376            }
11377            String names[] = p.info.authority.split(";");
11378            for (int j = 0; j < names.length; j++) {
11379                if (mProvidersByAuthority.get(names[j]) == p) {
11380                    mProvidersByAuthority.remove(names[j]);
11381                    if (DEBUG_REMOVE) {
11382                        if (chatty)
11383                            Log.d(TAG, "Unregistered content provider: " + names[j]
11384                                    + ", className = " + p.info.name + ", isSyncable = "
11385                                    + p.info.isSyncable);
11386                    }
11387                }
11388            }
11389            if (DEBUG_REMOVE && chatty) {
11390                if (r == null) {
11391                    r = new StringBuilder(256);
11392                } else {
11393                    r.append(' ');
11394                }
11395                r.append(p.info.name);
11396            }
11397        }
11398        if (r != null) {
11399            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11400        }
11401
11402        N = pkg.services.size();
11403        r = null;
11404        for (i=0; i<N; i++) {
11405            PackageParser.Service s = pkg.services.get(i);
11406            mServices.removeService(s);
11407            if (chatty) {
11408                if (r == null) {
11409                    r = new StringBuilder(256);
11410                } else {
11411                    r.append(' ');
11412                }
11413                r.append(s.info.name);
11414            }
11415        }
11416        if (r != null) {
11417            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11418        }
11419
11420        N = pkg.receivers.size();
11421        r = null;
11422        for (i=0; i<N; i++) {
11423            PackageParser.Activity a = pkg.receivers.get(i);
11424            mReceivers.removeActivity(a, "receiver");
11425            if (DEBUG_REMOVE && chatty) {
11426                if (r == null) {
11427                    r = new StringBuilder(256);
11428                } else {
11429                    r.append(' ');
11430                }
11431                r.append(a.info.name);
11432            }
11433        }
11434        if (r != null) {
11435            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11436        }
11437
11438        N = pkg.activities.size();
11439        r = null;
11440        for (i=0; i<N; i++) {
11441            PackageParser.Activity a = pkg.activities.get(i);
11442            mActivities.removeActivity(a, "activity");
11443            if (DEBUG_REMOVE && chatty) {
11444                if (r == null) {
11445                    r = new StringBuilder(256);
11446                } else {
11447                    r.append(' ');
11448                }
11449                r.append(a.info.name);
11450            }
11451        }
11452        if (r != null) {
11453            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11454        }
11455
11456        N = pkg.permissions.size();
11457        r = null;
11458        for (i=0; i<N; i++) {
11459            PackageParser.Permission p = pkg.permissions.get(i);
11460            BasePermission bp = mSettings.mPermissions.get(p.info.name);
11461            if (bp == null) {
11462                bp = mSettings.mPermissionTrees.get(p.info.name);
11463            }
11464            if (bp != null && bp.perm == p) {
11465                bp.perm = null;
11466                if (DEBUG_REMOVE && chatty) {
11467                    if (r == null) {
11468                        r = new StringBuilder(256);
11469                    } else {
11470                        r.append(' ');
11471                    }
11472                    r.append(p.info.name);
11473                }
11474            }
11475            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11476                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11477                if (appOpPkgs != null) {
11478                    appOpPkgs.remove(pkg.packageName);
11479                }
11480            }
11481        }
11482        if (r != null) {
11483            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11484        }
11485
11486        N = pkg.requestedPermissions.size();
11487        r = null;
11488        for (i=0; i<N; i++) {
11489            String perm = pkg.requestedPermissions.get(i);
11490            BasePermission bp = mSettings.mPermissions.get(perm);
11491            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11492                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11493                if (appOpPkgs != null) {
11494                    appOpPkgs.remove(pkg.packageName);
11495                    if (appOpPkgs.isEmpty()) {
11496                        mAppOpPermissionPackages.remove(perm);
11497                    }
11498                }
11499            }
11500        }
11501        if (r != null) {
11502            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11503        }
11504
11505        N = pkg.instrumentation.size();
11506        r = null;
11507        for (i=0; i<N; i++) {
11508            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11509            mInstrumentation.remove(a.getComponentName());
11510            if (DEBUG_REMOVE && chatty) {
11511                if (r == null) {
11512                    r = new StringBuilder(256);
11513                } else {
11514                    r.append(' ');
11515                }
11516                r.append(a.info.name);
11517            }
11518        }
11519        if (r != null) {
11520            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11521        }
11522
11523        r = null;
11524        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11525            // Only system apps can hold shared libraries.
11526            if (pkg.libraryNames != null) {
11527                for (i = 0; i < pkg.libraryNames.size(); i++) {
11528                    String name = pkg.libraryNames.get(i);
11529                    if (removeSharedLibraryLPw(name, 0)) {
11530                        if (DEBUG_REMOVE && chatty) {
11531                            if (r == null) {
11532                                r = new StringBuilder(256);
11533                            } else {
11534                                r.append(' ');
11535                            }
11536                            r.append(name);
11537                        }
11538                    }
11539                }
11540            }
11541        }
11542
11543        r = null;
11544
11545        // Any package can hold static shared libraries.
11546        if (pkg.staticSharedLibName != null) {
11547            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11548                if (DEBUG_REMOVE && chatty) {
11549                    if (r == null) {
11550                        r = new StringBuilder(256);
11551                    } else {
11552                        r.append(' ');
11553                    }
11554                    r.append(pkg.staticSharedLibName);
11555                }
11556            }
11557        }
11558
11559        if (r != null) {
11560            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11561        }
11562    }
11563
11564    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11565        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11566            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11567                return true;
11568            }
11569        }
11570        return false;
11571    }
11572
11573    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11574    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11575    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11576
11577    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11578        // Update the parent permissions
11579        updatePermissionsLPw(pkg.packageName, pkg, flags);
11580        // Update the child permissions
11581        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11582        for (int i = 0; i < childCount; i++) {
11583            PackageParser.Package childPkg = pkg.childPackages.get(i);
11584            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11585        }
11586    }
11587
11588    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11589            int flags) {
11590        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11591        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11592    }
11593
11594    private void updatePermissionsLPw(String changingPkg,
11595            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11596        // Make sure there are no dangling permission trees.
11597        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11598        while (it.hasNext()) {
11599            final BasePermission bp = it.next();
11600            if (bp.packageSetting == null) {
11601                // We may not yet have parsed the package, so just see if
11602                // we still know about its settings.
11603                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11604            }
11605            if (bp.packageSetting == null) {
11606                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11607                        + " from package " + bp.sourcePackage);
11608                it.remove();
11609            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11610                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11611                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11612                            + " from package " + bp.sourcePackage);
11613                    flags |= UPDATE_PERMISSIONS_ALL;
11614                    it.remove();
11615                }
11616            }
11617        }
11618
11619        // Make sure all dynamic permissions have been assigned to a package,
11620        // and make sure there are no dangling permissions.
11621        it = mSettings.mPermissions.values().iterator();
11622        while (it.hasNext()) {
11623            final BasePermission bp = it.next();
11624            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11625                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11626                        + bp.name + " pkg=" + bp.sourcePackage
11627                        + " info=" + bp.pendingInfo);
11628                if (bp.packageSetting == null && bp.pendingInfo != null) {
11629                    final BasePermission tree = findPermissionTreeLP(bp.name);
11630                    if (tree != null && tree.perm != null) {
11631                        bp.packageSetting = tree.packageSetting;
11632                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11633                                new PermissionInfo(bp.pendingInfo));
11634                        bp.perm.info.packageName = tree.perm.info.packageName;
11635                        bp.perm.info.name = bp.name;
11636                        bp.uid = tree.uid;
11637                    }
11638                }
11639            }
11640            if (bp.packageSetting == null) {
11641                // We may not yet have parsed the package, so just see if
11642                // we still know about its settings.
11643                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11644            }
11645            if (bp.packageSetting == null) {
11646                Slog.w(TAG, "Removing dangling permission: " + bp.name
11647                        + " from package " + bp.sourcePackage);
11648                it.remove();
11649            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11650                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11651                    Slog.i(TAG, "Removing old permission: " + bp.name
11652                            + " from package " + bp.sourcePackage);
11653                    flags |= UPDATE_PERMISSIONS_ALL;
11654                    it.remove();
11655                }
11656            }
11657        }
11658
11659        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11660        // Now update the permissions for all packages, in particular
11661        // replace the granted permissions of the system packages.
11662        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11663            for (PackageParser.Package pkg : mPackages.values()) {
11664                if (pkg != pkgInfo) {
11665                    // Only replace for packages on requested volume
11666                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11667                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11668                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11669                    grantPermissionsLPw(pkg, replace, changingPkg);
11670                }
11671            }
11672        }
11673
11674        if (pkgInfo != null) {
11675            // Only replace for packages on requested volume
11676            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11677            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11678                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11679            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11680        }
11681        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11682    }
11683
11684    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11685            String packageOfInterest) {
11686        // IMPORTANT: There are two types of permissions: install and runtime.
11687        // Install time permissions are granted when the app is installed to
11688        // all device users and users added in the future. Runtime permissions
11689        // are granted at runtime explicitly to specific users. Normal and signature
11690        // protected permissions are install time permissions. Dangerous permissions
11691        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11692        // otherwise they are runtime permissions. This function does not manage
11693        // runtime permissions except for the case an app targeting Lollipop MR1
11694        // being upgraded to target a newer SDK, in which case dangerous permissions
11695        // are transformed from install time to runtime ones.
11696
11697        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11698        if (ps == null) {
11699            return;
11700        }
11701
11702        PermissionsState permissionsState = ps.getPermissionsState();
11703        PermissionsState origPermissions = permissionsState;
11704
11705        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11706
11707        boolean runtimePermissionsRevoked = false;
11708        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11709
11710        boolean changedInstallPermission = false;
11711
11712        if (replace) {
11713            ps.installPermissionsFixed = false;
11714            if (!ps.isSharedUser()) {
11715                origPermissions = new PermissionsState(permissionsState);
11716                permissionsState.reset();
11717            } else {
11718                // We need to know only about runtime permission changes since the
11719                // calling code always writes the install permissions state but
11720                // the runtime ones are written only if changed. The only cases of
11721                // changed runtime permissions here are promotion of an install to
11722                // runtime and revocation of a runtime from a shared user.
11723                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11724                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11725                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11726                    runtimePermissionsRevoked = true;
11727                }
11728            }
11729        }
11730
11731        permissionsState.setGlobalGids(mGlobalGids);
11732
11733        final int N = pkg.requestedPermissions.size();
11734        for (int i=0; i<N; i++) {
11735            final String name = pkg.requestedPermissions.get(i);
11736            final BasePermission bp = mSettings.mPermissions.get(name);
11737            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11738                    >= Build.VERSION_CODES.M;
11739
11740            if (DEBUG_INSTALL) {
11741                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11742            }
11743
11744            if (bp == null || bp.packageSetting == null) {
11745                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11746                    Slog.w(TAG, "Unknown permission " + name
11747                            + " in package " + pkg.packageName);
11748                }
11749                continue;
11750            }
11751
11752
11753            // Limit ephemeral apps to ephemeral allowed permissions.
11754            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11755                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11756                        + pkg.packageName);
11757                continue;
11758            }
11759
11760            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
11761                Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
11762                        + pkg.packageName);
11763                continue;
11764            }
11765
11766            final String perm = bp.name;
11767            boolean allowedSig = false;
11768            int grant = GRANT_DENIED;
11769
11770            // Keep track of app op permissions.
11771            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11772                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11773                if (pkgs == null) {
11774                    pkgs = new ArraySet<>();
11775                    mAppOpPermissionPackages.put(bp.name, pkgs);
11776                }
11777                pkgs.add(pkg.packageName);
11778            }
11779
11780            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11781            switch (level) {
11782                case PermissionInfo.PROTECTION_NORMAL: {
11783                    // For all apps normal permissions are install time ones.
11784                    grant = GRANT_INSTALL;
11785                } break;
11786
11787                case PermissionInfo.PROTECTION_DANGEROUS: {
11788                    // If a permission review is required for legacy apps we represent
11789                    // their permissions as always granted runtime ones since we need
11790                    // to keep the review required permission flag per user while an
11791                    // install permission's state is shared across all users.
11792                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11793                        // For legacy apps dangerous permissions are install time ones.
11794                        grant = GRANT_INSTALL;
11795                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11796                        // For legacy apps that became modern, install becomes runtime.
11797                        grant = GRANT_UPGRADE;
11798                    } else if (mPromoteSystemApps
11799                            && isSystemApp(ps)
11800                            && mExistingSystemPackages.contains(ps.name)) {
11801                        // For legacy system apps, install becomes runtime.
11802                        // We cannot check hasInstallPermission() for system apps since those
11803                        // permissions were granted implicitly and not persisted pre-M.
11804                        grant = GRANT_UPGRADE;
11805                    } else {
11806                        // For modern apps keep runtime permissions unchanged.
11807                        grant = GRANT_RUNTIME;
11808                    }
11809                } break;
11810
11811                case PermissionInfo.PROTECTION_SIGNATURE: {
11812                    // For all apps signature permissions are install time ones.
11813                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11814                    if (allowedSig) {
11815                        grant = GRANT_INSTALL;
11816                    }
11817                } break;
11818            }
11819
11820            if (DEBUG_INSTALL) {
11821                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11822            }
11823
11824            if (grant != GRANT_DENIED) {
11825                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11826                    // If this is an existing, non-system package, then
11827                    // we can't add any new permissions to it.
11828                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11829                        // Except...  if this is a permission that was added
11830                        // to the platform (note: need to only do this when
11831                        // updating the platform).
11832                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11833                            grant = GRANT_DENIED;
11834                        }
11835                    }
11836                }
11837
11838                switch (grant) {
11839                    case GRANT_INSTALL: {
11840                        // Revoke this as runtime permission to handle the case of
11841                        // a runtime permission being downgraded to an install one.
11842                        // Also in permission review mode we keep dangerous permissions
11843                        // for legacy apps
11844                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11845                            if (origPermissions.getRuntimePermissionState(
11846                                    bp.name, userId) != null) {
11847                                // Revoke the runtime permission and clear the flags.
11848                                origPermissions.revokeRuntimePermission(bp, userId);
11849                                origPermissions.updatePermissionFlags(bp, userId,
11850                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11851                                // If we revoked a permission permission, we have to write.
11852                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11853                                        changedRuntimePermissionUserIds, userId);
11854                            }
11855                        }
11856                        // Grant an install permission.
11857                        if (permissionsState.grantInstallPermission(bp) !=
11858                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11859                            changedInstallPermission = true;
11860                        }
11861                    } break;
11862
11863                    case GRANT_RUNTIME: {
11864                        // Grant previously granted runtime permissions.
11865                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11866                            PermissionState permissionState = origPermissions
11867                                    .getRuntimePermissionState(bp.name, userId);
11868                            int flags = permissionState != null
11869                                    ? permissionState.getFlags() : 0;
11870                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11871                                // Don't propagate the permission in a permission review mode if
11872                                // the former was revoked, i.e. marked to not propagate on upgrade.
11873                                // Note that in a permission review mode install permissions are
11874                                // represented as constantly granted runtime ones since we need to
11875                                // keep a per user state associated with the permission. Also the
11876                                // revoke on upgrade flag is no longer applicable and is reset.
11877                                final boolean revokeOnUpgrade = (flags & PackageManager
11878                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11879                                if (revokeOnUpgrade) {
11880                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11881                                    // Since we changed the flags, we have to write.
11882                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11883                                            changedRuntimePermissionUserIds, userId);
11884                                }
11885                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11886                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11887                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11888                                        // If we cannot put the permission as it was,
11889                                        // we have to write.
11890                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11891                                                changedRuntimePermissionUserIds, userId);
11892                                    }
11893                                }
11894
11895                                // If the app supports runtime permissions no need for a review.
11896                                if (mPermissionReviewRequired
11897                                        && appSupportsRuntimePermissions
11898                                        && (flags & PackageManager
11899                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11900                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11901                                    // Since we changed the flags, we have to write.
11902                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11903                                            changedRuntimePermissionUserIds, userId);
11904                                }
11905                            } else if (mPermissionReviewRequired
11906                                    && !appSupportsRuntimePermissions) {
11907                                // For legacy apps that need a permission review, every new
11908                                // runtime permission is granted but it is pending a review.
11909                                // We also need to review only platform defined runtime
11910                                // permissions as these are the only ones the platform knows
11911                                // how to disable the API to simulate revocation as legacy
11912                                // apps don't expect to run with revoked permissions.
11913                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11914                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11915                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11916                                        // We changed the flags, hence have to write.
11917                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11918                                                changedRuntimePermissionUserIds, userId);
11919                                    }
11920                                }
11921                                if (permissionsState.grantRuntimePermission(bp, userId)
11922                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11923                                    // We changed the permission, hence have to write.
11924                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11925                                            changedRuntimePermissionUserIds, userId);
11926                                }
11927                            }
11928                            // Propagate the permission flags.
11929                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11930                        }
11931                    } break;
11932
11933                    case GRANT_UPGRADE: {
11934                        // Grant runtime permissions for a previously held install permission.
11935                        PermissionState permissionState = origPermissions
11936                                .getInstallPermissionState(bp.name);
11937                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11938
11939                        if (origPermissions.revokeInstallPermission(bp)
11940                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11941                            // We will be transferring the permission flags, so clear them.
11942                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11943                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11944                            changedInstallPermission = true;
11945                        }
11946
11947                        // If the permission is not to be promoted to runtime we ignore it and
11948                        // also its other flags as they are not applicable to install permissions.
11949                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11950                            for (int userId : currentUserIds) {
11951                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11952                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11953                                    // Transfer the permission flags.
11954                                    permissionsState.updatePermissionFlags(bp, userId,
11955                                            flags, flags);
11956                                    // If we granted the permission, we have to write.
11957                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11958                                            changedRuntimePermissionUserIds, userId);
11959                                }
11960                            }
11961                        }
11962                    } break;
11963
11964                    default: {
11965                        if (packageOfInterest == null
11966                                || packageOfInterest.equals(pkg.packageName)) {
11967                            Slog.w(TAG, "Not granting permission " + perm
11968                                    + " to package " + pkg.packageName
11969                                    + " because it was previously installed without");
11970                        }
11971                    } break;
11972                }
11973            } else {
11974                if (permissionsState.revokeInstallPermission(bp) !=
11975                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11976                    // Also drop the permission flags.
11977                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11978                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11979                    changedInstallPermission = true;
11980                    Slog.i(TAG, "Un-granting permission " + perm
11981                            + " from package " + pkg.packageName
11982                            + " (protectionLevel=" + bp.protectionLevel
11983                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11984                            + ")");
11985                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11986                    // Don't print warning for app op permissions, since it is fine for them
11987                    // not to be granted, there is a UI for the user to decide.
11988                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11989                        Slog.w(TAG, "Not granting permission " + perm
11990                                + " to package " + pkg.packageName
11991                                + " (protectionLevel=" + bp.protectionLevel
11992                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11993                                + ")");
11994                    }
11995                }
11996            }
11997        }
11998
11999        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12000                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12001            // This is the first that we have heard about this package, so the
12002            // permissions we have now selected are fixed until explicitly
12003            // changed.
12004            ps.installPermissionsFixed = true;
12005        }
12006
12007        // Persist the runtime permissions state for users with changes. If permissions
12008        // were revoked because no app in the shared user declares them we have to
12009        // write synchronously to avoid losing runtime permissions state.
12010        for (int userId : changedRuntimePermissionUserIds) {
12011            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12012        }
12013    }
12014
12015    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12016        boolean allowed = false;
12017        final int NP = PackageParser.NEW_PERMISSIONS.length;
12018        for (int ip=0; ip<NP; ip++) {
12019            final PackageParser.NewPermissionInfo npi
12020                    = PackageParser.NEW_PERMISSIONS[ip];
12021            if (npi.name.equals(perm)
12022                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12023                allowed = true;
12024                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12025                        + pkg.packageName);
12026                break;
12027            }
12028        }
12029        return allowed;
12030    }
12031
12032    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12033            BasePermission bp, PermissionsState origPermissions) {
12034        boolean privilegedPermission = (bp.protectionLevel
12035                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12036        boolean privappPermissionsDisable =
12037                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12038        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12039        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12040        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12041                && !platformPackage && platformPermission) {
12042            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12043                    .getPrivAppPermissions(pkg.packageName);
12044            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12045            if (!whitelisted) {
12046                Slog.w(TAG, "Privileged permission " + perm + " for package "
12047                        + pkg.packageName + " - not in privapp-permissions whitelist");
12048                // Only report violations for apps on system image
12049                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12050                    if (mPrivappPermissionsViolations == null) {
12051                        mPrivappPermissionsViolations = new ArraySet<>();
12052                    }
12053                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12054                }
12055                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12056                    return false;
12057                }
12058            }
12059        }
12060        boolean allowed = (compareSignatures(
12061                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12062                        == PackageManager.SIGNATURE_MATCH)
12063                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12064                        == PackageManager.SIGNATURE_MATCH);
12065        if (!allowed && privilegedPermission) {
12066            if (isSystemApp(pkg)) {
12067                // For updated system applications, a system permission
12068                // is granted only if it had been defined by the original application.
12069                if (pkg.isUpdatedSystemApp()) {
12070                    final PackageSetting sysPs = mSettings
12071                            .getDisabledSystemPkgLPr(pkg.packageName);
12072                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12073                        // If the original was granted this permission, we take
12074                        // that grant decision as read and propagate it to the
12075                        // update.
12076                        if (sysPs.isPrivileged()) {
12077                            allowed = true;
12078                        }
12079                    } else {
12080                        // The system apk may have been updated with an older
12081                        // version of the one on the data partition, but which
12082                        // granted a new system permission that it didn't have
12083                        // before.  In this case we do want to allow the app to
12084                        // now get the new permission if the ancestral apk is
12085                        // privileged to get it.
12086                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12087                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12088                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12089                                    allowed = true;
12090                                    break;
12091                                }
12092                            }
12093                        }
12094                        // Also if a privileged parent package on the system image or any of
12095                        // its children requested a privileged permission, the updated child
12096                        // packages can also get the permission.
12097                        if (pkg.parentPackage != null) {
12098                            final PackageSetting disabledSysParentPs = mSettings
12099                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12100                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12101                                    && disabledSysParentPs.isPrivileged()) {
12102                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12103                                    allowed = true;
12104                                } else if (disabledSysParentPs.pkg.childPackages != null) {
12105                                    final int count = disabledSysParentPs.pkg.childPackages.size();
12106                                    for (int i = 0; i < count; i++) {
12107                                        PackageParser.Package disabledSysChildPkg =
12108                                                disabledSysParentPs.pkg.childPackages.get(i);
12109                                        if (isPackageRequestingPermission(disabledSysChildPkg,
12110                                                perm)) {
12111                                            allowed = true;
12112                                            break;
12113                                        }
12114                                    }
12115                                }
12116                            }
12117                        }
12118                    }
12119                } else {
12120                    allowed = isPrivilegedApp(pkg);
12121                }
12122            }
12123        }
12124        if (!allowed) {
12125            if (!allowed && (bp.protectionLevel
12126                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12127                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12128                // If this was a previously normal/dangerous permission that got moved
12129                // to a system permission as part of the runtime permission redesign, then
12130                // we still want to blindly grant it to old apps.
12131                allowed = true;
12132            }
12133            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12134                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12135                // If this permission is to be granted to the system installer and
12136                // this app is an installer, then it gets the permission.
12137                allowed = true;
12138            }
12139            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12140                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12141                // If this permission is to be granted to the system verifier and
12142                // this app is a verifier, then it gets the permission.
12143                allowed = true;
12144            }
12145            if (!allowed && (bp.protectionLevel
12146                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12147                    && isSystemApp(pkg)) {
12148                // Any pre-installed system app is allowed to get this permission.
12149                allowed = true;
12150            }
12151            if (!allowed && (bp.protectionLevel
12152                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12153                // For development permissions, a development permission
12154                // is granted only if it was already granted.
12155                allowed = origPermissions.hasInstallPermission(perm);
12156            }
12157            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12158                    && pkg.packageName.equals(mSetupWizardPackage)) {
12159                // If this permission is to be granted to the system setup wizard and
12160                // this app is a setup wizard, then it gets the permission.
12161                allowed = true;
12162            }
12163        }
12164        return allowed;
12165    }
12166
12167    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12168        final int permCount = pkg.requestedPermissions.size();
12169        for (int j = 0; j < permCount; j++) {
12170            String requestedPermission = pkg.requestedPermissions.get(j);
12171            if (permission.equals(requestedPermission)) {
12172                return true;
12173            }
12174        }
12175        return false;
12176    }
12177
12178    final class ActivityIntentResolver
12179            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12180        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12181                boolean defaultOnly, int userId) {
12182            if (!sUserManager.exists(userId)) return null;
12183            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12184            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12185        }
12186
12187        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12188                int userId) {
12189            if (!sUserManager.exists(userId)) return null;
12190            mFlags = flags;
12191            return super.queryIntent(intent, resolvedType,
12192                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12193                    userId);
12194        }
12195
12196        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12197                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12198            if (!sUserManager.exists(userId)) return null;
12199            if (packageActivities == null) {
12200                return null;
12201            }
12202            mFlags = flags;
12203            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12204            final int N = packageActivities.size();
12205            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12206                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12207
12208            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12209            for (int i = 0; i < N; ++i) {
12210                intentFilters = packageActivities.get(i).intents;
12211                if (intentFilters != null && intentFilters.size() > 0) {
12212                    PackageParser.ActivityIntentInfo[] array =
12213                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12214                    intentFilters.toArray(array);
12215                    listCut.add(array);
12216                }
12217            }
12218            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12219        }
12220
12221        /**
12222         * Finds a privileged activity that matches the specified activity names.
12223         */
12224        private PackageParser.Activity findMatchingActivity(
12225                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12226            for (PackageParser.Activity sysActivity : activityList) {
12227                if (sysActivity.info.name.equals(activityInfo.name)) {
12228                    return sysActivity;
12229                }
12230                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12231                    return sysActivity;
12232                }
12233                if (sysActivity.info.targetActivity != null) {
12234                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12235                        return sysActivity;
12236                    }
12237                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12238                        return sysActivity;
12239                    }
12240                }
12241            }
12242            return null;
12243        }
12244
12245        public class IterGenerator<E> {
12246            public Iterator<E> generate(ActivityIntentInfo info) {
12247                return null;
12248            }
12249        }
12250
12251        public class ActionIterGenerator extends IterGenerator<String> {
12252            @Override
12253            public Iterator<String> generate(ActivityIntentInfo info) {
12254                return info.actionsIterator();
12255            }
12256        }
12257
12258        public class CategoriesIterGenerator extends IterGenerator<String> {
12259            @Override
12260            public Iterator<String> generate(ActivityIntentInfo info) {
12261                return info.categoriesIterator();
12262            }
12263        }
12264
12265        public class SchemesIterGenerator extends IterGenerator<String> {
12266            @Override
12267            public Iterator<String> generate(ActivityIntentInfo info) {
12268                return info.schemesIterator();
12269            }
12270        }
12271
12272        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12273            @Override
12274            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12275                return info.authoritiesIterator();
12276            }
12277        }
12278
12279        /**
12280         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12281         * MODIFIED. Do not pass in a list that should not be changed.
12282         */
12283        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12284                IterGenerator<T> generator, Iterator<T> searchIterator) {
12285            // loop through the set of actions; every one must be found in the intent filter
12286            while (searchIterator.hasNext()) {
12287                // we must have at least one filter in the list to consider a match
12288                if (intentList.size() == 0) {
12289                    break;
12290                }
12291
12292                final T searchAction = searchIterator.next();
12293
12294                // loop through the set of intent filters
12295                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12296                while (intentIter.hasNext()) {
12297                    final ActivityIntentInfo intentInfo = intentIter.next();
12298                    boolean selectionFound = false;
12299
12300                    // loop through the intent filter's selection criteria; at least one
12301                    // of them must match the searched criteria
12302                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12303                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12304                        final T intentSelection = intentSelectionIter.next();
12305                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12306                            selectionFound = true;
12307                            break;
12308                        }
12309                    }
12310
12311                    // the selection criteria wasn't found in this filter's set; this filter
12312                    // is not a potential match
12313                    if (!selectionFound) {
12314                        intentIter.remove();
12315                    }
12316                }
12317            }
12318        }
12319
12320        private boolean isProtectedAction(ActivityIntentInfo filter) {
12321            final Iterator<String> actionsIter = filter.actionsIterator();
12322            while (actionsIter != null && actionsIter.hasNext()) {
12323                final String filterAction = actionsIter.next();
12324                if (PROTECTED_ACTIONS.contains(filterAction)) {
12325                    return true;
12326                }
12327            }
12328            return false;
12329        }
12330
12331        /**
12332         * Adjusts the priority of the given intent filter according to policy.
12333         * <p>
12334         * <ul>
12335         * <li>The priority for non privileged applications is capped to '0'</li>
12336         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12337         * <li>The priority for unbundled updates to privileged applications is capped to the
12338         *      priority defined on the system partition</li>
12339         * </ul>
12340         * <p>
12341         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12342         * allowed to obtain any priority on any action.
12343         */
12344        private void adjustPriority(
12345                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12346            // nothing to do; priority is fine as-is
12347            if (intent.getPriority() <= 0) {
12348                return;
12349            }
12350
12351            final ActivityInfo activityInfo = intent.activity.info;
12352            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12353
12354            final boolean privilegedApp =
12355                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12356            if (!privilegedApp) {
12357                // non-privileged applications can never define a priority >0
12358                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
12359                        + " package: " + applicationInfo.packageName
12360                        + " activity: " + intent.activity.className
12361                        + " origPrio: " + intent.getPriority());
12362                intent.setPriority(0);
12363                return;
12364            }
12365
12366            if (systemActivities == null) {
12367                // the system package is not disabled; we're parsing the system partition
12368                if (isProtectedAction(intent)) {
12369                    if (mDeferProtectedFilters) {
12370                        // We can't deal with these just yet. No component should ever obtain a
12371                        // >0 priority for a protected actions, with ONE exception -- the setup
12372                        // wizard. The setup wizard, however, cannot be known until we're able to
12373                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12374                        // until all intent filters have been processed. Chicken, meet egg.
12375                        // Let the filter temporarily have a high priority and rectify the
12376                        // priorities after all system packages have been scanned.
12377                        mProtectedFilters.add(intent);
12378                        if (DEBUG_FILTERS) {
12379                            Slog.i(TAG, "Protected action; save for later;"
12380                                    + " package: " + applicationInfo.packageName
12381                                    + " activity: " + intent.activity.className
12382                                    + " origPrio: " + intent.getPriority());
12383                        }
12384                        return;
12385                    } else {
12386                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12387                            Slog.i(TAG, "No setup wizard;"
12388                                + " All protected intents capped to priority 0");
12389                        }
12390                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12391                            if (DEBUG_FILTERS) {
12392                                Slog.i(TAG, "Found setup wizard;"
12393                                    + " allow priority " + intent.getPriority() + ";"
12394                                    + " package: " + intent.activity.info.packageName
12395                                    + " activity: " + intent.activity.className
12396                                    + " priority: " + intent.getPriority());
12397                            }
12398                            // setup wizard gets whatever it wants
12399                            return;
12400                        }
12401                        Slog.w(TAG, "Protected action; cap priority to 0;"
12402                                + " package: " + intent.activity.info.packageName
12403                                + " activity: " + intent.activity.className
12404                                + " origPrio: " + intent.getPriority());
12405                        intent.setPriority(0);
12406                        return;
12407                    }
12408                }
12409                // privileged apps on the system image get whatever priority they request
12410                return;
12411            }
12412
12413            // privileged app unbundled update ... try to find the same activity
12414            final PackageParser.Activity foundActivity =
12415                    findMatchingActivity(systemActivities, activityInfo);
12416            if (foundActivity == null) {
12417                // this is a new activity; it cannot obtain >0 priority
12418                if (DEBUG_FILTERS) {
12419                    Slog.i(TAG, "New activity; cap priority to 0;"
12420                            + " package: " + applicationInfo.packageName
12421                            + " activity: " + intent.activity.className
12422                            + " origPrio: " + intent.getPriority());
12423                }
12424                intent.setPriority(0);
12425                return;
12426            }
12427
12428            // found activity, now check for filter equivalence
12429
12430            // a shallow copy is enough; we modify the list, not its contents
12431            final List<ActivityIntentInfo> intentListCopy =
12432                    new ArrayList<>(foundActivity.intents);
12433            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12434
12435            // find matching action subsets
12436            final Iterator<String> actionsIterator = intent.actionsIterator();
12437            if (actionsIterator != null) {
12438                getIntentListSubset(
12439                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12440                if (intentListCopy.size() == 0) {
12441                    // no more intents to match; we're not equivalent
12442                    if (DEBUG_FILTERS) {
12443                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12444                                + " package: " + applicationInfo.packageName
12445                                + " activity: " + intent.activity.className
12446                                + " origPrio: " + intent.getPriority());
12447                    }
12448                    intent.setPriority(0);
12449                    return;
12450                }
12451            }
12452
12453            // find matching category subsets
12454            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12455            if (categoriesIterator != null) {
12456                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12457                        categoriesIterator);
12458                if (intentListCopy.size() == 0) {
12459                    // no more intents to match; we're not equivalent
12460                    if (DEBUG_FILTERS) {
12461                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12462                                + " package: " + applicationInfo.packageName
12463                                + " activity: " + intent.activity.className
12464                                + " origPrio: " + intent.getPriority());
12465                    }
12466                    intent.setPriority(0);
12467                    return;
12468                }
12469            }
12470
12471            // find matching schemes subsets
12472            final Iterator<String> schemesIterator = intent.schemesIterator();
12473            if (schemesIterator != null) {
12474                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12475                        schemesIterator);
12476                if (intentListCopy.size() == 0) {
12477                    // no more intents to match; we're not equivalent
12478                    if (DEBUG_FILTERS) {
12479                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12480                                + " package: " + applicationInfo.packageName
12481                                + " activity: " + intent.activity.className
12482                                + " origPrio: " + intent.getPriority());
12483                    }
12484                    intent.setPriority(0);
12485                    return;
12486                }
12487            }
12488
12489            // find matching authorities subsets
12490            final Iterator<IntentFilter.AuthorityEntry>
12491                    authoritiesIterator = intent.authoritiesIterator();
12492            if (authoritiesIterator != null) {
12493                getIntentListSubset(intentListCopy,
12494                        new AuthoritiesIterGenerator(),
12495                        authoritiesIterator);
12496                if (intentListCopy.size() == 0) {
12497                    // no more intents to match; we're not equivalent
12498                    if (DEBUG_FILTERS) {
12499                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12500                                + " package: " + applicationInfo.packageName
12501                                + " activity: " + intent.activity.className
12502                                + " origPrio: " + intent.getPriority());
12503                    }
12504                    intent.setPriority(0);
12505                    return;
12506                }
12507            }
12508
12509            // we found matching filter(s); app gets the max priority of all intents
12510            int cappedPriority = 0;
12511            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12512                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12513            }
12514            if (intent.getPriority() > cappedPriority) {
12515                if (DEBUG_FILTERS) {
12516                    Slog.i(TAG, "Found matching filter(s);"
12517                            + " cap priority to " + cappedPriority + ";"
12518                            + " package: " + applicationInfo.packageName
12519                            + " activity: " + intent.activity.className
12520                            + " origPrio: " + intent.getPriority());
12521                }
12522                intent.setPriority(cappedPriority);
12523                return;
12524            }
12525            // all this for nothing; the requested priority was <= what was on the system
12526        }
12527
12528        public final void addActivity(PackageParser.Activity a, String type) {
12529            mActivities.put(a.getComponentName(), a);
12530            if (DEBUG_SHOW_INFO)
12531                Log.v(
12532                TAG, "  " + type + " " +
12533                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12534            if (DEBUG_SHOW_INFO)
12535                Log.v(TAG, "    Class=" + a.info.name);
12536            final int NI = a.intents.size();
12537            for (int j=0; j<NI; j++) {
12538                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12539                if ("activity".equals(type)) {
12540                    final PackageSetting ps =
12541                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12542                    final List<PackageParser.Activity> systemActivities =
12543                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12544                    adjustPriority(systemActivities, intent);
12545                }
12546                if (DEBUG_SHOW_INFO) {
12547                    Log.v(TAG, "    IntentFilter:");
12548                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12549                }
12550                if (!intent.debugCheck()) {
12551                    Log.w(TAG, "==> For Activity " + a.info.name);
12552                }
12553                addFilter(intent);
12554            }
12555        }
12556
12557        public final void removeActivity(PackageParser.Activity a, String type) {
12558            mActivities.remove(a.getComponentName());
12559            if (DEBUG_SHOW_INFO) {
12560                Log.v(TAG, "  " + type + " "
12561                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12562                                : a.info.name) + ":");
12563                Log.v(TAG, "    Class=" + a.info.name);
12564            }
12565            final int NI = a.intents.size();
12566            for (int j=0; j<NI; j++) {
12567                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12568                if (DEBUG_SHOW_INFO) {
12569                    Log.v(TAG, "    IntentFilter:");
12570                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12571                }
12572                removeFilter(intent);
12573            }
12574        }
12575
12576        @Override
12577        protected boolean allowFilterResult(
12578                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12579            ActivityInfo filterAi = filter.activity.info;
12580            for (int i=dest.size()-1; i>=0; i--) {
12581                ActivityInfo destAi = dest.get(i).activityInfo;
12582                if (destAi.name == filterAi.name
12583                        && destAi.packageName == filterAi.packageName) {
12584                    return false;
12585                }
12586            }
12587            return true;
12588        }
12589
12590        @Override
12591        protected ActivityIntentInfo[] newArray(int size) {
12592            return new ActivityIntentInfo[size];
12593        }
12594
12595        @Override
12596        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12597            if (!sUserManager.exists(userId)) return true;
12598            PackageParser.Package p = filter.activity.owner;
12599            if (p != null) {
12600                PackageSetting ps = (PackageSetting)p.mExtras;
12601                if (ps != null) {
12602                    // System apps are never considered stopped for purposes of
12603                    // filtering, because there may be no way for the user to
12604                    // actually re-launch them.
12605                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12606                            && ps.getStopped(userId);
12607                }
12608            }
12609            return false;
12610        }
12611
12612        @Override
12613        protected boolean isPackageForFilter(String packageName,
12614                PackageParser.ActivityIntentInfo info) {
12615            return packageName.equals(info.activity.owner.packageName);
12616        }
12617
12618        @Override
12619        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12620                int match, int userId) {
12621            if (!sUserManager.exists(userId)) return null;
12622            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12623                return null;
12624            }
12625            final PackageParser.Activity activity = info.activity;
12626            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12627            if (ps == null) {
12628                return null;
12629            }
12630            final PackageUserState userState = ps.readUserState(userId);
12631            ActivityInfo ai = generateActivityInfo(activity, mFlags, userState, userId);
12632            if (ai == null) {
12633                return null;
12634            }
12635            final boolean matchExplicitlyVisibleOnly =
12636                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12637            final boolean matchVisibleToInstantApp =
12638                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12639            final boolean componentVisible =
12640                    matchVisibleToInstantApp
12641                    && info.isVisibleToInstantApp()
12642                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12643            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12644            // throw out filters that aren't visible to ephemeral apps
12645            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12646                return null;
12647            }
12648            // throw out instant app filters if we're not explicitly requesting them
12649            if (!matchInstantApp && userState.instantApp) {
12650                return null;
12651            }
12652            // throw out instant app filters if updates are available; will trigger
12653            // instant app resolution
12654            if (userState.instantApp && ps.isUpdateAvailable()) {
12655                return null;
12656            }
12657            final ResolveInfo res = new ResolveInfo();
12658            res.activityInfo = ai;
12659            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12660                res.filter = info;
12661            }
12662            if (info != null) {
12663                res.handleAllWebDataURI = info.handleAllWebDataURI();
12664            }
12665            res.priority = info.getPriority();
12666            res.preferredOrder = activity.owner.mPreferredOrder;
12667            //System.out.println("Result: " + res.activityInfo.className +
12668            //                   " = " + res.priority);
12669            res.match = match;
12670            res.isDefault = info.hasDefault;
12671            res.labelRes = info.labelRes;
12672            res.nonLocalizedLabel = info.nonLocalizedLabel;
12673            if (userNeedsBadging(userId)) {
12674                res.noResourceId = true;
12675            } else {
12676                res.icon = info.icon;
12677            }
12678            res.iconResourceId = info.icon;
12679            res.system = res.activityInfo.applicationInfo.isSystemApp();
12680            res.isInstantAppAvailable = userState.instantApp;
12681            return res;
12682        }
12683
12684        @Override
12685        protected void sortResults(List<ResolveInfo> results) {
12686            Collections.sort(results, mResolvePrioritySorter);
12687        }
12688
12689        @Override
12690        protected void dumpFilter(PrintWriter out, String prefix,
12691                PackageParser.ActivityIntentInfo filter) {
12692            out.print(prefix); out.print(
12693                    Integer.toHexString(System.identityHashCode(filter.activity)));
12694                    out.print(' ');
12695                    filter.activity.printComponentShortName(out);
12696                    out.print(" filter ");
12697                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12698        }
12699
12700        @Override
12701        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12702            return filter.activity;
12703        }
12704
12705        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12706            PackageParser.Activity activity = (PackageParser.Activity)label;
12707            out.print(prefix); out.print(
12708                    Integer.toHexString(System.identityHashCode(activity)));
12709                    out.print(' ');
12710                    activity.printComponentShortName(out);
12711            if (count > 1) {
12712                out.print(" ("); out.print(count); out.print(" filters)");
12713            }
12714            out.println();
12715        }
12716
12717        // Keys are String (activity class name), values are Activity.
12718        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12719                = new ArrayMap<ComponentName, PackageParser.Activity>();
12720        private int mFlags;
12721    }
12722
12723    private final class ServiceIntentResolver
12724            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12725        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12726                boolean defaultOnly, int userId) {
12727            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12728            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12729        }
12730
12731        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12732                int userId) {
12733            if (!sUserManager.exists(userId)) return null;
12734            mFlags = flags;
12735            return super.queryIntent(intent, resolvedType,
12736                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12737                    userId);
12738        }
12739
12740        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12741                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12742            if (!sUserManager.exists(userId)) return null;
12743            if (packageServices == null) {
12744                return null;
12745            }
12746            mFlags = flags;
12747            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12748            final int N = packageServices.size();
12749            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12750                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12751
12752            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12753            for (int i = 0; i < N; ++i) {
12754                intentFilters = packageServices.get(i).intents;
12755                if (intentFilters != null && intentFilters.size() > 0) {
12756                    PackageParser.ServiceIntentInfo[] array =
12757                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12758                    intentFilters.toArray(array);
12759                    listCut.add(array);
12760                }
12761            }
12762            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12763        }
12764
12765        public final void addService(PackageParser.Service s) {
12766            mServices.put(s.getComponentName(), s);
12767            if (DEBUG_SHOW_INFO) {
12768                Log.v(TAG, "  "
12769                        + (s.info.nonLocalizedLabel != null
12770                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12771                Log.v(TAG, "    Class=" + s.info.name);
12772            }
12773            final int NI = s.intents.size();
12774            int j;
12775            for (j=0; j<NI; j++) {
12776                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12777                if (DEBUG_SHOW_INFO) {
12778                    Log.v(TAG, "    IntentFilter:");
12779                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12780                }
12781                if (!intent.debugCheck()) {
12782                    Log.w(TAG, "==> For Service " + s.info.name);
12783                }
12784                addFilter(intent);
12785            }
12786        }
12787
12788        public final void removeService(PackageParser.Service s) {
12789            mServices.remove(s.getComponentName());
12790            if (DEBUG_SHOW_INFO) {
12791                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12792                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12793                Log.v(TAG, "    Class=" + s.info.name);
12794            }
12795            final int NI = s.intents.size();
12796            int j;
12797            for (j=0; j<NI; j++) {
12798                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12799                if (DEBUG_SHOW_INFO) {
12800                    Log.v(TAG, "    IntentFilter:");
12801                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12802                }
12803                removeFilter(intent);
12804            }
12805        }
12806
12807        @Override
12808        protected boolean allowFilterResult(
12809                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12810            ServiceInfo filterSi = filter.service.info;
12811            for (int i=dest.size()-1; i>=0; i--) {
12812                ServiceInfo destAi = dest.get(i).serviceInfo;
12813                if (destAi.name == filterSi.name
12814                        && destAi.packageName == filterSi.packageName) {
12815                    return false;
12816                }
12817            }
12818            return true;
12819        }
12820
12821        @Override
12822        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12823            return new PackageParser.ServiceIntentInfo[size];
12824        }
12825
12826        @Override
12827        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12828            if (!sUserManager.exists(userId)) return true;
12829            PackageParser.Package p = filter.service.owner;
12830            if (p != null) {
12831                PackageSetting ps = (PackageSetting)p.mExtras;
12832                if (ps != null) {
12833                    // System apps are never considered stopped for purposes of
12834                    // filtering, because there may be no way for the user to
12835                    // actually re-launch them.
12836                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12837                            && ps.getStopped(userId);
12838                }
12839            }
12840            return false;
12841        }
12842
12843        @Override
12844        protected boolean isPackageForFilter(String packageName,
12845                PackageParser.ServiceIntentInfo info) {
12846            return packageName.equals(info.service.owner.packageName);
12847        }
12848
12849        @Override
12850        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12851                int match, int userId) {
12852            if (!sUserManager.exists(userId)) return null;
12853            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12854            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12855                return null;
12856            }
12857            final PackageParser.Service service = info.service;
12858            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12859            if (ps == null) {
12860                return null;
12861            }
12862            final PackageUserState userState = ps.readUserState(userId);
12863            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12864                    userState, userId);
12865            if (si == null) {
12866                return null;
12867            }
12868            final boolean matchVisibleToInstantApp =
12869                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12870            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12871            // throw out filters that aren't visible to ephemeral apps
12872            if (matchVisibleToInstantApp
12873                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12874                return null;
12875            }
12876            // throw out ephemeral filters if we're not explicitly requesting them
12877            if (!isInstantApp && userState.instantApp) {
12878                return null;
12879            }
12880            // throw out instant app filters if updates are available; will trigger
12881            // instant app resolution
12882            if (userState.instantApp && ps.isUpdateAvailable()) {
12883                return null;
12884            }
12885            final ResolveInfo res = new ResolveInfo();
12886            res.serviceInfo = si;
12887            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12888                res.filter = filter;
12889            }
12890            res.priority = info.getPriority();
12891            res.preferredOrder = service.owner.mPreferredOrder;
12892            res.match = match;
12893            res.isDefault = info.hasDefault;
12894            res.labelRes = info.labelRes;
12895            res.nonLocalizedLabel = info.nonLocalizedLabel;
12896            res.icon = info.icon;
12897            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12898            return res;
12899        }
12900
12901        @Override
12902        protected void sortResults(List<ResolveInfo> results) {
12903            Collections.sort(results, mResolvePrioritySorter);
12904        }
12905
12906        @Override
12907        protected void dumpFilter(PrintWriter out, String prefix,
12908                PackageParser.ServiceIntentInfo filter) {
12909            out.print(prefix); out.print(
12910                    Integer.toHexString(System.identityHashCode(filter.service)));
12911                    out.print(' ');
12912                    filter.service.printComponentShortName(out);
12913                    out.print(" filter ");
12914                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12915        }
12916
12917        @Override
12918        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12919            return filter.service;
12920        }
12921
12922        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12923            PackageParser.Service service = (PackageParser.Service)label;
12924            out.print(prefix); out.print(
12925                    Integer.toHexString(System.identityHashCode(service)));
12926                    out.print(' ');
12927                    service.printComponentShortName(out);
12928            if (count > 1) {
12929                out.print(" ("); out.print(count); out.print(" filters)");
12930            }
12931            out.println();
12932        }
12933
12934//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12935//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12936//            final List<ResolveInfo> retList = Lists.newArrayList();
12937//            while (i.hasNext()) {
12938//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12939//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12940//                    retList.add(resolveInfo);
12941//                }
12942//            }
12943//            return retList;
12944//        }
12945
12946        // Keys are String (activity class name), values are Activity.
12947        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12948                = new ArrayMap<ComponentName, PackageParser.Service>();
12949        private int mFlags;
12950    }
12951
12952    private final class ProviderIntentResolver
12953            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12954        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12955                boolean defaultOnly, int userId) {
12956            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12957            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12958        }
12959
12960        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12961                int userId) {
12962            if (!sUserManager.exists(userId))
12963                return null;
12964            mFlags = flags;
12965            return super.queryIntent(intent, resolvedType,
12966                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12967                    userId);
12968        }
12969
12970        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12971                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12972            if (!sUserManager.exists(userId))
12973                return null;
12974            if (packageProviders == null) {
12975                return null;
12976            }
12977            mFlags = flags;
12978            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12979            final int N = packageProviders.size();
12980            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12981                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12982
12983            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12984            for (int i = 0; i < N; ++i) {
12985                intentFilters = packageProviders.get(i).intents;
12986                if (intentFilters != null && intentFilters.size() > 0) {
12987                    PackageParser.ProviderIntentInfo[] array =
12988                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12989                    intentFilters.toArray(array);
12990                    listCut.add(array);
12991                }
12992            }
12993            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12994        }
12995
12996        public final void addProvider(PackageParser.Provider p) {
12997            if (mProviders.containsKey(p.getComponentName())) {
12998                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12999                return;
13000            }
13001
13002            mProviders.put(p.getComponentName(), p);
13003            if (DEBUG_SHOW_INFO) {
13004                Log.v(TAG, "  "
13005                        + (p.info.nonLocalizedLabel != null
13006                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13007                Log.v(TAG, "    Class=" + p.info.name);
13008            }
13009            final int NI = p.intents.size();
13010            int j;
13011            for (j = 0; j < NI; j++) {
13012                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13013                if (DEBUG_SHOW_INFO) {
13014                    Log.v(TAG, "    IntentFilter:");
13015                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13016                }
13017                if (!intent.debugCheck()) {
13018                    Log.w(TAG, "==> For Provider " + p.info.name);
13019                }
13020                addFilter(intent);
13021            }
13022        }
13023
13024        public final void removeProvider(PackageParser.Provider p) {
13025            mProviders.remove(p.getComponentName());
13026            if (DEBUG_SHOW_INFO) {
13027                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13028                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13029                Log.v(TAG, "    Class=" + p.info.name);
13030            }
13031            final int NI = p.intents.size();
13032            int j;
13033            for (j = 0; j < NI; j++) {
13034                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13035                if (DEBUG_SHOW_INFO) {
13036                    Log.v(TAG, "    IntentFilter:");
13037                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13038                }
13039                removeFilter(intent);
13040            }
13041        }
13042
13043        @Override
13044        protected boolean allowFilterResult(
13045                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13046            ProviderInfo filterPi = filter.provider.info;
13047            for (int i = dest.size() - 1; i >= 0; i--) {
13048                ProviderInfo destPi = dest.get(i).providerInfo;
13049                if (destPi.name == filterPi.name
13050                        && destPi.packageName == filterPi.packageName) {
13051                    return false;
13052                }
13053            }
13054            return true;
13055        }
13056
13057        @Override
13058        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13059            return new PackageParser.ProviderIntentInfo[size];
13060        }
13061
13062        @Override
13063        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13064            if (!sUserManager.exists(userId))
13065                return true;
13066            PackageParser.Package p = filter.provider.owner;
13067            if (p != null) {
13068                PackageSetting ps = (PackageSetting) p.mExtras;
13069                if (ps != null) {
13070                    // System apps are never considered stopped for purposes of
13071                    // filtering, because there may be no way for the user to
13072                    // actually re-launch them.
13073                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13074                            && ps.getStopped(userId);
13075                }
13076            }
13077            return false;
13078        }
13079
13080        @Override
13081        protected boolean isPackageForFilter(String packageName,
13082                PackageParser.ProviderIntentInfo info) {
13083            return packageName.equals(info.provider.owner.packageName);
13084        }
13085
13086        @Override
13087        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13088                int match, int userId) {
13089            if (!sUserManager.exists(userId))
13090                return null;
13091            final PackageParser.ProviderIntentInfo info = filter;
13092            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13093                return null;
13094            }
13095            final PackageParser.Provider provider = info.provider;
13096            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13097            if (ps == null) {
13098                return null;
13099            }
13100            final PackageUserState userState = ps.readUserState(userId);
13101            final boolean matchVisibleToInstantApp =
13102                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13103            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13104            // throw out filters that aren't visible to instant applications
13105            if (matchVisibleToInstantApp
13106                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13107                return null;
13108            }
13109            // throw out instant application filters if we're not explicitly requesting them
13110            if (!isInstantApp && userState.instantApp) {
13111                return null;
13112            }
13113            // throw out instant application filters if updates are available; will trigger
13114            // instant application resolution
13115            if (userState.instantApp && ps.isUpdateAvailable()) {
13116                return null;
13117            }
13118            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13119                    userState, userId);
13120            if (pi == null) {
13121                return null;
13122            }
13123            final ResolveInfo res = new ResolveInfo();
13124            res.providerInfo = pi;
13125            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13126                res.filter = filter;
13127            }
13128            res.priority = info.getPriority();
13129            res.preferredOrder = provider.owner.mPreferredOrder;
13130            res.match = match;
13131            res.isDefault = info.hasDefault;
13132            res.labelRes = info.labelRes;
13133            res.nonLocalizedLabel = info.nonLocalizedLabel;
13134            res.icon = info.icon;
13135            res.system = res.providerInfo.applicationInfo.isSystemApp();
13136            return res;
13137        }
13138
13139        @Override
13140        protected void sortResults(List<ResolveInfo> results) {
13141            Collections.sort(results, mResolvePrioritySorter);
13142        }
13143
13144        @Override
13145        protected void dumpFilter(PrintWriter out, String prefix,
13146                PackageParser.ProviderIntentInfo filter) {
13147            out.print(prefix);
13148            out.print(
13149                    Integer.toHexString(System.identityHashCode(filter.provider)));
13150            out.print(' ');
13151            filter.provider.printComponentShortName(out);
13152            out.print(" filter ");
13153            out.println(Integer.toHexString(System.identityHashCode(filter)));
13154        }
13155
13156        @Override
13157        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13158            return filter.provider;
13159        }
13160
13161        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13162            PackageParser.Provider provider = (PackageParser.Provider)label;
13163            out.print(prefix); out.print(
13164                    Integer.toHexString(System.identityHashCode(provider)));
13165                    out.print(' ');
13166                    provider.printComponentShortName(out);
13167            if (count > 1) {
13168                out.print(" ("); out.print(count); out.print(" filters)");
13169            }
13170            out.println();
13171        }
13172
13173        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13174                = new ArrayMap<ComponentName, PackageParser.Provider>();
13175        private int mFlags;
13176    }
13177
13178    static final class EphemeralIntentResolver
13179            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13180        /**
13181         * The result that has the highest defined order. Ordering applies on a
13182         * per-package basis. Mapping is from package name to Pair of order and
13183         * EphemeralResolveInfo.
13184         * <p>
13185         * NOTE: This is implemented as a field variable for convenience and efficiency.
13186         * By having a field variable, we're able to track filter ordering as soon as
13187         * a non-zero order is defined. Otherwise, multiple loops across the result set
13188         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13189         * this needs to be contained entirely within {@link #filterResults}.
13190         */
13191        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13192
13193        @Override
13194        protected AuxiliaryResolveInfo[] newArray(int size) {
13195            return new AuxiliaryResolveInfo[size];
13196        }
13197
13198        @Override
13199        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13200            return true;
13201        }
13202
13203        @Override
13204        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13205                int userId) {
13206            if (!sUserManager.exists(userId)) {
13207                return null;
13208            }
13209            final String packageName = responseObj.resolveInfo.getPackageName();
13210            final Integer order = responseObj.getOrder();
13211            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13212                    mOrderResult.get(packageName);
13213            // ordering is enabled and this item's order isn't high enough
13214            if (lastOrderResult != null && lastOrderResult.first >= order) {
13215                return null;
13216            }
13217            final InstantAppResolveInfo res = responseObj.resolveInfo;
13218            if (order > 0) {
13219                // non-zero order, enable ordering
13220                mOrderResult.put(packageName, new Pair<>(order, res));
13221            }
13222            return responseObj;
13223        }
13224
13225        @Override
13226        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13227            // only do work if ordering is enabled [most of the time it won't be]
13228            if (mOrderResult.size() == 0) {
13229                return;
13230            }
13231            int resultSize = results.size();
13232            for (int i = 0; i < resultSize; i++) {
13233                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13234                final String packageName = info.getPackageName();
13235                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13236                if (savedInfo == null) {
13237                    // package doesn't having ordering
13238                    continue;
13239                }
13240                if (savedInfo.second == info) {
13241                    // circled back to the highest ordered item; remove from order list
13242                    mOrderResult.remove(savedInfo);
13243                    if (mOrderResult.size() == 0) {
13244                        // no more ordered items
13245                        break;
13246                    }
13247                    continue;
13248                }
13249                // item has a worse order, remove it from the result list
13250                results.remove(i);
13251                resultSize--;
13252                i--;
13253            }
13254        }
13255    }
13256
13257    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13258            new Comparator<ResolveInfo>() {
13259        public int compare(ResolveInfo r1, ResolveInfo r2) {
13260            int v1 = r1.priority;
13261            int v2 = r2.priority;
13262            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13263            if (v1 != v2) {
13264                return (v1 > v2) ? -1 : 1;
13265            }
13266            v1 = r1.preferredOrder;
13267            v2 = r2.preferredOrder;
13268            if (v1 != v2) {
13269                return (v1 > v2) ? -1 : 1;
13270            }
13271            if (r1.isDefault != r2.isDefault) {
13272                return r1.isDefault ? -1 : 1;
13273            }
13274            v1 = r1.match;
13275            v2 = r2.match;
13276            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13277            if (v1 != v2) {
13278                return (v1 > v2) ? -1 : 1;
13279            }
13280            if (r1.system != r2.system) {
13281                return r1.system ? -1 : 1;
13282            }
13283            if (r1.activityInfo != null) {
13284                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13285            }
13286            if (r1.serviceInfo != null) {
13287                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13288            }
13289            if (r1.providerInfo != null) {
13290                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13291            }
13292            return 0;
13293        }
13294    };
13295
13296    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13297            new Comparator<ProviderInfo>() {
13298        public int compare(ProviderInfo p1, ProviderInfo p2) {
13299            final int v1 = p1.initOrder;
13300            final int v2 = p2.initOrder;
13301            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13302        }
13303    };
13304
13305    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13306            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13307            final int[] userIds) {
13308        mHandler.post(new Runnable() {
13309            @Override
13310            public void run() {
13311                try {
13312                    final IActivityManager am = ActivityManager.getService();
13313                    if (am == null) return;
13314                    final int[] resolvedUserIds;
13315                    if (userIds == null) {
13316                        resolvedUserIds = am.getRunningUserIds();
13317                    } else {
13318                        resolvedUserIds = userIds;
13319                    }
13320                    for (int id : resolvedUserIds) {
13321                        final Intent intent = new Intent(action,
13322                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13323                        if (extras != null) {
13324                            intent.putExtras(extras);
13325                        }
13326                        if (targetPkg != null) {
13327                            intent.setPackage(targetPkg);
13328                        }
13329                        // Modify the UID when posting to other users
13330                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13331                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
13332                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13333                            intent.putExtra(Intent.EXTRA_UID, uid);
13334                        }
13335                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13336                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13337                        if (DEBUG_BROADCASTS) {
13338                            RuntimeException here = new RuntimeException("here");
13339                            here.fillInStackTrace();
13340                            Slog.d(TAG, "Sending to user " + id + ": "
13341                                    + intent.toShortString(false, true, false, false)
13342                                    + " " + intent.getExtras(), here);
13343                        }
13344                        am.broadcastIntent(null, intent, null, finishedReceiver,
13345                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
13346                                null, finishedReceiver != null, false, id);
13347                    }
13348                } catch (RemoteException ex) {
13349                }
13350            }
13351        });
13352    }
13353
13354    /**
13355     * Check if the external storage media is available. This is true if there
13356     * is a mounted external storage medium or if the external storage is
13357     * emulated.
13358     */
13359    private boolean isExternalMediaAvailable() {
13360        return mMediaMounted || Environment.isExternalStorageEmulated();
13361    }
13362
13363    @Override
13364    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13365        // writer
13366        synchronized (mPackages) {
13367            if (!isExternalMediaAvailable()) {
13368                // If the external storage is no longer mounted at this point,
13369                // the caller may not have been able to delete all of this
13370                // packages files and can not delete any more.  Bail.
13371                return null;
13372            }
13373            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13374            if (lastPackage != null) {
13375                pkgs.remove(lastPackage);
13376            }
13377            if (pkgs.size() > 0) {
13378                return pkgs.get(0);
13379            }
13380        }
13381        return null;
13382    }
13383
13384    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13385        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13386                userId, andCode ? 1 : 0, packageName);
13387        if (mSystemReady) {
13388            msg.sendToTarget();
13389        } else {
13390            if (mPostSystemReadyMessages == null) {
13391                mPostSystemReadyMessages = new ArrayList<>();
13392            }
13393            mPostSystemReadyMessages.add(msg);
13394        }
13395    }
13396
13397    void startCleaningPackages() {
13398        // reader
13399        if (!isExternalMediaAvailable()) {
13400            return;
13401        }
13402        synchronized (mPackages) {
13403            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13404                return;
13405            }
13406        }
13407        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13408        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13409        IActivityManager am = ActivityManager.getService();
13410        if (am != null) {
13411            int dcsUid = -1;
13412            synchronized (mPackages) {
13413                if (!mDefaultContainerWhitelisted) {
13414                    mDefaultContainerWhitelisted = true;
13415                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13416                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13417                }
13418            }
13419            try {
13420                if (dcsUid > 0) {
13421                    am.backgroundWhitelistUid(dcsUid);
13422                }
13423                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13424                        UserHandle.USER_SYSTEM);
13425            } catch (RemoteException e) {
13426            }
13427        }
13428    }
13429
13430    @Override
13431    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
13432            int installFlags, String installerPackageName, int userId) {
13433        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
13434
13435        final int callingUid = Binder.getCallingUid();
13436        enforceCrossUserPermission(callingUid, userId,
13437                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
13438
13439        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13440            try {
13441                if (observer != null) {
13442                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
13443                }
13444            } catch (RemoteException re) {
13445            }
13446            return;
13447        }
13448
13449        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
13450            installFlags |= PackageManager.INSTALL_FROM_ADB;
13451
13452        } else {
13453            // Caller holds INSTALL_PACKAGES permission, so we're less strict
13454            // about installerPackageName.
13455
13456            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
13457            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
13458        }
13459
13460        UserHandle user;
13461        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
13462            user = UserHandle.ALL;
13463        } else {
13464            user = new UserHandle(userId);
13465        }
13466
13467        // Only system components can circumvent runtime permissions when installing.
13468        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
13469                && mContext.checkCallingOrSelfPermission(Manifest.permission
13470                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
13471            throw new SecurityException("You need the "
13472                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
13473                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
13474        }
13475
13476        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
13477                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13478            throw new IllegalArgumentException(
13479                    "New installs into ASEC containers no longer supported");
13480        }
13481
13482        final File originFile = new File(originPath);
13483        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
13484
13485        final Message msg = mHandler.obtainMessage(INIT_COPY);
13486        final VerificationInfo verificationInfo = new VerificationInfo(
13487                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
13488        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
13489                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
13490                null /*packageAbiOverride*/, null /*grantedPermissions*/,
13491                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
13492        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
13493        msg.obj = params;
13494
13495        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
13496                System.identityHashCode(msg.obj));
13497        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13498                System.identityHashCode(msg.obj));
13499
13500        mHandler.sendMessage(msg);
13501    }
13502
13503
13504    /**
13505     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13506     * it is acting on behalf on an enterprise or the user).
13507     *
13508     * Note that the ordering of the conditionals in this method is important. The checks we perform
13509     * are as follows, in this order:
13510     *
13511     * 1) If the install is being performed by a system app, we can trust the app to have set the
13512     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13513     *    what it is.
13514     * 2) If the install is being performed by a device or profile owner app, the install reason
13515     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13516     *    set the install reason correctly. If the app targets an older SDK version where install
13517     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13518     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13519     * 3) In all other cases, the install is being performed by a regular app that is neither part
13520     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13521     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13522     *    set to enterprise policy and if so, change it to unknown instead.
13523     */
13524    private int fixUpInstallReason(String installerPackageName, int installerUid,
13525            int installReason) {
13526        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13527                == PERMISSION_GRANTED) {
13528            // If the install is being performed by a system app, we trust that app to have set the
13529            // install reason correctly.
13530            return installReason;
13531        }
13532
13533        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13534            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13535        if (dpm != null) {
13536            ComponentName owner = null;
13537            try {
13538                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13539                if (owner == null) {
13540                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13541                }
13542            } catch (RemoteException e) {
13543            }
13544            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13545                // If the install is being performed by a device or profile owner, the install
13546                // reason should be enterprise policy.
13547                return PackageManager.INSTALL_REASON_POLICY;
13548            }
13549        }
13550
13551        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13552            // If the install is being performed by a regular app (i.e. neither system app nor
13553            // device or profile owner), we have no reason to believe that the app is acting on
13554            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13555            // change it to unknown instead.
13556            return PackageManager.INSTALL_REASON_UNKNOWN;
13557        }
13558
13559        // If the install is being performed by a regular app and the install reason was set to any
13560        // value but enterprise policy, leave the install reason unchanged.
13561        return installReason;
13562    }
13563
13564    void installStage(String packageName, File stagedDir, String stagedCid,
13565            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13566            String installerPackageName, int installerUid, UserHandle user,
13567            Certificate[][] certificates) {
13568        if (DEBUG_EPHEMERAL) {
13569            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13570                Slog.d(TAG, "Ephemeral install of " + packageName);
13571            }
13572        }
13573        final VerificationInfo verificationInfo = new VerificationInfo(
13574                sessionParams.originatingUri, sessionParams.referrerUri,
13575                sessionParams.originatingUid, installerUid);
13576
13577        final OriginInfo origin;
13578        if (stagedDir != null) {
13579            origin = OriginInfo.fromStagedFile(stagedDir);
13580        } else {
13581            origin = OriginInfo.fromStagedContainer(stagedCid);
13582        }
13583
13584        final Message msg = mHandler.obtainMessage(INIT_COPY);
13585        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13586                sessionParams.installReason);
13587        final InstallParams params = new InstallParams(origin, null, observer,
13588                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13589                verificationInfo, user, sessionParams.abiOverride,
13590                sessionParams.grantedRuntimePermissions, certificates, installReason);
13591        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13592        msg.obj = params;
13593
13594        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13595                System.identityHashCode(msg.obj));
13596        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13597                System.identityHashCode(msg.obj));
13598
13599        mHandler.sendMessage(msg);
13600    }
13601
13602    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13603            int userId) {
13604        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13605        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13606    }
13607
13608    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
13609        if (ArrayUtils.isEmpty(userIds)) {
13610            return;
13611        }
13612        Bundle extras = new Bundle(1);
13613        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13614        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13615
13616        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13617                packageName, extras, 0, null, null, userIds);
13618        if (isSystem) {
13619            mHandler.post(() -> {
13620                        for (int userId : userIds) {
13621                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13622                        }
13623                    }
13624            );
13625        }
13626    }
13627
13628    /**
13629     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13630     * automatically without needing an explicit launch.
13631     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13632     */
13633    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13634        // If user is not running, the app didn't miss any broadcast
13635        if (!mUserManagerInternal.isUserRunning(userId)) {
13636            return;
13637        }
13638        final IActivityManager am = ActivityManager.getService();
13639        try {
13640            // Deliver LOCKED_BOOT_COMPLETED first
13641            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13642                    .setPackage(packageName);
13643            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13644            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13645                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13646
13647            // Deliver BOOT_COMPLETED only if user is unlocked
13648            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13649                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13650                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13651                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13652            }
13653        } catch (RemoteException e) {
13654            throw e.rethrowFromSystemServer();
13655        }
13656    }
13657
13658    @Override
13659    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13660            int userId) {
13661        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13662        PackageSetting pkgSetting;
13663        final int uid = Binder.getCallingUid();
13664        enforceCrossUserPermission(uid, userId,
13665                true /* requireFullPermission */, true /* checkShell */,
13666                "setApplicationHiddenSetting for user " + userId);
13667
13668        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13669            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13670            return false;
13671        }
13672
13673        long callingId = Binder.clearCallingIdentity();
13674        try {
13675            boolean sendAdded = false;
13676            boolean sendRemoved = false;
13677            // writer
13678            synchronized (mPackages) {
13679                pkgSetting = mSettings.mPackages.get(packageName);
13680                if (pkgSetting == null) {
13681                    return false;
13682                }
13683                // Do not allow "android" is being disabled
13684                if ("android".equals(packageName)) {
13685                    Slog.w(TAG, "Cannot hide package: android");
13686                    return false;
13687                }
13688                // Cannot hide static shared libs as they are considered
13689                // a part of the using app (emulating static linking). Also
13690                // static libs are installed always on internal storage.
13691                PackageParser.Package pkg = mPackages.get(packageName);
13692                if (pkg != null && pkg.staticSharedLibName != null) {
13693                    Slog.w(TAG, "Cannot hide package: " + packageName
13694                            + " providing static shared library: "
13695                            + pkg.staticSharedLibName);
13696                    return false;
13697                }
13698                // Only allow protected packages to hide themselves.
13699                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13700                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13701                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13702                    return false;
13703                }
13704
13705                if (pkgSetting.getHidden(userId) != hidden) {
13706                    pkgSetting.setHidden(hidden, userId);
13707                    mSettings.writePackageRestrictionsLPr(userId);
13708                    if (hidden) {
13709                        sendRemoved = true;
13710                    } else {
13711                        sendAdded = true;
13712                    }
13713                }
13714            }
13715            if (sendAdded) {
13716                sendPackageAddedForUser(packageName, pkgSetting, userId);
13717                return true;
13718            }
13719            if (sendRemoved) {
13720                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13721                        "hiding pkg");
13722                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13723                return true;
13724            }
13725        } finally {
13726            Binder.restoreCallingIdentity(callingId);
13727        }
13728        return false;
13729    }
13730
13731    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13732            int userId) {
13733        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13734        info.removedPackage = packageName;
13735        info.installerPackageName = pkgSetting.installerPackageName;
13736        info.removedUsers = new int[] {userId};
13737        info.broadcastUsers = new int[] {userId};
13738        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13739        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13740    }
13741
13742    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13743        if (pkgList.length > 0) {
13744            Bundle extras = new Bundle(1);
13745            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13746
13747            sendPackageBroadcast(
13748                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13749                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13750                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13751                    new int[] {userId});
13752        }
13753    }
13754
13755    /**
13756     * Returns true if application is not found or there was an error. Otherwise it returns
13757     * the hidden state of the package for the given user.
13758     */
13759    @Override
13760    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13761        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13762        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13763                true /* requireFullPermission */, false /* checkShell */,
13764                "getApplicationHidden for user " + userId);
13765        PackageSetting pkgSetting;
13766        long callingId = Binder.clearCallingIdentity();
13767        try {
13768            // writer
13769            synchronized (mPackages) {
13770                pkgSetting = mSettings.mPackages.get(packageName);
13771                if (pkgSetting == null) {
13772                    return true;
13773                }
13774                return pkgSetting.getHidden(userId);
13775            }
13776        } finally {
13777            Binder.restoreCallingIdentity(callingId);
13778        }
13779    }
13780
13781    /**
13782     * @hide
13783     */
13784    @Override
13785    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13786            int installReason) {
13787        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13788                null);
13789        PackageSetting pkgSetting;
13790        final int uid = Binder.getCallingUid();
13791        enforceCrossUserPermission(uid, userId,
13792                true /* requireFullPermission */, true /* checkShell */,
13793                "installExistingPackage for user " + userId);
13794        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13795            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13796        }
13797
13798        long callingId = Binder.clearCallingIdentity();
13799        try {
13800            boolean installed = false;
13801            final boolean instantApp =
13802                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13803            final boolean fullApp =
13804                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13805
13806            // writer
13807            synchronized (mPackages) {
13808                pkgSetting = mSettings.mPackages.get(packageName);
13809                if (pkgSetting == null) {
13810                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13811                }
13812                if (!pkgSetting.getInstalled(userId)) {
13813                    pkgSetting.setInstalled(true, userId);
13814                    pkgSetting.setHidden(false, userId);
13815                    pkgSetting.setInstallReason(installReason, userId);
13816                    mSettings.writePackageRestrictionsLPr(userId);
13817                    mSettings.writeKernelMappingLPr(pkgSetting);
13818                    installed = true;
13819                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13820                    // upgrade app from instant to full; we don't allow app downgrade
13821                    installed = true;
13822                }
13823                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13824            }
13825
13826            if (installed) {
13827                if (pkgSetting.pkg != null) {
13828                    synchronized (mInstallLock) {
13829                        // We don't need to freeze for a brand new install
13830                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13831                    }
13832                }
13833                sendPackageAddedForUser(packageName, pkgSetting, userId);
13834                synchronized (mPackages) {
13835                    updateSequenceNumberLP(packageName, new int[]{ userId });
13836                }
13837            }
13838        } finally {
13839            Binder.restoreCallingIdentity(callingId);
13840        }
13841
13842        return PackageManager.INSTALL_SUCCEEDED;
13843    }
13844
13845    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13846            boolean instantApp, boolean fullApp) {
13847        // no state specified; do nothing
13848        if (!instantApp && !fullApp) {
13849            return;
13850        }
13851        if (userId != UserHandle.USER_ALL) {
13852            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13853                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13854            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13855                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13856            }
13857        } else {
13858            for (int currentUserId : sUserManager.getUserIds()) {
13859                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13860                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13861                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13862                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13863                }
13864            }
13865        }
13866    }
13867
13868    boolean isUserRestricted(int userId, String restrictionKey) {
13869        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13870        if (restrictions.getBoolean(restrictionKey, false)) {
13871            Log.w(TAG, "User is restricted: " + restrictionKey);
13872            return true;
13873        }
13874        return false;
13875    }
13876
13877    @Override
13878    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13879            int userId) {
13880        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13881        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13882                true /* requireFullPermission */, true /* checkShell */,
13883                "setPackagesSuspended for user " + userId);
13884
13885        if (ArrayUtils.isEmpty(packageNames)) {
13886            return packageNames;
13887        }
13888
13889        // List of package names for whom the suspended state has changed.
13890        List<String> changedPackages = new ArrayList<>(packageNames.length);
13891        // List of package names for whom the suspended state is not set as requested in this
13892        // method.
13893        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13894        long callingId = Binder.clearCallingIdentity();
13895        try {
13896            for (int i = 0; i < packageNames.length; i++) {
13897                String packageName = packageNames[i];
13898                boolean changed = false;
13899                final int appId;
13900                synchronized (mPackages) {
13901                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13902                    if (pkgSetting == null) {
13903                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13904                                + "\". Skipping suspending/un-suspending.");
13905                        unactionedPackages.add(packageName);
13906                        continue;
13907                    }
13908                    appId = pkgSetting.appId;
13909                    if (pkgSetting.getSuspended(userId) != suspended) {
13910                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13911                            unactionedPackages.add(packageName);
13912                            continue;
13913                        }
13914                        pkgSetting.setSuspended(suspended, userId);
13915                        mSettings.writePackageRestrictionsLPr(userId);
13916                        changed = true;
13917                        changedPackages.add(packageName);
13918                    }
13919                }
13920
13921                if (changed && suspended) {
13922                    killApplication(packageName, UserHandle.getUid(userId, appId),
13923                            "suspending package");
13924                }
13925            }
13926        } finally {
13927            Binder.restoreCallingIdentity(callingId);
13928        }
13929
13930        if (!changedPackages.isEmpty()) {
13931            sendPackagesSuspendedForUser(changedPackages.toArray(
13932                    new String[changedPackages.size()]), userId, suspended);
13933        }
13934
13935        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13936    }
13937
13938    @Override
13939    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13940        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13941                true /* requireFullPermission */, false /* checkShell */,
13942                "isPackageSuspendedForUser for user " + userId);
13943        synchronized (mPackages) {
13944            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13945            if (pkgSetting == null) {
13946                throw new IllegalArgumentException("Unknown target package: " + packageName);
13947            }
13948            return pkgSetting.getSuspended(userId);
13949        }
13950    }
13951
13952    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13953        if (isPackageDeviceAdmin(packageName, userId)) {
13954            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13955                    + "\": has an active device admin");
13956            return false;
13957        }
13958
13959        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13960        if (packageName.equals(activeLauncherPackageName)) {
13961            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13962                    + "\": contains the active launcher");
13963            return false;
13964        }
13965
13966        if (packageName.equals(mRequiredInstallerPackage)) {
13967            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13968                    + "\": required for package installation");
13969            return false;
13970        }
13971
13972        if (packageName.equals(mRequiredUninstallerPackage)) {
13973            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13974                    + "\": required for package uninstallation");
13975            return false;
13976        }
13977
13978        if (packageName.equals(mRequiredVerifierPackage)) {
13979            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13980                    + "\": required for package verification");
13981            return false;
13982        }
13983
13984        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13985            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13986                    + "\": is the default dialer");
13987            return false;
13988        }
13989
13990        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13991            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13992                    + "\": protected package");
13993            return false;
13994        }
13995
13996        // Cannot suspend static shared libs as they are considered
13997        // a part of the using app (emulating static linking). Also
13998        // static libs are installed always on internal storage.
13999        PackageParser.Package pkg = mPackages.get(packageName);
14000        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14001            Slog.w(TAG, "Cannot suspend package: " + packageName
14002                    + " providing static shared library: "
14003                    + pkg.staticSharedLibName);
14004            return false;
14005        }
14006
14007        return true;
14008    }
14009
14010    private String getActiveLauncherPackageName(int userId) {
14011        Intent intent = new Intent(Intent.ACTION_MAIN);
14012        intent.addCategory(Intent.CATEGORY_HOME);
14013        ResolveInfo resolveInfo = resolveIntent(
14014                intent,
14015                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14016                PackageManager.MATCH_DEFAULT_ONLY,
14017                userId);
14018
14019        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14020    }
14021
14022    private String getDefaultDialerPackageName(int userId) {
14023        synchronized (mPackages) {
14024            return mSettings.getDefaultDialerPackageNameLPw(userId);
14025        }
14026    }
14027
14028    @Override
14029    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14030        mContext.enforceCallingOrSelfPermission(
14031                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14032                "Only package verification agents can verify applications");
14033
14034        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14035        final PackageVerificationResponse response = new PackageVerificationResponse(
14036                verificationCode, Binder.getCallingUid());
14037        msg.arg1 = id;
14038        msg.obj = response;
14039        mHandler.sendMessage(msg);
14040    }
14041
14042    @Override
14043    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14044            long millisecondsToDelay) {
14045        mContext.enforceCallingOrSelfPermission(
14046                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14047                "Only package verification agents can extend verification timeouts");
14048
14049        final PackageVerificationState state = mPendingVerification.get(id);
14050        final PackageVerificationResponse response = new PackageVerificationResponse(
14051                verificationCodeAtTimeout, Binder.getCallingUid());
14052
14053        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14054            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14055        }
14056        if (millisecondsToDelay < 0) {
14057            millisecondsToDelay = 0;
14058        }
14059        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14060                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14061            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14062        }
14063
14064        if ((state != null) && !state.timeoutExtended()) {
14065            state.extendTimeout();
14066
14067            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14068            msg.arg1 = id;
14069            msg.obj = response;
14070            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14071        }
14072    }
14073
14074    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14075            int verificationCode, UserHandle user) {
14076        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14077        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14078        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14079        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14080        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14081
14082        mContext.sendBroadcastAsUser(intent, user,
14083                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14084    }
14085
14086    private ComponentName matchComponentForVerifier(String packageName,
14087            List<ResolveInfo> receivers) {
14088        ActivityInfo targetReceiver = null;
14089
14090        final int NR = receivers.size();
14091        for (int i = 0; i < NR; i++) {
14092            final ResolveInfo info = receivers.get(i);
14093            if (info.activityInfo == null) {
14094                continue;
14095            }
14096
14097            if (packageName.equals(info.activityInfo.packageName)) {
14098                targetReceiver = info.activityInfo;
14099                break;
14100            }
14101        }
14102
14103        if (targetReceiver == null) {
14104            return null;
14105        }
14106
14107        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14108    }
14109
14110    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14111            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14112        if (pkgInfo.verifiers.length == 0) {
14113            return null;
14114        }
14115
14116        final int N = pkgInfo.verifiers.length;
14117        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14118        for (int i = 0; i < N; i++) {
14119            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14120
14121            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14122                    receivers);
14123            if (comp == null) {
14124                continue;
14125            }
14126
14127            final int verifierUid = getUidForVerifier(verifierInfo);
14128            if (verifierUid == -1) {
14129                continue;
14130            }
14131
14132            if (DEBUG_VERIFY) {
14133                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14134                        + " with the correct signature");
14135            }
14136            sufficientVerifiers.add(comp);
14137            verificationState.addSufficientVerifier(verifierUid);
14138        }
14139
14140        return sufficientVerifiers;
14141    }
14142
14143    private int getUidForVerifier(VerifierInfo verifierInfo) {
14144        synchronized (mPackages) {
14145            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14146            if (pkg == null) {
14147                return -1;
14148            } else if (pkg.mSignatures.length != 1) {
14149                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14150                        + " has more than one signature; ignoring");
14151                return -1;
14152            }
14153
14154            /*
14155             * If the public key of the package's signature does not match
14156             * our expected public key, then this is a different package and
14157             * we should skip.
14158             */
14159
14160            final byte[] expectedPublicKey;
14161            try {
14162                final Signature verifierSig = pkg.mSignatures[0];
14163                final PublicKey publicKey = verifierSig.getPublicKey();
14164                expectedPublicKey = publicKey.getEncoded();
14165            } catch (CertificateException e) {
14166                return -1;
14167            }
14168
14169            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14170
14171            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14172                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14173                        + " does not have the expected public key; ignoring");
14174                return -1;
14175            }
14176
14177            return pkg.applicationInfo.uid;
14178        }
14179    }
14180
14181    @Override
14182    public void finishPackageInstall(int token, boolean didLaunch) {
14183        enforceSystemOrRoot("Only the system is allowed to finish installs");
14184
14185        if (DEBUG_INSTALL) {
14186            Slog.v(TAG, "BM finishing package install for " + token);
14187        }
14188        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14189
14190        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14191        mHandler.sendMessage(msg);
14192    }
14193
14194    /**
14195     * Get the verification agent timeout.  Used for both the APK verifier and the
14196     * intent filter verifier.
14197     *
14198     * @return verification timeout in milliseconds
14199     */
14200    private long getVerificationTimeout() {
14201        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14202                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14203                DEFAULT_VERIFICATION_TIMEOUT);
14204    }
14205
14206    /**
14207     * Get the default verification agent response code.
14208     *
14209     * @return default verification response code
14210     */
14211    private int getDefaultVerificationResponse() {
14212        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14213                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14214                DEFAULT_VERIFICATION_RESPONSE);
14215    }
14216
14217    /**
14218     * Check whether or not package verification has been enabled.
14219     *
14220     * @return true if verification should be performed
14221     */
14222    private boolean isVerificationEnabled(int userId, int installFlags) {
14223        if (!DEFAULT_VERIFY_ENABLE) {
14224            return false;
14225        }
14226
14227        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14228
14229        // Check if installing from ADB
14230        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14231            // Do not run verification in a test harness environment
14232            if (ActivityManager.isRunningInTestHarness()) {
14233                return false;
14234            }
14235            if (ensureVerifyAppsEnabled) {
14236                return true;
14237            }
14238            // Check if the developer does not want package verification for ADB installs
14239            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14240                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14241                return false;
14242            }
14243        }
14244
14245        if (ensureVerifyAppsEnabled) {
14246            return true;
14247        }
14248
14249        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14250                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14251    }
14252
14253    @Override
14254    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14255            throws RemoteException {
14256        mContext.enforceCallingOrSelfPermission(
14257                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14258                "Only intentfilter verification agents can verify applications");
14259
14260        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14261        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14262                Binder.getCallingUid(), verificationCode, failedDomains);
14263        msg.arg1 = id;
14264        msg.obj = response;
14265        mHandler.sendMessage(msg);
14266    }
14267
14268    @Override
14269    public int getIntentVerificationStatus(String packageName, int userId) {
14270        synchronized (mPackages) {
14271            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14272        }
14273    }
14274
14275    @Override
14276    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14277        mContext.enforceCallingOrSelfPermission(
14278                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14279
14280        boolean result = false;
14281        synchronized (mPackages) {
14282            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14283        }
14284        if (result) {
14285            scheduleWritePackageRestrictionsLocked(userId);
14286        }
14287        return result;
14288    }
14289
14290    @Override
14291    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14292            String packageName) {
14293        synchronized (mPackages) {
14294            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14295        }
14296    }
14297
14298    @Override
14299    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14300        if (TextUtils.isEmpty(packageName)) {
14301            return ParceledListSlice.emptyList();
14302        }
14303        synchronized (mPackages) {
14304            PackageParser.Package pkg = mPackages.get(packageName);
14305            if (pkg == null || pkg.activities == null) {
14306                return ParceledListSlice.emptyList();
14307            }
14308            final int count = pkg.activities.size();
14309            ArrayList<IntentFilter> result = new ArrayList<>();
14310            for (int n=0; n<count; n++) {
14311                PackageParser.Activity activity = pkg.activities.get(n);
14312                if (activity.intents != null && activity.intents.size() > 0) {
14313                    result.addAll(activity.intents);
14314                }
14315            }
14316            return new ParceledListSlice<>(result);
14317        }
14318    }
14319
14320    @Override
14321    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14322        mContext.enforceCallingOrSelfPermission(
14323                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14324
14325        synchronized (mPackages) {
14326            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14327            if (packageName != null) {
14328                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
14329                        packageName, userId);
14330            }
14331            return result;
14332        }
14333    }
14334
14335    @Override
14336    public String getDefaultBrowserPackageName(int userId) {
14337        synchronized (mPackages) {
14338            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14339        }
14340    }
14341
14342    /**
14343     * Get the "allow unknown sources" setting.
14344     *
14345     * @return the current "allow unknown sources" setting
14346     */
14347    private int getUnknownSourcesSettings() {
14348        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14349                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14350                -1);
14351    }
14352
14353    @Override
14354    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14355        final int uid = Binder.getCallingUid();
14356        // writer
14357        synchronized (mPackages) {
14358            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14359            if (targetPackageSetting == null) {
14360                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14361            }
14362
14363            PackageSetting installerPackageSetting;
14364            if (installerPackageName != null) {
14365                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14366                if (installerPackageSetting == null) {
14367                    throw new IllegalArgumentException("Unknown installer package: "
14368                            + installerPackageName);
14369                }
14370            } else {
14371                installerPackageSetting = null;
14372            }
14373
14374            Signature[] callerSignature;
14375            Object obj = mSettings.getUserIdLPr(uid);
14376            if (obj != null) {
14377                if (obj instanceof SharedUserSetting) {
14378                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
14379                } else if (obj instanceof PackageSetting) {
14380                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
14381                } else {
14382                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
14383                }
14384            } else {
14385                throw new SecurityException("Unknown calling UID: " + uid);
14386            }
14387
14388            // Verify: can't set installerPackageName to a package that is
14389            // not signed with the same cert as the caller.
14390            if (installerPackageSetting != null) {
14391                if (compareSignatures(callerSignature,
14392                        installerPackageSetting.signatures.mSignatures)
14393                        != PackageManager.SIGNATURE_MATCH) {
14394                    throw new SecurityException(
14395                            "Caller does not have same cert as new installer package "
14396                            + installerPackageName);
14397                }
14398            }
14399
14400            // Verify: if target already has an installer package, it must
14401            // be signed with the same cert as the caller.
14402            if (targetPackageSetting.installerPackageName != null) {
14403                PackageSetting setting = mSettings.mPackages.get(
14404                        targetPackageSetting.installerPackageName);
14405                // If the currently set package isn't valid, then it's always
14406                // okay to change it.
14407                if (setting != null) {
14408                    if (compareSignatures(callerSignature,
14409                            setting.signatures.mSignatures)
14410                            != PackageManager.SIGNATURE_MATCH) {
14411                        throw new SecurityException(
14412                                "Caller does not have same cert as old installer package "
14413                                + targetPackageSetting.installerPackageName);
14414                    }
14415                }
14416            }
14417
14418            // Okay!
14419            targetPackageSetting.installerPackageName = installerPackageName;
14420            if (installerPackageName != null) {
14421                mSettings.mInstallerPackages.add(installerPackageName);
14422            }
14423            scheduleWriteSettingsLocked();
14424        }
14425    }
14426
14427    @Override
14428    public void setApplicationCategoryHint(String packageName, int categoryHint,
14429            String callerPackageName) {
14430        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14431                callerPackageName);
14432        synchronized (mPackages) {
14433            PackageSetting ps = mSettings.mPackages.get(packageName);
14434            if (ps == null) {
14435                throw new IllegalArgumentException("Unknown target package " + packageName);
14436            }
14437
14438            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14439                throw new IllegalArgumentException("Calling package " + callerPackageName
14440                        + " is not installer for " + packageName);
14441            }
14442
14443            if (ps.categoryHint != categoryHint) {
14444                ps.categoryHint = categoryHint;
14445                scheduleWriteSettingsLocked();
14446            }
14447        }
14448    }
14449
14450    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14451        // Queue up an async operation since the package installation may take a little while.
14452        mHandler.post(new Runnable() {
14453            public void run() {
14454                mHandler.removeCallbacks(this);
14455                 // Result object to be returned
14456                PackageInstalledInfo res = new PackageInstalledInfo();
14457                res.setReturnCode(currentStatus);
14458                res.uid = -1;
14459                res.pkg = null;
14460                res.removedInfo = null;
14461                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14462                    args.doPreInstall(res.returnCode);
14463                    synchronized (mInstallLock) {
14464                        installPackageTracedLI(args, res);
14465                    }
14466                    args.doPostInstall(res.returnCode, res.uid);
14467                }
14468
14469                // A restore should be performed at this point if (a) the install
14470                // succeeded, (b) the operation is not an update, and (c) the new
14471                // package has not opted out of backup participation.
14472                final boolean update = res.removedInfo != null
14473                        && res.removedInfo.removedPackage != null;
14474                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14475                boolean doRestore = !update
14476                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14477
14478                // Set up the post-install work request bookkeeping.  This will be used
14479                // and cleaned up by the post-install event handling regardless of whether
14480                // there's a restore pass performed.  Token values are >= 1.
14481                int token;
14482                if (mNextInstallToken < 0) mNextInstallToken = 1;
14483                token = mNextInstallToken++;
14484
14485                PostInstallData data = new PostInstallData(args, res);
14486                mRunningInstalls.put(token, data);
14487                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14488
14489                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14490                    // Pass responsibility to the Backup Manager.  It will perform a
14491                    // restore if appropriate, then pass responsibility back to the
14492                    // Package Manager to run the post-install observer callbacks
14493                    // and broadcasts.
14494                    IBackupManager bm = IBackupManager.Stub.asInterface(
14495                            ServiceManager.getService(Context.BACKUP_SERVICE));
14496                    if (bm != null) {
14497                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14498                                + " to BM for possible restore");
14499                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14500                        try {
14501                            // TODO: http://b/22388012
14502                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14503                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14504                            } else {
14505                                doRestore = false;
14506                            }
14507                        } catch (RemoteException e) {
14508                            // can't happen; the backup manager is local
14509                        } catch (Exception e) {
14510                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14511                            doRestore = false;
14512                        }
14513                    } else {
14514                        Slog.e(TAG, "Backup Manager not found!");
14515                        doRestore = false;
14516                    }
14517                }
14518
14519                if (!doRestore) {
14520                    // No restore possible, or the Backup Manager was mysteriously not
14521                    // available -- just fire the post-install work request directly.
14522                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14523
14524                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14525
14526                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14527                    mHandler.sendMessage(msg);
14528                }
14529            }
14530        });
14531    }
14532
14533    /**
14534     * Callback from PackageSettings whenever an app is first transitioned out of the
14535     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14536     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14537     * here whether the app is the target of an ongoing install, and only send the
14538     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14539     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14540     * handling.
14541     */
14542    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14543        // Serialize this with the rest of the install-process message chain.  In the
14544        // restore-at-install case, this Runnable will necessarily run before the
14545        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14546        // are coherent.  In the non-restore case, the app has already completed install
14547        // and been launched through some other means, so it is not in a problematic
14548        // state for observers to see the FIRST_LAUNCH signal.
14549        mHandler.post(new Runnable() {
14550            @Override
14551            public void run() {
14552                for (int i = 0; i < mRunningInstalls.size(); i++) {
14553                    final PostInstallData data = mRunningInstalls.valueAt(i);
14554                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14555                        continue;
14556                    }
14557                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14558                        // right package; but is it for the right user?
14559                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14560                            if (userId == data.res.newUsers[uIndex]) {
14561                                if (DEBUG_BACKUP) {
14562                                    Slog.i(TAG, "Package " + pkgName
14563                                            + " being restored so deferring FIRST_LAUNCH");
14564                                }
14565                                return;
14566                            }
14567                        }
14568                    }
14569                }
14570                // didn't find it, so not being restored
14571                if (DEBUG_BACKUP) {
14572                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14573                }
14574                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14575            }
14576        });
14577    }
14578
14579    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14580        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14581                installerPkg, null, userIds);
14582    }
14583
14584    private abstract class HandlerParams {
14585        private static final int MAX_RETRIES = 4;
14586
14587        /**
14588         * Number of times startCopy() has been attempted and had a non-fatal
14589         * error.
14590         */
14591        private int mRetries = 0;
14592
14593        /** User handle for the user requesting the information or installation. */
14594        private final UserHandle mUser;
14595        String traceMethod;
14596        int traceCookie;
14597
14598        HandlerParams(UserHandle user) {
14599            mUser = user;
14600        }
14601
14602        UserHandle getUser() {
14603            return mUser;
14604        }
14605
14606        HandlerParams setTraceMethod(String traceMethod) {
14607            this.traceMethod = traceMethod;
14608            return this;
14609        }
14610
14611        HandlerParams setTraceCookie(int traceCookie) {
14612            this.traceCookie = traceCookie;
14613            return this;
14614        }
14615
14616        final boolean startCopy() {
14617            boolean res;
14618            try {
14619                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14620
14621                if (++mRetries > MAX_RETRIES) {
14622                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14623                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14624                    handleServiceError();
14625                    return false;
14626                } else {
14627                    handleStartCopy();
14628                    res = true;
14629                }
14630            } catch (RemoteException e) {
14631                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14632                mHandler.sendEmptyMessage(MCS_RECONNECT);
14633                res = false;
14634            }
14635            handleReturnCode();
14636            return res;
14637        }
14638
14639        final void serviceError() {
14640            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14641            handleServiceError();
14642            handleReturnCode();
14643        }
14644
14645        abstract void handleStartCopy() throws RemoteException;
14646        abstract void handleServiceError();
14647        abstract void handleReturnCode();
14648    }
14649
14650    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14651        for (File path : paths) {
14652            try {
14653                mcs.clearDirectory(path.getAbsolutePath());
14654            } catch (RemoteException e) {
14655            }
14656        }
14657    }
14658
14659    static class OriginInfo {
14660        /**
14661         * Location where install is coming from, before it has been
14662         * copied/renamed into place. This could be a single monolithic APK
14663         * file, or a cluster directory. This location may be untrusted.
14664         */
14665        final File file;
14666        final String cid;
14667
14668        /**
14669         * Flag indicating that {@link #file} or {@link #cid} has already been
14670         * staged, meaning downstream users don't need to defensively copy the
14671         * contents.
14672         */
14673        final boolean staged;
14674
14675        /**
14676         * Flag indicating that {@link #file} or {@link #cid} is an already
14677         * installed app that is being moved.
14678         */
14679        final boolean existing;
14680
14681        final String resolvedPath;
14682        final File resolvedFile;
14683
14684        static OriginInfo fromNothing() {
14685            return new OriginInfo(null, null, false, false);
14686        }
14687
14688        static OriginInfo fromUntrustedFile(File file) {
14689            return new OriginInfo(file, null, false, false);
14690        }
14691
14692        static OriginInfo fromExistingFile(File file) {
14693            return new OriginInfo(file, null, false, true);
14694        }
14695
14696        static OriginInfo fromStagedFile(File file) {
14697            return new OriginInfo(file, null, true, false);
14698        }
14699
14700        static OriginInfo fromStagedContainer(String cid) {
14701            return new OriginInfo(null, cid, true, false);
14702        }
14703
14704        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14705            this.file = file;
14706            this.cid = cid;
14707            this.staged = staged;
14708            this.existing = existing;
14709
14710            if (cid != null) {
14711                resolvedPath = PackageHelper.getSdDir(cid);
14712                resolvedFile = new File(resolvedPath);
14713            } else if (file != null) {
14714                resolvedPath = file.getAbsolutePath();
14715                resolvedFile = file;
14716            } else {
14717                resolvedPath = null;
14718                resolvedFile = null;
14719            }
14720        }
14721    }
14722
14723    static class MoveInfo {
14724        final int moveId;
14725        final String fromUuid;
14726        final String toUuid;
14727        final String packageName;
14728        final String dataAppName;
14729        final int appId;
14730        final String seinfo;
14731        final int targetSdkVersion;
14732
14733        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14734                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14735            this.moveId = moveId;
14736            this.fromUuid = fromUuid;
14737            this.toUuid = toUuid;
14738            this.packageName = packageName;
14739            this.dataAppName = dataAppName;
14740            this.appId = appId;
14741            this.seinfo = seinfo;
14742            this.targetSdkVersion = targetSdkVersion;
14743        }
14744    }
14745
14746    static class VerificationInfo {
14747        /** A constant used to indicate that a uid value is not present. */
14748        public static final int NO_UID = -1;
14749
14750        /** URI referencing where the package was downloaded from. */
14751        final Uri originatingUri;
14752
14753        /** HTTP referrer URI associated with the originatingURI. */
14754        final Uri referrer;
14755
14756        /** UID of the application that the install request originated from. */
14757        final int originatingUid;
14758
14759        /** UID of application requesting the install */
14760        final int installerUid;
14761
14762        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14763            this.originatingUri = originatingUri;
14764            this.referrer = referrer;
14765            this.originatingUid = originatingUid;
14766            this.installerUid = installerUid;
14767        }
14768    }
14769
14770    class InstallParams extends HandlerParams {
14771        final OriginInfo origin;
14772        final MoveInfo move;
14773        final IPackageInstallObserver2 observer;
14774        int installFlags;
14775        final String installerPackageName;
14776        final String volumeUuid;
14777        private InstallArgs mArgs;
14778        private int mRet;
14779        final String packageAbiOverride;
14780        final String[] grantedRuntimePermissions;
14781        final VerificationInfo verificationInfo;
14782        final Certificate[][] certificates;
14783        final int installReason;
14784
14785        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14786                int installFlags, String installerPackageName, String volumeUuid,
14787                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14788                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14789            super(user);
14790            this.origin = origin;
14791            this.move = move;
14792            this.observer = observer;
14793            this.installFlags = installFlags;
14794            this.installerPackageName = installerPackageName;
14795            this.volumeUuid = volumeUuid;
14796            this.verificationInfo = verificationInfo;
14797            this.packageAbiOverride = packageAbiOverride;
14798            this.grantedRuntimePermissions = grantedPermissions;
14799            this.certificates = certificates;
14800            this.installReason = installReason;
14801        }
14802
14803        @Override
14804        public String toString() {
14805            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14806                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14807        }
14808
14809        private int installLocationPolicy(PackageInfoLite pkgLite) {
14810            String packageName = pkgLite.packageName;
14811            int installLocation = pkgLite.installLocation;
14812            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14813            // reader
14814            synchronized (mPackages) {
14815                // Currently installed package which the new package is attempting to replace or
14816                // null if no such package is installed.
14817                PackageParser.Package installedPkg = mPackages.get(packageName);
14818                // Package which currently owns the data which the new package will own if installed.
14819                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14820                // will be null whereas dataOwnerPkg will contain information about the package
14821                // which was uninstalled while keeping its data.
14822                PackageParser.Package dataOwnerPkg = installedPkg;
14823                if (dataOwnerPkg  == null) {
14824                    PackageSetting ps = mSettings.mPackages.get(packageName);
14825                    if (ps != null) {
14826                        dataOwnerPkg = ps.pkg;
14827                    }
14828                }
14829
14830                if (dataOwnerPkg != null) {
14831                    // If installed, the package will get access to data left on the device by its
14832                    // predecessor. As a security measure, this is permited only if this is not a
14833                    // version downgrade or if the predecessor package is marked as debuggable and
14834                    // a downgrade is explicitly requested.
14835                    //
14836                    // On debuggable platform builds, downgrades are permitted even for
14837                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14838                    // not offer security guarantees and thus it's OK to disable some security
14839                    // mechanisms to make debugging/testing easier on those builds. However, even on
14840                    // debuggable builds downgrades of packages are permitted only if requested via
14841                    // installFlags. This is because we aim to keep the behavior of debuggable
14842                    // platform builds as close as possible to the behavior of non-debuggable
14843                    // platform builds.
14844                    final boolean downgradeRequested =
14845                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14846                    final boolean packageDebuggable =
14847                                (dataOwnerPkg.applicationInfo.flags
14848                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14849                    final boolean downgradePermitted =
14850                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14851                    if (!downgradePermitted) {
14852                        try {
14853                            checkDowngrade(dataOwnerPkg, pkgLite);
14854                        } catch (PackageManagerException e) {
14855                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14856                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14857                        }
14858                    }
14859                }
14860
14861                if (installedPkg != null) {
14862                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14863                        // Check for updated system application.
14864                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14865                            if (onSd) {
14866                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14867                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14868                            }
14869                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14870                        } else {
14871                            if (onSd) {
14872                                // Install flag overrides everything.
14873                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14874                            }
14875                            // If current upgrade specifies particular preference
14876                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14877                                // Application explicitly specified internal.
14878                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14879                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14880                                // App explictly prefers external. Let policy decide
14881                            } else {
14882                                // Prefer previous location
14883                                if (isExternal(installedPkg)) {
14884                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14885                                }
14886                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14887                            }
14888                        }
14889                    } else {
14890                        // Invalid install. Return error code
14891                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14892                    }
14893                }
14894            }
14895            // All the special cases have been taken care of.
14896            // Return result based on recommended install location.
14897            if (onSd) {
14898                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14899            }
14900            return pkgLite.recommendedInstallLocation;
14901        }
14902
14903        /*
14904         * Invoke remote method to get package information and install
14905         * location values. Override install location based on default
14906         * policy if needed and then create install arguments based
14907         * on the install location.
14908         */
14909        public void handleStartCopy() throws RemoteException {
14910            int ret = PackageManager.INSTALL_SUCCEEDED;
14911
14912            // If we're already staged, we've firmly committed to an install location
14913            if (origin.staged) {
14914                if (origin.file != null) {
14915                    installFlags |= PackageManager.INSTALL_INTERNAL;
14916                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14917                } else if (origin.cid != null) {
14918                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14919                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14920                } else {
14921                    throw new IllegalStateException("Invalid stage location");
14922                }
14923            }
14924
14925            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14926            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14927            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14928            PackageInfoLite pkgLite = null;
14929
14930            if (onInt && onSd) {
14931                // Check if both bits are set.
14932                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14933                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14934            } else if (onSd && ephemeral) {
14935                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14936                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14937            } else {
14938                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14939                        packageAbiOverride);
14940
14941                if (DEBUG_EPHEMERAL && ephemeral) {
14942                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14943                }
14944
14945                /*
14946                 * If we have too little free space, try to free cache
14947                 * before giving up.
14948                 */
14949                if (!origin.staged && pkgLite.recommendedInstallLocation
14950                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14951                    // TODO: focus freeing disk space on the target device
14952                    final StorageManager storage = StorageManager.from(mContext);
14953                    final long lowThreshold = storage.getStorageLowBytes(
14954                            Environment.getDataDirectory());
14955
14956                    final long sizeBytes = mContainerService.calculateInstalledSize(
14957                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14958
14959                    try {
14960                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14961                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14962                                installFlags, packageAbiOverride);
14963                    } catch (InstallerException e) {
14964                        Slog.w(TAG, "Failed to free cache", e);
14965                    }
14966
14967                    /*
14968                     * The cache free must have deleted the file we
14969                     * downloaded to install.
14970                     *
14971                     * TODO: fix the "freeCache" call to not delete
14972                     *       the file we care about.
14973                     */
14974                    if (pkgLite.recommendedInstallLocation
14975                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14976                        pkgLite.recommendedInstallLocation
14977                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14978                    }
14979                }
14980            }
14981
14982            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14983                int loc = pkgLite.recommendedInstallLocation;
14984                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14985                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14986                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14987                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14988                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14989                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14990                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14991                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14992                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14993                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14994                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14995                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14996                } else {
14997                    // Override with defaults if needed.
14998                    loc = installLocationPolicy(pkgLite);
14999                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15000                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15001                    } else if (!onSd && !onInt) {
15002                        // Override install location with flags
15003                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15004                            // Set the flag to install on external media.
15005                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15006                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15007                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15008                            if (DEBUG_EPHEMERAL) {
15009                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15010                            }
15011                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15012                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15013                                    |PackageManager.INSTALL_INTERNAL);
15014                        } else {
15015                            // Make sure the flag for installing on external
15016                            // media is unset
15017                            installFlags |= PackageManager.INSTALL_INTERNAL;
15018                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15019                        }
15020                    }
15021                }
15022            }
15023
15024            final InstallArgs args = createInstallArgs(this);
15025            mArgs = args;
15026
15027            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15028                // TODO: http://b/22976637
15029                // Apps installed for "all" users use the device owner to verify the app
15030                UserHandle verifierUser = getUser();
15031                if (verifierUser == UserHandle.ALL) {
15032                    verifierUser = UserHandle.SYSTEM;
15033                }
15034
15035                /*
15036                 * Determine if we have any installed package verifiers. If we
15037                 * do, then we'll defer to them to verify the packages.
15038                 */
15039                final int requiredUid = mRequiredVerifierPackage == null ? -1
15040                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15041                                verifierUser.getIdentifier());
15042                if (!origin.existing && requiredUid != -1
15043                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
15044                    final Intent verification = new Intent(
15045                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15046                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15047                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15048                            PACKAGE_MIME_TYPE);
15049                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15050
15051                    // Query all live verifiers based on current user state
15052                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15053                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15054
15055                    if (DEBUG_VERIFY) {
15056                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15057                                + verification.toString() + " with " + pkgLite.verifiers.length
15058                                + " optional verifiers");
15059                    }
15060
15061                    final int verificationId = mPendingVerificationToken++;
15062
15063                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15064
15065                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15066                            installerPackageName);
15067
15068                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15069                            installFlags);
15070
15071                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15072                            pkgLite.packageName);
15073
15074                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15075                            pkgLite.versionCode);
15076
15077                    if (verificationInfo != null) {
15078                        if (verificationInfo.originatingUri != null) {
15079                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15080                                    verificationInfo.originatingUri);
15081                        }
15082                        if (verificationInfo.referrer != null) {
15083                            verification.putExtra(Intent.EXTRA_REFERRER,
15084                                    verificationInfo.referrer);
15085                        }
15086                        if (verificationInfo.originatingUid >= 0) {
15087                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15088                                    verificationInfo.originatingUid);
15089                        }
15090                        if (verificationInfo.installerUid >= 0) {
15091                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15092                                    verificationInfo.installerUid);
15093                        }
15094                    }
15095
15096                    final PackageVerificationState verificationState = new PackageVerificationState(
15097                            requiredUid, args);
15098
15099                    mPendingVerification.append(verificationId, verificationState);
15100
15101                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15102                            receivers, verificationState);
15103
15104                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15105                    final long idleDuration = getVerificationTimeout();
15106
15107                    /*
15108                     * If any sufficient verifiers were listed in the package
15109                     * manifest, attempt to ask them.
15110                     */
15111                    if (sufficientVerifiers != null) {
15112                        final int N = sufficientVerifiers.size();
15113                        if (N == 0) {
15114                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15115                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15116                        } else {
15117                            for (int i = 0; i < N; i++) {
15118                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15119                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15120                                        verifierComponent.getPackageName(), idleDuration,
15121                                        verifierUser.getIdentifier(), false, "package verifier");
15122
15123                                final Intent sufficientIntent = new Intent(verification);
15124                                sufficientIntent.setComponent(verifierComponent);
15125                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15126                            }
15127                        }
15128                    }
15129
15130                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15131                            mRequiredVerifierPackage, receivers);
15132                    if (ret == PackageManager.INSTALL_SUCCEEDED
15133                            && mRequiredVerifierPackage != null) {
15134                        Trace.asyncTraceBegin(
15135                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15136                        /*
15137                         * Send the intent to the required verification agent,
15138                         * but only start the verification timeout after the
15139                         * target BroadcastReceivers have run.
15140                         */
15141                        verification.setComponent(requiredVerifierComponent);
15142                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15143                                mRequiredVerifierPackage, idleDuration,
15144                                verifierUser.getIdentifier(), false, "package verifier");
15145                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15146                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15147                                new BroadcastReceiver() {
15148                                    @Override
15149                                    public void onReceive(Context context, Intent intent) {
15150                                        final Message msg = mHandler
15151                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15152                                        msg.arg1 = verificationId;
15153                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15154                                    }
15155                                }, null, 0, null, null);
15156
15157                        /*
15158                         * We don't want the copy to proceed until verification
15159                         * succeeds, so null out this field.
15160                         */
15161                        mArgs = null;
15162                    }
15163                } else {
15164                    /*
15165                     * No package verification is enabled, so immediately start
15166                     * the remote call to initiate copy using temporary file.
15167                     */
15168                    ret = args.copyApk(mContainerService, true);
15169                }
15170            }
15171
15172            mRet = ret;
15173        }
15174
15175        @Override
15176        void handleReturnCode() {
15177            // If mArgs is null, then MCS couldn't be reached. When it
15178            // reconnects, it will try again to install. At that point, this
15179            // will succeed.
15180            if (mArgs != null) {
15181                processPendingInstall(mArgs, mRet);
15182            }
15183        }
15184
15185        @Override
15186        void handleServiceError() {
15187            mArgs = createInstallArgs(this);
15188            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15189        }
15190
15191        public boolean isForwardLocked() {
15192            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15193        }
15194    }
15195
15196    /**
15197     * Used during creation of InstallArgs
15198     *
15199     * @param installFlags package installation flags
15200     * @return true if should be installed on external storage
15201     */
15202    private static boolean installOnExternalAsec(int installFlags) {
15203        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
15204            return false;
15205        }
15206        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
15207            return true;
15208        }
15209        return false;
15210    }
15211
15212    /**
15213     * Used during creation of InstallArgs
15214     *
15215     * @param installFlags package installation flags
15216     * @return true if should be installed as forward locked
15217     */
15218    private static boolean installForwardLocked(int installFlags) {
15219        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15220    }
15221
15222    private InstallArgs createInstallArgs(InstallParams params) {
15223        if (params.move != null) {
15224            return new MoveInstallArgs(params);
15225        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
15226            return new AsecInstallArgs(params);
15227        } else {
15228            return new FileInstallArgs(params);
15229        }
15230    }
15231
15232    /**
15233     * Create args that describe an existing installed package. Typically used
15234     * when cleaning up old installs, or used as a move source.
15235     */
15236    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15237            String resourcePath, String[] instructionSets) {
15238        final boolean isInAsec;
15239        if (installOnExternalAsec(installFlags)) {
15240            /* Apps on SD card are always in ASEC containers. */
15241            isInAsec = true;
15242        } else if (installForwardLocked(installFlags)
15243                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
15244            /*
15245             * Forward-locked apps are only in ASEC containers if they're the
15246             * new style
15247             */
15248            isInAsec = true;
15249        } else {
15250            isInAsec = false;
15251        }
15252
15253        if (isInAsec) {
15254            return new AsecInstallArgs(codePath, instructionSets,
15255                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
15256        } else {
15257            return new FileInstallArgs(codePath, resourcePath, instructionSets);
15258        }
15259    }
15260
15261    static abstract class InstallArgs {
15262        /** @see InstallParams#origin */
15263        final OriginInfo origin;
15264        /** @see InstallParams#move */
15265        final MoveInfo move;
15266
15267        final IPackageInstallObserver2 observer;
15268        // Always refers to PackageManager flags only
15269        final int installFlags;
15270        final String installerPackageName;
15271        final String volumeUuid;
15272        final UserHandle user;
15273        final String abiOverride;
15274        final String[] installGrantPermissions;
15275        /** If non-null, drop an async trace when the install completes */
15276        final String traceMethod;
15277        final int traceCookie;
15278        final Certificate[][] certificates;
15279        final int installReason;
15280
15281        // The list of instruction sets supported by this app. This is currently
15282        // only used during the rmdex() phase to clean up resources. We can get rid of this
15283        // if we move dex files under the common app path.
15284        /* nullable */ String[] instructionSets;
15285
15286        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15287                int installFlags, String installerPackageName, String volumeUuid,
15288                UserHandle user, String[] instructionSets,
15289                String abiOverride, String[] installGrantPermissions,
15290                String traceMethod, int traceCookie, Certificate[][] certificates,
15291                int installReason) {
15292            this.origin = origin;
15293            this.move = move;
15294            this.installFlags = installFlags;
15295            this.observer = observer;
15296            this.installerPackageName = installerPackageName;
15297            this.volumeUuid = volumeUuid;
15298            this.user = user;
15299            this.instructionSets = instructionSets;
15300            this.abiOverride = abiOverride;
15301            this.installGrantPermissions = installGrantPermissions;
15302            this.traceMethod = traceMethod;
15303            this.traceCookie = traceCookie;
15304            this.certificates = certificates;
15305            this.installReason = installReason;
15306        }
15307
15308        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15309        abstract int doPreInstall(int status);
15310
15311        /**
15312         * Rename package into final resting place. All paths on the given
15313         * scanned package should be updated to reflect the rename.
15314         */
15315        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15316        abstract int doPostInstall(int status, int uid);
15317
15318        /** @see PackageSettingBase#codePathString */
15319        abstract String getCodePath();
15320        /** @see PackageSettingBase#resourcePathString */
15321        abstract String getResourcePath();
15322
15323        // Need installer lock especially for dex file removal.
15324        abstract void cleanUpResourcesLI();
15325        abstract boolean doPostDeleteLI(boolean delete);
15326
15327        /**
15328         * Called before the source arguments are copied. This is used mostly
15329         * for MoveParams when it needs to read the source file to put it in the
15330         * destination.
15331         */
15332        int doPreCopy() {
15333            return PackageManager.INSTALL_SUCCEEDED;
15334        }
15335
15336        /**
15337         * Called after the source arguments are copied. This is used mostly for
15338         * MoveParams when it needs to read the source file to put it in the
15339         * destination.
15340         */
15341        int doPostCopy(int uid) {
15342            return PackageManager.INSTALL_SUCCEEDED;
15343        }
15344
15345        protected boolean isFwdLocked() {
15346            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15347        }
15348
15349        protected boolean isExternalAsec() {
15350            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15351        }
15352
15353        protected boolean isEphemeral() {
15354            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15355        }
15356
15357        UserHandle getUser() {
15358            return user;
15359        }
15360    }
15361
15362    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15363        if (!allCodePaths.isEmpty()) {
15364            if (instructionSets == null) {
15365                throw new IllegalStateException("instructionSet == null");
15366            }
15367            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15368            for (String codePath : allCodePaths) {
15369                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15370                    try {
15371                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15372                    } catch (InstallerException ignored) {
15373                    }
15374                }
15375            }
15376        }
15377    }
15378
15379    /**
15380     * Logic to handle installation of non-ASEC applications, including copying
15381     * and renaming logic.
15382     */
15383    class FileInstallArgs extends InstallArgs {
15384        private File codeFile;
15385        private File resourceFile;
15386
15387        // Example topology:
15388        // /data/app/com.example/base.apk
15389        // /data/app/com.example/split_foo.apk
15390        // /data/app/com.example/lib/arm/libfoo.so
15391        // /data/app/com.example/lib/arm64/libfoo.so
15392        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15393
15394        /** New install */
15395        FileInstallArgs(InstallParams params) {
15396            super(params.origin, params.move, params.observer, params.installFlags,
15397                    params.installerPackageName, params.volumeUuid,
15398                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15399                    params.grantedRuntimePermissions,
15400                    params.traceMethod, params.traceCookie, params.certificates,
15401                    params.installReason);
15402            if (isFwdLocked()) {
15403                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15404            }
15405        }
15406
15407        /** Existing install */
15408        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15409            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15410                    null, null, null, 0, null /*certificates*/,
15411                    PackageManager.INSTALL_REASON_UNKNOWN);
15412            this.codeFile = (codePath != null) ? new File(codePath) : null;
15413            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15414        }
15415
15416        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15417            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15418            try {
15419                return doCopyApk(imcs, temp);
15420            } finally {
15421                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15422            }
15423        }
15424
15425        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15426            if (origin.staged) {
15427                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15428                codeFile = origin.file;
15429                resourceFile = origin.file;
15430                return PackageManager.INSTALL_SUCCEEDED;
15431            }
15432
15433            try {
15434                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15435                final File tempDir =
15436                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15437                codeFile = tempDir;
15438                resourceFile = tempDir;
15439            } catch (IOException e) {
15440                Slog.w(TAG, "Failed to create copy file: " + e);
15441                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15442            }
15443
15444            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15445                @Override
15446                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15447                    if (!FileUtils.isValidExtFilename(name)) {
15448                        throw new IllegalArgumentException("Invalid filename: " + name);
15449                    }
15450                    try {
15451                        final File file = new File(codeFile, name);
15452                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15453                                O_RDWR | O_CREAT, 0644);
15454                        Os.chmod(file.getAbsolutePath(), 0644);
15455                        return new ParcelFileDescriptor(fd);
15456                    } catch (ErrnoException e) {
15457                        throw new RemoteException("Failed to open: " + e.getMessage());
15458                    }
15459                }
15460            };
15461
15462            int ret = PackageManager.INSTALL_SUCCEEDED;
15463            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15464            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15465                Slog.e(TAG, "Failed to copy package");
15466                return ret;
15467            }
15468
15469            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15470            NativeLibraryHelper.Handle handle = null;
15471            try {
15472                handle = NativeLibraryHelper.Handle.create(codeFile);
15473                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15474                        abiOverride);
15475            } catch (IOException e) {
15476                Slog.e(TAG, "Copying native libraries failed", e);
15477                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15478            } finally {
15479                IoUtils.closeQuietly(handle);
15480            }
15481
15482            return ret;
15483        }
15484
15485        int doPreInstall(int status) {
15486            if (status != PackageManager.INSTALL_SUCCEEDED) {
15487                cleanUp();
15488            }
15489            return status;
15490        }
15491
15492        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15493            if (status != PackageManager.INSTALL_SUCCEEDED) {
15494                cleanUp();
15495                return false;
15496            }
15497
15498            final File targetDir = codeFile.getParentFile();
15499            final File beforeCodeFile = codeFile;
15500            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15501
15502            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15503            try {
15504                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15505            } catch (ErrnoException e) {
15506                Slog.w(TAG, "Failed to rename", e);
15507                return false;
15508            }
15509
15510            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15511                Slog.w(TAG, "Failed to restorecon");
15512                return false;
15513            }
15514
15515            // Reflect the rename internally
15516            codeFile = afterCodeFile;
15517            resourceFile = afterCodeFile;
15518
15519            // Reflect the rename in scanned details
15520            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15521            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15522                    afterCodeFile, pkg.baseCodePath));
15523            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15524                    afterCodeFile, pkg.splitCodePaths));
15525
15526            // Reflect the rename in app info
15527            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15528            pkg.setApplicationInfoCodePath(pkg.codePath);
15529            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15530            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15531            pkg.setApplicationInfoResourcePath(pkg.codePath);
15532            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15533            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15534
15535            return true;
15536        }
15537
15538        int doPostInstall(int status, int uid) {
15539            if (status != PackageManager.INSTALL_SUCCEEDED) {
15540                cleanUp();
15541            }
15542            return status;
15543        }
15544
15545        @Override
15546        String getCodePath() {
15547            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15548        }
15549
15550        @Override
15551        String getResourcePath() {
15552            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15553        }
15554
15555        private boolean cleanUp() {
15556            if (codeFile == null || !codeFile.exists()) {
15557                return false;
15558            }
15559
15560            removeCodePathLI(codeFile);
15561
15562            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15563                resourceFile.delete();
15564            }
15565
15566            return true;
15567        }
15568
15569        void cleanUpResourcesLI() {
15570            // Try enumerating all code paths before deleting
15571            List<String> allCodePaths = Collections.EMPTY_LIST;
15572            if (codeFile != null && codeFile.exists()) {
15573                try {
15574                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15575                    allCodePaths = pkg.getAllCodePaths();
15576                } catch (PackageParserException e) {
15577                    // Ignored; we tried our best
15578                }
15579            }
15580
15581            cleanUp();
15582            removeDexFiles(allCodePaths, instructionSets);
15583        }
15584
15585        boolean doPostDeleteLI(boolean delete) {
15586            // XXX err, shouldn't we respect the delete flag?
15587            cleanUpResourcesLI();
15588            return true;
15589        }
15590    }
15591
15592    private boolean isAsecExternal(String cid) {
15593        final String asecPath = PackageHelper.getSdFilesystem(cid);
15594        return !asecPath.startsWith(mAsecInternalPath);
15595    }
15596
15597    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15598            PackageManagerException {
15599        if (copyRet < 0) {
15600            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15601                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15602                throw new PackageManagerException(copyRet, message);
15603            }
15604        }
15605    }
15606
15607    /**
15608     * Extract the StorageManagerService "container ID" from the full code path of an
15609     * .apk.
15610     */
15611    static String cidFromCodePath(String fullCodePath) {
15612        int eidx = fullCodePath.lastIndexOf("/");
15613        String subStr1 = fullCodePath.substring(0, eidx);
15614        int sidx = subStr1.lastIndexOf("/");
15615        return subStr1.substring(sidx+1, eidx);
15616    }
15617
15618    /**
15619     * Logic to handle installation of ASEC applications, including copying and
15620     * renaming logic.
15621     */
15622    class AsecInstallArgs extends InstallArgs {
15623        static final String RES_FILE_NAME = "pkg.apk";
15624        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15625
15626        String cid;
15627        String packagePath;
15628        String resourcePath;
15629
15630        /** New install */
15631        AsecInstallArgs(InstallParams params) {
15632            super(params.origin, params.move, params.observer, params.installFlags,
15633                    params.installerPackageName, params.volumeUuid,
15634                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15635                    params.grantedRuntimePermissions,
15636                    params.traceMethod, params.traceCookie, params.certificates,
15637                    params.installReason);
15638        }
15639
15640        /** Existing install */
15641        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15642                        boolean isExternal, boolean isForwardLocked) {
15643            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15644                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15645                    instructionSets, null, null, null, 0, null /*certificates*/,
15646                    PackageManager.INSTALL_REASON_UNKNOWN);
15647            // Hackily pretend we're still looking at a full code path
15648            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15649                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15650            }
15651
15652            // Extract cid from fullCodePath
15653            int eidx = fullCodePath.lastIndexOf("/");
15654            String subStr1 = fullCodePath.substring(0, eidx);
15655            int sidx = subStr1.lastIndexOf("/");
15656            cid = subStr1.substring(sidx+1, eidx);
15657            setMountPath(subStr1);
15658        }
15659
15660        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15661            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15662                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15663                    instructionSets, null, null, null, 0, null /*certificates*/,
15664                    PackageManager.INSTALL_REASON_UNKNOWN);
15665            this.cid = cid;
15666            setMountPath(PackageHelper.getSdDir(cid));
15667        }
15668
15669        void createCopyFile() {
15670            cid = mInstallerService.allocateExternalStageCidLegacy();
15671        }
15672
15673        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15674            if (origin.staged && origin.cid != null) {
15675                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15676                cid = origin.cid;
15677                setMountPath(PackageHelper.getSdDir(cid));
15678                return PackageManager.INSTALL_SUCCEEDED;
15679            }
15680
15681            if (temp) {
15682                createCopyFile();
15683            } else {
15684                /*
15685                 * Pre-emptively destroy the container since it's destroyed if
15686                 * copying fails due to it existing anyway.
15687                 */
15688                PackageHelper.destroySdDir(cid);
15689            }
15690
15691            final String newMountPath = imcs.copyPackageToContainer(
15692                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15693                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15694
15695            if (newMountPath != null) {
15696                setMountPath(newMountPath);
15697                return PackageManager.INSTALL_SUCCEEDED;
15698            } else {
15699                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15700            }
15701        }
15702
15703        @Override
15704        String getCodePath() {
15705            return packagePath;
15706        }
15707
15708        @Override
15709        String getResourcePath() {
15710            return resourcePath;
15711        }
15712
15713        int doPreInstall(int status) {
15714            if (status != PackageManager.INSTALL_SUCCEEDED) {
15715                // Destroy container
15716                PackageHelper.destroySdDir(cid);
15717            } else {
15718                boolean mounted = PackageHelper.isContainerMounted(cid);
15719                if (!mounted) {
15720                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15721                            Process.SYSTEM_UID);
15722                    if (newMountPath != null) {
15723                        setMountPath(newMountPath);
15724                    } else {
15725                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15726                    }
15727                }
15728            }
15729            return status;
15730        }
15731
15732        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15733            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15734            String newMountPath = null;
15735            if (PackageHelper.isContainerMounted(cid)) {
15736                // Unmount the container
15737                if (!PackageHelper.unMountSdDir(cid)) {
15738                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15739                    return false;
15740                }
15741            }
15742            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15743                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15744                        " which might be stale. Will try to clean up.");
15745                // Clean up the stale container and proceed to recreate.
15746                if (!PackageHelper.destroySdDir(newCacheId)) {
15747                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15748                    return false;
15749                }
15750                // Successfully cleaned up stale container. Try to rename again.
15751                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15752                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15753                            + " inspite of cleaning it up.");
15754                    return false;
15755                }
15756            }
15757            if (!PackageHelper.isContainerMounted(newCacheId)) {
15758                Slog.w(TAG, "Mounting container " + newCacheId);
15759                newMountPath = PackageHelper.mountSdDir(newCacheId,
15760                        getEncryptKey(), Process.SYSTEM_UID);
15761            } else {
15762                newMountPath = PackageHelper.getSdDir(newCacheId);
15763            }
15764            if (newMountPath == null) {
15765                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15766                return false;
15767            }
15768            Log.i(TAG, "Succesfully renamed " + cid +
15769                    " to " + newCacheId +
15770                    " at new path: " + newMountPath);
15771            cid = newCacheId;
15772
15773            final File beforeCodeFile = new File(packagePath);
15774            setMountPath(newMountPath);
15775            final File afterCodeFile = new File(packagePath);
15776
15777            // Reflect the rename in scanned details
15778            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15779            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15780                    afterCodeFile, pkg.baseCodePath));
15781            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15782                    afterCodeFile, pkg.splitCodePaths));
15783
15784            // Reflect the rename in app info
15785            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15786            pkg.setApplicationInfoCodePath(pkg.codePath);
15787            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15788            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15789            pkg.setApplicationInfoResourcePath(pkg.codePath);
15790            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15791            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15792
15793            return true;
15794        }
15795
15796        private void setMountPath(String mountPath) {
15797            final File mountFile = new File(mountPath);
15798
15799            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15800            if (monolithicFile.exists()) {
15801                packagePath = monolithicFile.getAbsolutePath();
15802                if (isFwdLocked()) {
15803                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15804                } else {
15805                    resourcePath = packagePath;
15806                }
15807            } else {
15808                packagePath = mountFile.getAbsolutePath();
15809                resourcePath = packagePath;
15810            }
15811        }
15812
15813        int doPostInstall(int status, int uid) {
15814            if (status != PackageManager.INSTALL_SUCCEEDED) {
15815                cleanUp();
15816            } else {
15817                final int groupOwner;
15818                final String protectedFile;
15819                if (isFwdLocked()) {
15820                    groupOwner = UserHandle.getSharedAppGid(uid);
15821                    protectedFile = RES_FILE_NAME;
15822                } else {
15823                    groupOwner = -1;
15824                    protectedFile = null;
15825                }
15826
15827                if (uid < Process.FIRST_APPLICATION_UID
15828                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15829                    Slog.e(TAG, "Failed to finalize " + cid);
15830                    PackageHelper.destroySdDir(cid);
15831                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15832                }
15833
15834                boolean mounted = PackageHelper.isContainerMounted(cid);
15835                if (!mounted) {
15836                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15837                }
15838            }
15839            return status;
15840        }
15841
15842        private void cleanUp() {
15843            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15844
15845            // Destroy secure container
15846            PackageHelper.destroySdDir(cid);
15847        }
15848
15849        private List<String> getAllCodePaths() {
15850            final File codeFile = new File(getCodePath());
15851            if (codeFile != null && codeFile.exists()) {
15852                try {
15853                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15854                    return pkg.getAllCodePaths();
15855                } catch (PackageParserException e) {
15856                    // Ignored; we tried our best
15857                }
15858            }
15859            return Collections.EMPTY_LIST;
15860        }
15861
15862        void cleanUpResourcesLI() {
15863            // Enumerate all code paths before deleting
15864            cleanUpResourcesLI(getAllCodePaths());
15865        }
15866
15867        private void cleanUpResourcesLI(List<String> allCodePaths) {
15868            cleanUp();
15869            removeDexFiles(allCodePaths, instructionSets);
15870        }
15871
15872        String getPackageName() {
15873            return getAsecPackageName(cid);
15874        }
15875
15876        boolean doPostDeleteLI(boolean delete) {
15877            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15878            final List<String> allCodePaths = getAllCodePaths();
15879            boolean mounted = PackageHelper.isContainerMounted(cid);
15880            if (mounted) {
15881                // Unmount first
15882                if (PackageHelper.unMountSdDir(cid)) {
15883                    mounted = false;
15884                }
15885            }
15886            if (!mounted && delete) {
15887                cleanUpResourcesLI(allCodePaths);
15888            }
15889            return !mounted;
15890        }
15891
15892        @Override
15893        int doPreCopy() {
15894            if (isFwdLocked()) {
15895                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15896                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15897                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15898                }
15899            }
15900
15901            return PackageManager.INSTALL_SUCCEEDED;
15902        }
15903
15904        @Override
15905        int doPostCopy(int uid) {
15906            if (isFwdLocked()) {
15907                if (uid < Process.FIRST_APPLICATION_UID
15908                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15909                                RES_FILE_NAME)) {
15910                    Slog.e(TAG, "Failed to finalize " + cid);
15911                    PackageHelper.destroySdDir(cid);
15912                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15913                }
15914            }
15915
15916            return PackageManager.INSTALL_SUCCEEDED;
15917        }
15918    }
15919
15920    /**
15921     * Logic to handle movement of existing installed applications.
15922     */
15923    class MoveInstallArgs extends InstallArgs {
15924        private File codeFile;
15925        private File resourceFile;
15926
15927        /** New install */
15928        MoveInstallArgs(InstallParams params) {
15929            super(params.origin, params.move, params.observer, params.installFlags,
15930                    params.installerPackageName, params.volumeUuid,
15931                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15932                    params.grantedRuntimePermissions,
15933                    params.traceMethod, params.traceCookie, params.certificates,
15934                    params.installReason);
15935        }
15936
15937        int copyApk(IMediaContainerService imcs, boolean temp) {
15938            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15939                    + move.fromUuid + " to " + move.toUuid);
15940            synchronized (mInstaller) {
15941                try {
15942                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15943                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15944                } catch (InstallerException e) {
15945                    Slog.w(TAG, "Failed to move app", e);
15946                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15947                }
15948            }
15949
15950            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15951            resourceFile = codeFile;
15952            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15953
15954            return PackageManager.INSTALL_SUCCEEDED;
15955        }
15956
15957        int doPreInstall(int status) {
15958            if (status != PackageManager.INSTALL_SUCCEEDED) {
15959                cleanUp(move.toUuid);
15960            }
15961            return status;
15962        }
15963
15964        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15965            if (status != PackageManager.INSTALL_SUCCEEDED) {
15966                cleanUp(move.toUuid);
15967                return false;
15968            }
15969
15970            // Reflect the move in app info
15971            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15972            pkg.setApplicationInfoCodePath(pkg.codePath);
15973            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15974            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15975            pkg.setApplicationInfoResourcePath(pkg.codePath);
15976            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15977            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15978
15979            return true;
15980        }
15981
15982        int doPostInstall(int status, int uid) {
15983            if (status == PackageManager.INSTALL_SUCCEEDED) {
15984                cleanUp(move.fromUuid);
15985            } else {
15986                cleanUp(move.toUuid);
15987            }
15988            return status;
15989        }
15990
15991        @Override
15992        String getCodePath() {
15993            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15994        }
15995
15996        @Override
15997        String getResourcePath() {
15998            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15999        }
16000
16001        private boolean cleanUp(String volumeUuid) {
16002            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16003                    move.dataAppName);
16004            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16005            final int[] userIds = sUserManager.getUserIds();
16006            synchronized (mInstallLock) {
16007                // Clean up both app data and code
16008                // All package moves are frozen until finished
16009                for (int userId : userIds) {
16010                    try {
16011                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16012                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16013                    } catch (InstallerException e) {
16014                        Slog.w(TAG, String.valueOf(e));
16015                    }
16016                }
16017                removeCodePathLI(codeFile);
16018            }
16019            return true;
16020        }
16021
16022        void cleanUpResourcesLI() {
16023            throw new UnsupportedOperationException();
16024        }
16025
16026        boolean doPostDeleteLI(boolean delete) {
16027            throw new UnsupportedOperationException();
16028        }
16029    }
16030
16031    static String getAsecPackageName(String packageCid) {
16032        int idx = packageCid.lastIndexOf("-");
16033        if (idx == -1) {
16034            return packageCid;
16035        }
16036        return packageCid.substring(0, idx);
16037    }
16038
16039    // Utility method used to create code paths based on package name and available index.
16040    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16041        String idxStr = "";
16042        int idx = 1;
16043        // Fall back to default value of idx=1 if prefix is not
16044        // part of oldCodePath
16045        if (oldCodePath != null) {
16046            String subStr = oldCodePath;
16047            // Drop the suffix right away
16048            if (suffix != null && subStr.endsWith(suffix)) {
16049                subStr = subStr.substring(0, subStr.length() - suffix.length());
16050            }
16051            // If oldCodePath already contains prefix find out the
16052            // ending index to either increment or decrement.
16053            int sidx = subStr.lastIndexOf(prefix);
16054            if (sidx != -1) {
16055                subStr = subStr.substring(sidx + prefix.length());
16056                if (subStr != null) {
16057                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16058                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16059                    }
16060                    try {
16061                        idx = Integer.parseInt(subStr);
16062                        if (idx <= 1) {
16063                            idx++;
16064                        } else {
16065                            idx--;
16066                        }
16067                    } catch(NumberFormatException e) {
16068                    }
16069                }
16070            }
16071        }
16072        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16073        return prefix + idxStr;
16074    }
16075
16076    private File getNextCodePath(File targetDir, String packageName) {
16077        File result;
16078        SecureRandom random = new SecureRandom();
16079        byte[] bytes = new byte[16];
16080        do {
16081            random.nextBytes(bytes);
16082            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16083            result = new File(targetDir, packageName + "-" + suffix);
16084        } while (result.exists());
16085        return result;
16086    }
16087
16088    // Utility method that returns the relative package path with respect
16089    // to the installation directory. Like say for /data/data/com.test-1.apk
16090    // string com.test-1 is returned.
16091    static String deriveCodePathName(String codePath) {
16092        if (codePath == null) {
16093            return null;
16094        }
16095        final File codeFile = new File(codePath);
16096        final String name = codeFile.getName();
16097        if (codeFile.isDirectory()) {
16098            return name;
16099        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16100            final int lastDot = name.lastIndexOf('.');
16101            return name.substring(0, lastDot);
16102        } else {
16103            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16104            return null;
16105        }
16106    }
16107
16108    static class PackageInstalledInfo {
16109        String name;
16110        int uid;
16111        // The set of users that originally had this package installed.
16112        int[] origUsers;
16113        // The set of users that now have this package installed.
16114        int[] newUsers;
16115        PackageParser.Package pkg;
16116        int returnCode;
16117        String returnMsg;
16118        PackageRemovedInfo removedInfo;
16119        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16120
16121        public void setError(int code, String msg) {
16122            setReturnCode(code);
16123            setReturnMessage(msg);
16124            Slog.w(TAG, msg);
16125        }
16126
16127        public void setError(String msg, PackageParserException e) {
16128            setReturnCode(e.error);
16129            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16130            Slog.w(TAG, msg, e);
16131        }
16132
16133        public void setError(String msg, PackageManagerException e) {
16134            returnCode = e.error;
16135            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16136            Slog.w(TAG, msg, e);
16137        }
16138
16139        public void setReturnCode(int returnCode) {
16140            this.returnCode = returnCode;
16141            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16142            for (int i = 0; i < childCount; i++) {
16143                addedChildPackages.valueAt(i).returnCode = returnCode;
16144            }
16145        }
16146
16147        private void setReturnMessage(String returnMsg) {
16148            this.returnMsg = returnMsg;
16149            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16150            for (int i = 0; i < childCount; i++) {
16151                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16152            }
16153        }
16154
16155        // In some error cases we want to convey more info back to the observer
16156        String origPackage;
16157        String origPermission;
16158    }
16159
16160    /*
16161     * Install a non-existing package.
16162     */
16163    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
16164            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
16165            PackageInstalledInfo res, int installReason) {
16166        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16167
16168        // Remember this for later, in case we need to rollback this install
16169        String pkgName = pkg.packageName;
16170
16171        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16172
16173        synchronized(mPackages) {
16174            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16175            if (renamedPackage != null) {
16176                // A package with the same name is already installed, though
16177                // it has been renamed to an older name.  The package we
16178                // are trying to install should be installed as an update to
16179                // the existing one, but that has not been requested, so bail.
16180                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16181                        + " without first uninstalling package running as "
16182                        + renamedPackage);
16183                return;
16184            }
16185            if (mPackages.containsKey(pkgName)) {
16186                // Don't allow installation over an existing package with the same name.
16187                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16188                        + " without first uninstalling.");
16189                return;
16190            }
16191        }
16192
16193        try {
16194            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
16195                    System.currentTimeMillis(), user);
16196
16197            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16198
16199            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16200                prepareAppDataAfterInstallLIF(newPackage);
16201
16202            } else {
16203                // Remove package from internal structures, but keep around any
16204                // data that might have already existed
16205                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16206                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16207            }
16208        } catch (PackageManagerException e) {
16209            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16210        }
16211
16212        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16213    }
16214
16215    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
16216        // Can't rotate keys during boot or if sharedUser.
16217        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
16218                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
16219            return false;
16220        }
16221        // app is using upgradeKeySets; make sure all are valid
16222        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16223        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
16224        for (int i = 0; i < upgradeKeySets.length; i++) {
16225            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
16226                Slog.wtf(TAG, "Package "
16227                         + (oldPs.name != null ? oldPs.name : "<null>")
16228                         + " contains upgrade-key-set reference to unknown key-set: "
16229                         + upgradeKeySets[i]
16230                         + " reverting to signatures check.");
16231                return false;
16232            }
16233        }
16234        return true;
16235    }
16236
16237    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
16238        // Upgrade keysets are being used.  Determine if new package has a superset of the
16239        // required keys.
16240        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
16241        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16242        for (int i = 0; i < upgradeKeySets.length; i++) {
16243            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
16244            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
16245                return true;
16246            }
16247        }
16248        return false;
16249    }
16250
16251    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16252        try (DigestInputStream digestStream =
16253                new DigestInputStream(new FileInputStream(file), digest)) {
16254            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16255        }
16256    }
16257
16258    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
16259            UserHandle user, String installerPackageName, PackageInstalledInfo res,
16260            int installReason) {
16261        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16262
16263        final PackageParser.Package oldPackage;
16264        final PackageSetting ps;
16265        final String pkgName = pkg.packageName;
16266        final int[] allUsers;
16267        final int[] installedUsers;
16268
16269        synchronized(mPackages) {
16270            oldPackage = mPackages.get(pkgName);
16271            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16272
16273            // don't allow upgrade to target a release SDK from a pre-release SDK
16274            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16275                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16276            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16277                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16278            if (oldTargetsPreRelease
16279                    && !newTargetsPreRelease
16280                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16281                Slog.w(TAG, "Can't install package targeting released sdk");
16282                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16283                return;
16284            }
16285
16286            ps = mSettings.mPackages.get(pkgName);
16287
16288            // verify signatures are valid
16289            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
16290                if (!checkUpgradeKeySetLP(ps, pkg)) {
16291                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16292                            "New package not signed by keys specified by upgrade-keysets: "
16293                                    + pkgName);
16294                    return;
16295                }
16296            } else {
16297                // default to original signature matching
16298                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
16299                        != PackageManager.SIGNATURE_MATCH) {
16300                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16301                            "New package has a different signature: " + pkgName);
16302                    return;
16303                }
16304            }
16305
16306            // don't allow a system upgrade unless the upgrade hash matches
16307            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
16308                byte[] digestBytes = null;
16309                try {
16310                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16311                    updateDigest(digest, new File(pkg.baseCodePath));
16312                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16313                        for (String path : pkg.splitCodePaths) {
16314                            updateDigest(digest, new File(path));
16315                        }
16316                    }
16317                    digestBytes = digest.digest();
16318                } catch (NoSuchAlgorithmException | IOException e) {
16319                    res.setError(INSTALL_FAILED_INVALID_APK,
16320                            "Could not compute hash: " + pkgName);
16321                    return;
16322                }
16323                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16324                    res.setError(INSTALL_FAILED_INVALID_APK,
16325                            "New package fails restrict-update check: " + pkgName);
16326                    return;
16327                }
16328                // retain upgrade restriction
16329                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16330            }
16331
16332            // Check for shared user id changes
16333            String invalidPackageName =
16334                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16335            if (invalidPackageName != null) {
16336                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16337                        "Package " + invalidPackageName + " tried to change user "
16338                                + oldPackage.mSharedUserId);
16339                return;
16340            }
16341
16342            // In case of rollback, remember per-user/profile install state
16343            allUsers = sUserManager.getUserIds();
16344            installedUsers = ps.queryInstalledUsers(allUsers, true);
16345
16346            // don't allow an upgrade from full to ephemeral
16347            if (isInstantApp) {
16348                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16349                    for (int currentUser : allUsers) {
16350                        if (!ps.getInstantApp(currentUser)) {
16351                            // can't downgrade from full to instant
16352                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16353                                    + " for user: " + currentUser);
16354                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16355                            return;
16356                        }
16357                    }
16358                } else if (!ps.getInstantApp(user.getIdentifier())) {
16359                    // can't downgrade from full to instant
16360                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16361                            + " for user: " + user.getIdentifier());
16362                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16363                    return;
16364                }
16365            }
16366        }
16367
16368        // Update what is removed
16369        res.removedInfo = new PackageRemovedInfo(this);
16370        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16371        res.removedInfo.removedPackage = oldPackage.packageName;
16372        res.removedInfo.installerPackageName = ps.installerPackageName;
16373        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16374        res.removedInfo.isUpdate = true;
16375        res.removedInfo.origUsers = installedUsers;
16376        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16377        for (int i = 0; i < installedUsers.length; i++) {
16378            final int userId = installedUsers[i];
16379            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16380        }
16381
16382        final int childCount = (oldPackage.childPackages != null)
16383                ? oldPackage.childPackages.size() : 0;
16384        for (int i = 0; i < childCount; i++) {
16385            boolean childPackageUpdated = false;
16386            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16387            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16388            if (res.addedChildPackages != null) {
16389                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16390                if (childRes != null) {
16391                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16392                    childRes.removedInfo.removedPackage = childPkg.packageName;
16393                    if (childPs != null) {
16394                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16395                    }
16396                    childRes.removedInfo.isUpdate = true;
16397                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16398                    childPackageUpdated = true;
16399                }
16400            }
16401            if (!childPackageUpdated) {
16402                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16403                childRemovedRes.removedPackage = childPkg.packageName;
16404                if (childPs != null) {
16405                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16406                }
16407                childRemovedRes.isUpdate = false;
16408                childRemovedRes.dataRemoved = true;
16409                synchronized (mPackages) {
16410                    if (childPs != null) {
16411                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16412                    }
16413                }
16414                if (res.removedInfo.removedChildPackages == null) {
16415                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16416                }
16417                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16418            }
16419        }
16420
16421        boolean sysPkg = (isSystemApp(oldPackage));
16422        if (sysPkg) {
16423            // Set the system/privileged flags as needed
16424            final boolean privileged =
16425                    (oldPackage.applicationInfo.privateFlags
16426                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16427            final int systemPolicyFlags = policyFlags
16428                    | PackageParser.PARSE_IS_SYSTEM
16429                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
16430
16431            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
16432                    user, allUsers, installerPackageName, res, installReason);
16433        } else {
16434            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
16435                    user, allUsers, installerPackageName, res, installReason);
16436        }
16437    }
16438
16439    public List<String> getPreviousCodePaths(String packageName) {
16440        final PackageSetting ps = mSettings.mPackages.get(packageName);
16441        final List<String> result = new ArrayList<String>();
16442        if (ps != null && ps.oldCodePaths != null) {
16443            result.addAll(ps.oldCodePaths);
16444        }
16445        return result;
16446    }
16447
16448    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16449            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16450            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16451            int installReason) {
16452        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16453                + deletedPackage);
16454
16455        String pkgName = deletedPackage.packageName;
16456        boolean deletedPkg = true;
16457        boolean addedPkg = false;
16458        boolean updatedSettings = false;
16459        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16460        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16461                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16462
16463        final long origUpdateTime = (pkg.mExtras != null)
16464                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16465
16466        // First delete the existing package while retaining the data directory
16467        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16468                res.removedInfo, true, pkg)) {
16469            // If the existing package wasn't successfully deleted
16470            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16471            deletedPkg = false;
16472        } else {
16473            // Successfully deleted the old package; proceed with replace.
16474
16475            // If deleted package lived in a container, give users a chance to
16476            // relinquish resources before killing.
16477            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16478                if (DEBUG_INSTALL) {
16479                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16480                }
16481                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16482                final ArrayList<String> pkgList = new ArrayList<String>(1);
16483                pkgList.add(deletedPackage.applicationInfo.packageName);
16484                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16485            }
16486
16487            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16488                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16489            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16490
16491            try {
16492                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
16493                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16494                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16495                        installReason);
16496
16497                // Update the in-memory copy of the previous code paths.
16498                PackageSetting ps = mSettings.mPackages.get(pkgName);
16499                if (!killApp) {
16500                    if (ps.oldCodePaths == null) {
16501                        ps.oldCodePaths = new ArraySet<>();
16502                    }
16503                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16504                    if (deletedPackage.splitCodePaths != null) {
16505                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16506                    }
16507                } else {
16508                    ps.oldCodePaths = null;
16509                }
16510                if (ps.childPackageNames != null) {
16511                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16512                        final String childPkgName = ps.childPackageNames.get(i);
16513                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16514                        childPs.oldCodePaths = ps.oldCodePaths;
16515                    }
16516                }
16517                // set instant app status, but, only if it's explicitly specified
16518                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16519                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16520                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16521                prepareAppDataAfterInstallLIF(newPackage);
16522                addedPkg = true;
16523                mDexManager.notifyPackageUpdated(newPackage.packageName,
16524                        newPackage.baseCodePath, newPackage.splitCodePaths);
16525            } catch (PackageManagerException e) {
16526                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16527            }
16528        }
16529
16530        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16531            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16532
16533            // Revert all internal state mutations and added folders for the failed install
16534            if (addedPkg) {
16535                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16536                        res.removedInfo, true, null);
16537            }
16538
16539            // Restore the old package
16540            if (deletedPkg) {
16541                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16542                File restoreFile = new File(deletedPackage.codePath);
16543                // Parse old package
16544                boolean oldExternal = isExternal(deletedPackage);
16545                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16546                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16547                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16548                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16549                try {
16550                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16551                            null);
16552                } catch (PackageManagerException e) {
16553                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16554                            + e.getMessage());
16555                    return;
16556                }
16557
16558                synchronized (mPackages) {
16559                    // Ensure the installer package name up to date
16560                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16561
16562                    // Update permissions for restored package
16563                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16564
16565                    mSettings.writeLPr();
16566                }
16567
16568                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16569            }
16570        } else {
16571            synchronized (mPackages) {
16572                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16573                if (ps != null) {
16574                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16575                    if (res.removedInfo.removedChildPackages != null) {
16576                        final int childCount = res.removedInfo.removedChildPackages.size();
16577                        // Iterate in reverse as we may modify the collection
16578                        for (int i = childCount - 1; i >= 0; i--) {
16579                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16580                            if (res.addedChildPackages.containsKey(childPackageName)) {
16581                                res.removedInfo.removedChildPackages.removeAt(i);
16582                            } else {
16583                                PackageRemovedInfo childInfo = res.removedInfo
16584                                        .removedChildPackages.valueAt(i);
16585                                childInfo.removedForAllUsers = mPackages.get(
16586                                        childInfo.removedPackage) == null;
16587                            }
16588                        }
16589                    }
16590                }
16591            }
16592        }
16593    }
16594
16595    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16596            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16597            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16598            int installReason) {
16599        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16600                + ", old=" + deletedPackage);
16601
16602        final boolean disabledSystem;
16603
16604        // Remove existing system package
16605        removePackageLI(deletedPackage, true);
16606
16607        synchronized (mPackages) {
16608            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16609        }
16610        if (!disabledSystem) {
16611            // We didn't need to disable the .apk as a current system package,
16612            // which means we are replacing another update that is already
16613            // installed.  We need to make sure to delete the older one's .apk.
16614            res.removedInfo.args = createInstallArgsForExisting(0,
16615                    deletedPackage.applicationInfo.getCodePath(),
16616                    deletedPackage.applicationInfo.getResourcePath(),
16617                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16618        } else {
16619            res.removedInfo.args = null;
16620        }
16621
16622        // Successfully disabled the old package. Now proceed with re-installation
16623        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16624                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16625        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16626
16627        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16628        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16629                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16630
16631        PackageParser.Package newPackage = null;
16632        try {
16633            // Add the package to the internal data structures
16634            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16635
16636            // Set the update and install times
16637            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16638            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16639                    System.currentTimeMillis());
16640
16641            // Update the package dynamic state if succeeded
16642            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16643                // Now that the install succeeded make sure we remove data
16644                // directories for any child package the update removed.
16645                final int deletedChildCount = (deletedPackage.childPackages != null)
16646                        ? deletedPackage.childPackages.size() : 0;
16647                final int newChildCount = (newPackage.childPackages != null)
16648                        ? newPackage.childPackages.size() : 0;
16649                for (int i = 0; i < deletedChildCount; i++) {
16650                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16651                    boolean childPackageDeleted = true;
16652                    for (int j = 0; j < newChildCount; j++) {
16653                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16654                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16655                            childPackageDeleted = false;
16656                            break;
16657                        }
16658                    }
16659                    if (childPackageDeleted) {
16660                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16661                                deletedChildPkg.packageName);
16662                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16663                            PackageRemovedInfo removedChildRes = res.removedInfo
16664                                    .removedChildPackages.get(deletedChildPkg.packageName);
16665                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16666                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16667                        }
16668                    }
16669                }
16670
16671                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16672                        installReason);
16673                prepareAppDataAfterInstallLIF(newPackage);
16674
16675                mDexManager.notifyPackageUpdated(newPackage.packageName,
16676                            newPackage.baseCodePath, newPackage.splitCodePaths);
16677            }
16678        } catch (PackageManagerException e) {
16679            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16680            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16681        }
16682
16683        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16684            // Re installation failed. Restore old information
16685            // Remove new pkg information
16686            if (newPackage != null) {
16687                removeInstalledPackageLI(newPackage, true);
16688            }
16689            // Add back the old system package
16690            try {
16691                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16692            } catch (PackageManagerException e) {
16693                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16694            }
16695
16696            synchronized (mPackages) {
16697                if (disabledSystem) {
16698                    enableSystemPackageLPw(deletedPackage);
16699                }
16700
16701                // Ensure the installer package name up to date
16702                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16703
16704                // Update permissions for restored package
16705                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16706
16707                mSettings.writeLPr();
16708            }
16709
16710            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16711                    + " after failed upgrade");
16712        }
16713    }
16714
16715    /**
16716     * Checks whether the parent or any of the child packages have a change shared
16717     * user. For a package to be a valid update the shred users of the parent and
16718     * the children should match. We may later support changing child shared users.
16719     * @param oldPkg The updated package.
16720     * @param newPkg The update package.
16721     * @return The shared user that change between the versions.
16722     */
16723    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16724            PackageParser.Package newPkg) {
16725        // Check parent shared user
16726        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16727            return newPkg.packageName;
16728        }
16729        // Check child shared users
16730        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16731        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16732        for (int i = 0; i < newChildCount; i++) {
16733            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16734            // If this child was present, did it have the same shared user?
16735            for (int j = 0; j < oldChildCount; j++) {
16736                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16737                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16738                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16739                    return newChildPkg.packageName;
16740                }
16741            }
16742        }
16743        return null;
16744    }
16745
16746    private void removeNativeBinariesLI(PackageSetting ps) {
16747        // Remove the lib path for the parent package
16748        if (ps != null) {
16749            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16750            // Remove the lib path for the child packages
16751            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16752            for (int i = 0; i < childCount; i++) {
16753                PackageSetting childPs = null;
16754                synchronized (mPackages) {
16755                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16756                }
16757                if (childPs != null) {
16758                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16759                            .legacyNativeLibraryPathString);
16760                }
16761            }
16762        }
16763    }
16764
16765    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16766        // Enable the parent package
16767        mSettings.enableSystemPackageLPw(pkg.packageName);
16768        // Enable the child packages
16769        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16770        for (int i = 0; i < childCount; i++) {
16771            PackageParser.Package childPkg = pkg.childPackages.get(i);
16772            mSettings.enableSystemPackageLPw(childPkg.packageName);
16773        }
16774    }
16775
16776    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16777            PackageParser.Package newPkg) {
16778        // Disable the parent package (parent always replaced)
16779        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16780        // Disable the child packages
16781        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16782        for (int i = 0; i < childCount; i++) {
16783            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16784            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16785            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16786        }
16787        return disabled;
16788    }
16789
16790    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16791            String installerPackageName) {
16792        // Enable the parent package
16793        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16794        // Enable the child packages
16795        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16796        for (int i = 0; i < childCount; i++) {
16797            PackageParser.Package childPkg = pkg.childPackages.get(i);
16798            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16799        }
16800    }
16801
16802    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16803        // Collect all used permissions in the UID
16804        ArraySet<String> usedPermissions = new ArraySet<>();
16805        final int packageCount = su.packages.size();
16806        for (int i = 0; i < packageCount; i++) {
16807            PackageSetting ps = su.packages.valueAt(i);
16808            if (ps.pkg == null) {
16809                continue;
16810            }
16811            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16812            for (int j = 0; j < requestedPermCount; j++) {
16813                String permission = ps.pkg.requestedPermissions.get(j);
16814                BasePermission bp = mSettings.mPermissions.get(permission);
16815                if (bp != null) {
16816                    usedPermissions.add(permission);
16817                }
16818            }
16819        }
16820
16821        PermissionsState permissionsState = su.getPermissionsState();
16822        // Prune install permissions
16823        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16824        final int installPermCount = installPermStates.size();
16825        for (int i = installPermCount - 1; i >= 0;  i--) {
16826            PermissionState permissionState = installPermStates.get(i);
16827            if (!usedPermissions.contains(permissionState.getName())) {
16828                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16829                if (bp != null) {
16830                    permissionsState.revokeInstallPermission(bp);
16831                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16832                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16833                }
16834            }
16835        }
16836
16837        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16838
16839        // Prune runtime permissions
16840        for (int userId : allUserIds) {
16841            List<PermissionState> runtimePermStates = permissionsState
16842                    .getRuntimePermissionStates(userId);
16843            final int runtimePermCount = runtimePermStates.size();
16844            for (int i = runtimePermCount - 1; i >= 0; i--) {
16845                PermissionState permissionState = runtimePermStates.get(i);
16846                if (!usedPermissions.contains(permissionState.getName())) {
16847                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16848                    if (bp != null) {
16849                        permissionsState.revokeRuntimePermission(bp, userId);
16850                        permissionsState.updatePermissionFlags(bp, userId,
16851                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16852                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16853                                runtimePermissionChangedUserIds, userId);
16854                    }
16855                }
16856            }
16857        }
16858
16859        return runtimePermissionChangedUserIds;
16860    }
16861
16862    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16863            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16864        // Update the parent package setting
16865        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16866                res, user, installReason);
16867        // Update the child packages setting
16868        final int childCount = (newPackage.childPackages != null)
16869                ? newPackage.childPackages.size() : 0;
16870        for (int i = 0; i < childCount; i++) {
16871            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16872            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16873            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16874                    childRes.origUsers, childRes, user, installReason);
16875        }
16876    }
16877
16878    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16879            String installerPackageName, int[] allUsers, int[] installedForUsers,
16880            PackageInstalledInfo res, UserHandle user, int installReason) {
16881        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16882
16883        String pkgName = newPackage.packageName;
16884        synchronized (mPackages) {
16885            //write settings. the installStatus will be incomplete at this stage.
16886            //note that the new package setting would have already been
16887            //added to mPackages. It hasn't been persisted yet.
16888            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16889            // TODO: Remove this write? It's also written at the end of this method
16890            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16891            mSettings.writeLPr();
16892            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16893        }
16894
16895        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16896        synchronized (mPackages) {
16897            updatePermissionsLPw(newPackage.packageName, newPackage,
16898                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16899                            ? UPDATE_PERMISSIONS_ALL : 0));
16900            // For system-bundled packages, we assume that installing an upgraded version
16901            // of the package implies that the user actually wants to run that new code,
16902            // so we enable the package.
16903            PackageSetting ps = mSettings.mPackages.get(pkgName);
16904            final int userId = user.getIdentifier();
16905            if (ps != null) {
16906                if (isSystemApp(newPackage)) {
16907                    if (DEBUG_INSTALL) {
16908                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16909                    }
16910                    // Enable system package for requested users
16911                    if (res.origUsers != null) {
16912                        for (int origUserId : res.origUsers) {
16913                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16914                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16915                                        origUserId, installerPackageName);
16916                            }
16917                        }
16918                    }
16919                    // Also convey the prior install/uninstall state
16920                    if (allUsers != null && installedForUsers != null) {
16921                        for (int currentUserId : allUsers) {
16922                            final boolean installed = ArrayUtils.contains(
16923                                    installedForUsers, currentUserId);
16924                            if (DEBUG_INSTALL) {
16925                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16926                            }
16927                            ps.setInstalled(installed, currentUserId);
16928                        }
16929                        // these install state changes will be persisted in the
16930                        // upcoming call to mSettings.writeLPr().
16931                    }
16932                }
16933                // It's implied that when a user requests installation, they want the app to be
16934                // installed and enabled.
16935                if (userId != UserHandle.USER_ALL) {
16936                    ps.setInstalled(true, userId);
16937                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16938                }
16939
16940                // When replacing an existing package, preserve the original install reason for all
16941                // users that had the package installed before.
16942                final Set<Integer> previousUserIds = new ArraySet<>();
16943                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16944                    final int installReasonCount = res.removedInfo.installReasons.size();
16945                    for (int i = 0; i < installReasonCount; i++) {
16946                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16947                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16948                        ps.setInstallReason(previousInstallReason, previousUserId);
16949                        previousUserIds.add(previousUserId);
16950                    }
16951                }
16952
16953                // Set install reason for users that are having the package newly installed.
16954                if (userId == UserHandle.USER_ALL) {
16955                    for (int currentUserId : sUserManager.getUserIds()) {
16956                        if (!previousUserIds.contains(currentUserId)) {
16957                            ps.setInstallReason(installReason, currentUserId);
16958                        }
16959                    }
16960                } else if (!previousUserIds.contains(userId)) {
16961                    ps.setInstallReason(installReason, userId);
16962                }
16963                mSettings.writeKernelMappingLPr(ps);
16964            }
16965            res.name = pkgName;
16966            res.uid = newPackage.applicationInfo.uid;
16967            res.pkg = newPackage;
16968            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16969            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16970            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16971            //to update install status
16972            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16973            mSettings.writeLPr();
16974            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16975        }
16976
16977        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16978    }
16979
16980    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16981        try {
16982            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16983            installPackageLI(args, res);
16984        } finally {
16985            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16986        }
16987    }
16988
16989    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16990        final int installFlags = args.installFlags;
16991        final String installerPackageName = args.installerPackageName;
16992        final String volumeUuid = args.volumeUuid;
16993        final File tmpPackageFile = new File(args.getCodePath());
16994        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16995        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16996                || (args.volumeUuid != null));
16997        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16998        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16999        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17000        boolean replace = false;
17001        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17002        if (args.move != null) {
17003            // moving a complete application; perform an initial scan on the new install location
17004            scanFlags |= SCAN_INITIAL;
17005        }
17006        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17007            scanFlags |= SCAN_DONT_KILL_APP;
17008        }
17009        if (instantApp) {
17010            scanFlags |= SCAN_AS_INSTANT_APP;
17011        }
17012        if (fullApp) {
17013            scanFlags |= SCAN_AS_FULL_APP;
17014        }
17015
17016        // Result object to be returned
17017        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17018
17019        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17020
17021        // Sanity check
17022        if (instantApp && (forwardLocked || onExternal)) {
17023            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17024                    + " external=" + onExternal);
17025            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17026            return;
17027        }
17028
17029        // Retrieve PackageSettings and parse package
17030        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17031                | PackageParser.PARSE_ENFORCE_CODE
17032                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17033                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17034                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17035                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17036        PackageParser pp = new PackageParser();
17037        pp.setSeparateProcesses(mSeparateProcesses);
17038        pp.setDisplayMetrics(mMetrics);
17039        pp.setCallback(mPackageParserCallback);
17040
17041        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17042        final PackageParser.Package pkg;
17043        try {
17044            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17045        } catch (PackageParserException e) {
17046            res.setError("Failed parse during installPackageLI", e);
17047            return;
17048        } finally {
17049            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17050        }
17051
17052        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17053        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17054            Slog.w(TAG, "Instant app package " + pkg.packageName
17055                    + " does not target O, this will be a fatal error.");
17056            // STOPSHIP: Make this a fatal error
17057            pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O;
17058        }
17059        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17060            Slog.w(TAG, "Instant app package " + pkg.packageName
17061                    + " does not target targetSandboxVersion 2, this will be a fatal error.");
17062            // STOPSHIP: Make this a fatal error
17063            pkg.applicationInfo.targetSandboxVersion = 2;
17064        }
17065
17066        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17067            // Static shared libraries have synthetic package names
17068            renameStaticSharedLibraryPackage(pkg);
17069
17070            // No static shared libs on external storage
17071            if (onExternal) {
17072                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17073                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17074                        "Packages declaring static-shared libs cannot be updated");
17075                return;
17076            }
17077        }
17078
17079        // If we are installing a clustered package add results for the children
17080        if (pkg.childPackages != null) {
17081            synchronized (mPackages) {
17082                final int childCount = pkg.childPackages.size();
17083                for (int i = 0; i < childCount; i++) {
17084                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17085                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17086                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17087                    childRes.pkg = childPkg;
17088                    childRes.name = childPkg.packageName;
17089                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17090                    if (childPs != null) {
17091                        childRes.origUsers = childPs.queryInstalledUsers(
17092                                sUserManager.getUserIds(), true);
17093                    }
17094                    if ((mPackages.containsKey(childPkg.packageName))) {
17095                        childRes.removedInfo = new PackageRemovedInfo(this);
17096                        childRes.removedInfo.removedPackage = childPkg.packageName;
17097                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17098                    }
17099                    if (res.addedChildPackages == null) {
17100                        res.addedChildPackages = new ArrayMap<>();
17101                    }
17102                    res.addedChildPackages.put(childPkg.packageName, childRes);
17103                }
17104            }
17105        }
17106
17107        // If package doesn't declare API override, mark that we have an install
17108        // time CPU ABI override.
17109        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17110            pkg.cpuAbiOverride = args.abiOverride;
17111        }
17112
17113        String pkgName = res.name = pkg.packageName;
17114        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17115            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17116                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17117                return;
17118            }
17119        }
17120
17121        try {
17122            // either use what we've been given or parse directly from the APK
17123            if (args.certificates != null) {
17124                try {
17125                    PackageParser.populateCertificates(pkg, args.certificates);
17126                } catch (PackageParserException e) {
17127                    // there was something wrong with the certificates we were given;
17128                    // try to pull them from the APK
17129                    PackageParser.collectCertificates(pkg, parseFlags);
17130                }
17131            } else {
17132                PackageParser.collectCertificates(pkg, parseFlags);
17133            }
17134        } catch (PackageParserException e) {
17135            res.setError("Failed collect during installPackageLI", e);
17136            return;
17137        }
17138
17139        // Get rid of all references to package scan path via parser.
17140        pp = null;
17141        String oldCodePath = null;
17142        boolean systemApp = false;
17143        synchronized (mPackages) {
17144            // Check if installing already existing package
17145            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17146                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17147                if (pkg.mOriginalPackages != null
17148                        && pkg.mOriginalPackages.contains(oldName)
17149                        && mPackages.containsKey(oldName)) {
17150                    // This package is derived from an original package,
17151                    // and this device has been updating from that original
17152                    // name.  We must continue using the original name, so
17153                    // rename the new package here.
17154                    pkg.setPackageName(oldName);
17155                    pkgName = pkg.packageName;
17156                    replace = true;
17157                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17158                            + oldName + " pkgName=" + pkgName);
17159                } else if (mPackages.containsKey(pkgName)) {
17160                    // This package, under its official name, already exists
17161                    // on the device; we should replace it.
17162                    replace = true;
17163                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17164                }
17165
17166                // Child packages are installed through the parent package
17167                if (pkg.parentPackage != null) {
17168                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17169                            "Package " + pkg.packageName + " is child of package "
17170                                    + pkg.parentPackage.parentPackage + ". Child packages "
17171                                    + "can be updated only through the parent package.");
17172                    return;
17173                }
17174
17175                if (replace) {
17176                    // Prevent apps opting out from runtime permissions
17177                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17178                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17179                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17180                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17181                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17182                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17183                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17184                                        + " doesn't support runtime permissions but the old"
17185                                        + " target SDK " + oldTargetSdk + " does.");
17186                        return;
17187                    }
17188                    // Prevent apps from downgrading their targetSandbox.
17189                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17190                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17191                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17192                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17193                                "Package " + pkg.packageName + " new target sandbox "
17194                                + newTargetSandbox + " is incompatible with the previous value of"
17195                                + oldTargetSandbox + ".");
17196                        return;
17197                    }
17198
17199                    // Prevent installing of child packages
17200                    if (oldPackage.parentPackage != null) {
17201                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17202                                "Package " + pkg.packageName + " is child of package "
17203                                        + oldPackage.parentPackage + ". Child packages "
17204                                        + "can be updated only through the parent package.");
17205                        return;
17206                    }
17207                }
17208            }
17209
17210            PackageSetting ps = mSettings.mPackages.get(pkgName);
17211            if (ps != null) {
17212                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17213
17214                // Static shared libs have same package with different versions where
17215                // we internally use a synthetic package name to allow multiple versions
17216                // of the same package, therefore we need to compare signatures against
17217                // the package setting for the latest library version.
17218                PackageSetting signatureCheckPs = ps;
17219                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17220                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17221                    if (libraryEntry != null) {
17222                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17223                    }
17224                }
17225
17226                // Quick sanity check that we're signed correctly if updating;
17227                // we'll check this again later when scanning, but we want to
17228                // bail early here before tripping over redefined permissions.
17229                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
17230                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
17231                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17232                                + pkg.packageName + " upgrade keys do not match the "
17233                                + "previously installed version");
17234                        return;
17235                    }
17236                } else {
17237                    try {
17238                        verifySignaturesLP(signatureCheckPs, pkg);
17239                    } catch (PackageManagerException e) {
17240                        res.setError(e.error, e.getMessage());
17241                        return;
17242                    }
17243                }
17244
17245                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17246                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17247                    systemApp = (ps.pkg.applicationInfo.flags &
17248                            ApplicationInfo.FLAG_SYSTEM) != 0;
17249                }
17250                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17251            }
17252
17253            int N = pkg.permissions.size();
17254            for (int i = N-1; i >= 0; i--) {
17255                PackageParser.Permission perm = pkg.permissions.get(i);
17256                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
17257
17258                // Don't allow anyone but the system to define ephemeral permissions.
17259                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
17260                        && !systemApp) {
17261                    Slog.w(TAG, "Non-System package " + pkg.packageName
17262                            + " attempting to delcare ephemeral permission "
17263                            + perm.info.name + "; Removing ephemeral.");
17264                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
17265                }
17266                // Check whether the newly-scanned package wants to define an already-defined perm
17267                if (bp != null) {
17268                    // If the defining package is signed with our cert, it's okay.  This
17269                    // also includes the "updating the same package" case, of course.
17270                    // "updating same package" could also involve key-rotation.
17271                    final boolean sigsOk;
17272                    if (bp.sourcePackage.equals(pkg.packageName)
17273                            && (bp.packageSetting instanceof PackageSetting)
17274                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
17275                                    scanFlags))) {
17276                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
17277                    } else {
17278                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
17279                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
17280                    }
17281                    if (!sigsOk) {
17282                        // If the owning package is the system itself, we log but allow
17283                        // install to proceed; we fail the install on all other permission
17284                        // redefinitions.
17285                        if (!bp.sourcePackage.equals("android")) {
17286                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17287                                    + pkg.packageName + " attempting to redeclare permission "
17288                                    + perm.info.name + " already owned by " + bp.sourcePackage);
17289                            res.origPermission = perm.info.name;
17290                            res.origPackage = bp.sourcePackage;
17291                            return;
17292                        } else {
17293                            Slog.w(TAG, "Package " + pkg.packageName
17294                                    + " attempting to redeclare system permission "
17295                                    + perm.info.name + "; ignoring new declaration");
17296                            pkg.permissions.remove(i);
17297                        }
17298                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17299                        // Prevent apps to change protection level to dangerous from any other
17300                        // type as this would allow a privilege escalation where an app adds a
17301                        // normal/signature permission in other app's group and later redefines
17302                        // it as dangerous leading to the group auto-grant.
17303                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17304                                == PermissionInfo.PROTECTION_DANGEROUS) {
17305                            if (bp != null && !bp.isRuntime()) {
17306                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17307                                        + "non-runtime permission " + perm.info.name
17308                                        + " to runtime; keeping old protection level");
17309                                perm.info.protectionLevel = bp.protectionLevel;
17310                            }
17311                        }
17312                    }
17313                }
17314            }
17315        }
17316
17317        if (systemApp) {
17318            if (onExternal) {
17319                // Abort update; system app can't be replaced with app on sdcard
17320                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17321                        "Cannot install updates to system apps on sdcard");
17322                return;
17323            } else if (instantApp) {
17324                // Abort update; system app can't be replaced with an instant app
17325                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17326                        "Cannot update a system app with an instant app");
17327                return;
17328            }
17329        }
17330
17331        if (args.move != null) {
17332            // We did an in-place move, so dex is ready to roll
17333            scanFlags |= SCAN_NO_DEX;
17334            scanFlags |= SCAN_MOVE;
17335
17336            synchronized (mPackages) {
17337                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17338                if (ps == null) {
17339                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17340                            "Missing settings for moved package " + pkgName);
17341                }
17342
17343                // We moved the entire application as-is, so bring over the
17344                // previously derived ABI information.
17345                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17346                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17347            }
17348
17349        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17350            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17351            scanFlags |= SCAN_NO_DEX;
17352
17353            try {
17354                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17355                    args.abiOverride : pkg.cpuAbiOverride);
17356                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
17357                        true /*extractLibs*/, mAppLib32InstallDir);
17358            } catch (PackageManagerException pme) {
17359                Slog.e(TAG, "Error deriving application ABI", pme);
17360                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17361                return;
17362            }
17363
17364            // Shared libraries for the package need to be updated.
17365            synchronized (mPackages) {
17366                try {
17367                    updateSharedLibrariesLPr(pkg, null);
17368                } catch (PackageManagerException e) {
17369                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17370                }
17371            }
17372
17373            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17374            // Do not run PackageDexOptimizer through the local performDexOpt
17375            // method because `pkg` may not be in `mPackages` yet.
17376            //
17377            // Also, don't fail application installs if the dexopt step fails.
17378            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17379                    null /* instructionSets */, false /* checkProfiles */,
17380                    getCompilerFilterForReason(REASON_INSTALL),
17381                    getOrCreateCompilerPackageStats(pkg),
17382                    mDexManager.isUsedByOtherApps(pkg.packageName));
17383            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17384
17385            // Notify BackgroundDexOptService that the package has been changed.
17386            // If this is an update of a package which used to fail to compile,
17387            // BDOS will remove it from its blacklist.
17388            // TODO: Layering violation
17389            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17390        }
17391
17392        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17393            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17394            return;
17395        }
17396
17397        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17398
17399        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17400                "installPackageLI")) {
17401            if (replace) {
17402                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17403                    // Static libs have a synthetic package name containing the version
17404                    // and cannot be updated as an update would get a new package name,
17405                    // unless this is the exact same version code which is useful for
17406                    // development.
17407                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17408                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
17409                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17410                                + "static-shared libs cannot be updated");
17411                        return;
17412                    }
17413                }
17414                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
17415                        installerPackageName, res, args.installReason);
17416            } else {
17417                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17418                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17419            }
17420        }
17421
17422        synchronized (mPackages) {
17423            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17424            if (ps != null) {
17425                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17426                ps.setUpdateAvailable(false /*updateAvailable*/);
17427            }
17428
17429            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17430            for (int i = 0; i < childCount; i++) {
17431                PackageParser.Package childPkg = pkg.childPackages.get(i);
17432                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17433                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17434                if (childPs != null) {
17435                    childRes.newUsers = childPs.queryInstalledUsers(
17436                            sUserManager.getUserIds(), true);
17437                }
17438            }
17439
17440            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17441                updateSequenceNumberLP(pkgName, res.newUsers);
17442                updateInstantAppInstallerLocked(pkgName);
17443            }
17444        }
17445    }
17446
17447    private void startIntentFilterVerifications(int userId, boolean replacing,
17448            PackageParser.Package pkg) {
17449        if (mIntentFilterVerifierComponent == null) {
17450            Slog.w(TAG, "No IntentFilter verification will not be done as "
17451                    + "there is no IntentFilterVerifier available!");
17452            return;
17453        }
17454
17455        final int verifierUid = getPackageUid(
17456                mIntentFilterVerifierComponent.getPackageName(),
17457                MATCH_DEBUG_TRIAGED_MISSING,
17458                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17459
17460        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17461        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17462        mHandler.sendMessage(msg);
17463
17464        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17465        for (int i = 0; i < childCount; i++) {
17466            PackageParser.Package childPkg = pkg.childPackages.get(i);
17467            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17468            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17469            mHandler.sendMessage(msg);
17470        }
17471    }
17472
17473    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17474            PackageParser.Package pkg) {
17475        int size = pkg.activities.size();
17476        if (size == 0) {
17477            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17478                    "No activity, so no need to verify any IntentFilter!");
17479            return;
17480        }
17481
17482        final boolean hasDomainURLs = hasDomainURLs(pkg);
17483        if (!hasDomainURLs) {
17484            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17485                    "No domain URLs, so no need to verify any IntentFilter!");
17486            return;
17487        }
17488
17489        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17490                + " if any IntentFilter from the " + size
17491                + " Activities needs verification ...");
17492
17493        int count = 0;
17494        final String packageName = pkg.packageName;
17495
17496        synchronized (mPackages) {
17497            // If this is a new install and we see that we've already run verification for this
17498            // package, we have nothing to do: it means the state was restored from backup.
17499            if (!replacing) {
17500                IntentFilterVerificationInfo ivi =
17501                        mSettings.getIntentFilterVerificationLPr(packageName);
17502                if (ivi != null) {
17503                    if (DEBUG_DOMAIN_VERIFICATION) {
17504                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17505                                + ivi.getStatusString());
17506                    }
17507                    return;
17508                }
17509            }
17510
17511            // If any filters need to be verified, then all need to be.
17512            boolean needToVerify = false;
17513            for (PackageParser.Activity a : pkg.activities) {
17514                for (ActivityIntentInfo filter : a.intents) {
17515                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17516                        if (DEBUG_DOMAIN_VERIFICATION) {
17517                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
17518                        }
17519                        needToVerify = true;
17520                        break;
17521                    }
17522                }
17523            }
17524
17525            if (needToVerify) {
17526                final int verificationId = mIntentFilterVerificationToken++;
17527                for (PackageParser.Activity a : pkg.activities) {
17528                    for (ActivityIntentInfo filter : a.intents) {
17529                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17530                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17531                                    "Verification needed for IntentFilter:" + filter.toString());
17532                            mIntentFilterVerifier.addOneIntentFilterVerification(
17533                                    verifierUid, userId, verificationId, filter, packageName);
17534                            count++;
17535                        }
17536                    }
17537                }
17538            }
17539        }
17540
17541        if (count > 0) {
17542            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17543                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17544                    +  " for userId:" + userId);
17545            mIntentFilterVerifier.startVerifications(userId);
17546        } else {
17547            if (DEBUG_DOMAIN_VERIFICATION) {
17548                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17549            }
17550        }
17551    }
17552
17553    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17554        final ComponentName cn  = filter.activity.getComponentName();
17555        final String packageName = cn.getPackageName();
17556
17557        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17558                packageName);
17559        if (ivi == null) {
17560            return true;
17561        }
17562        int status = ivi.getStatus();
17563        switch (status) {
17564            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17565            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17566                return true;
17567
17568            default:
17569                // Nothing to do
17570                return false;
17571        }
17572    }
17573
17574    private static boolean isMultiArch(ApplicationInfo info) {
17575        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17576    }
17577
17578    private static boolean isExternal(PackageParser.Package pkg) {
17579        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17580    }
17581
17582    private static boolean isExternal(PackageSetting ps) {
17583        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17584    }
17585
17586    private static boolean isSystemApp(PackageParser.Package pkg) {
17587        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17588    }
17589
17590    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17591        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17592    }
17593
17594    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17595        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17596    }
17597
17598    private static boolean isSystemApp(PackageSetting ps) {
17599        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17600    }
17601
17602    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17603        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17604    }
17605
17606    private int packageFlagsToInstallFlags(PackageSetting ps) {
17607        int installFlags = 0;
17608        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17609            // This existing package was an external ASEC install when we have
17610            // the external flag without a UUID
17611            installFlags |= PackageManager.INSTALL_EXTERNAL;
17612        }
17613        if (ps.isForwardLocked()) {
17614            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17615        }
17616        return installFlags;
17617    }
17618
17619    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17620        if (isExternal(pkg)) {
17621            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17622                return StorageManager.UUID_PRIMARY_PHYSICAL;
17623            } else {
17624                return pkg.volumeUuid;
17625            }
17626        } else {
17627            return StorageManager.UUID_PRIVATE_INTERNAL;
17628        }
17629    }
17630
17631    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17632        if (isExternal(pkg)) {
17633            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17634                return mSettings.getExternalVersion();
17635            } else {
17636                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17637            }
17638        } else {
17639            return mSettings.getInternalVersion();
17640        }
17641    }
17642
17643    private void deleteTempPackageFiles() {
17644        final FilenameFilter filter = new FilenameFilter() {
17645            public boolean accept(File dir, String name) {
17646                return name.startsWith("vmdl") && name.endsWith(".tmp");
17647            }
17648        };
17649        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17650            file.delete();
17651        }
17652    }
17653
17654    @Override
17655    public void deletePackageAsUser(String packageName, int versionCode,
17656            IPackageDeleteObserver observer, int userId, int flags) {
17657        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17658                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17659    }
17660
17661    @Override
17662    public void deletePackageVersioned(VersionedPackage versionedPackage,
17663            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17664        mContext.enforceCallingOrSelfPermission(
17665                android.Manifest.permission.DELETE_PACKAGES, null);
17666        Preconditions.checkNotNull(versionedPackage);
17667        Preconditions.checkNotNull(observer);
17668        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17669                PackageManager.VERSION_CODE_HIGHEST,
17670                Integer.MAX_VALUE, "versionCode must be >= -1");
17671
17672        final String packageName = versionedPackage.getPackageName();
17673        // TODO: We will change version code to long, so in the new API it is long
17674        final int versionCode = (int) versionedPackage.getVersionCode();
17675        final String internalPackageName;
17676        synchronized (mPackages) {
17677            // Normalize package name to handle renamed packages and static libs
17678            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17679                    // TODO: We will change version code to long, so in the new API it is long
17680                    (int) versionedPackage.getVersionCode());
17681        }
17682
17683        final int uid = Binder.getCallingUid();
17684        if (!isOrphaned(internalPackageName)
17685                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17686            try {
17687                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17688                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17689                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17690                observer.onUserActionRequired(intent);
17691            } catch (RemoteException re) {
17692            }
17693            return;
17694        }
17695        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17696        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17697        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17698            mContext.enforceCallingOrSelfPermission(
17699                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17700                    "deletePackage for user " + userId);
17701        }
17702
17703        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17704            try {
17705                observer.onPackageDeleted(packageName,
17706                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17707            } catch (RemoteException re) {
17708            }
17709            return;
17710        }
17711
17712        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17713            try {
17714                observer.onPackageDeleted(packageName,
17715                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17716            } catch (RemoteException re) {
17717            }
17718            return;
17719        }
17720
17721        if (DEBUG_REMOVE) {
17722            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17723                    + " deleteAllUsers: " + deleteAllUsers + " version="
17724                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17725                    ? "VERSION_CODE_HIGHEST" : versionCode));
17726        }
17727        // Queue up an async operation since the package deletion may take a little while.
17728        mHandler.post(new Runnable() {
17729            public void run() {
17730                mHandler.removeCallbacks(this);
17731                int returnCode;
17732                if (!deleteAllUsers) {
17733                    returnCode = deletePackageX(internalPackageName, versionCode,
17734                            userId, deleteFlags);
17735                } else {
17736                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17737                            internalPackageName, users);
17738                    // If nobody is blocking uninstall, proceed with delete for all users
17739                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17740                        returnCode = deletePackageX(internalPackageName, versionCode,
17741                                userId, deleteFlags);
17742                    } else {
17743                        // Otherwise uninstall individually for users with blockUninstalls=false
17744                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17745                        for (int userId : users) {
17746                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17747                                returnCode = deletePackageX(internalPackageName, versionCode,
17748                                        userId, userFlags);
17749                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17750                                    Slog.w(TAG, "Package delete failed for user " + userId
17751                                            + ", returnCode " + returnCode);
17752                                }
17753                            }
17754                        }
17755                        // The app has only been marked uninstalled for certain users.
17756                        // We still need to report that delete was blocked
17757                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17758                    }
17759                }
17760                try {
17761                    observer.onPackageDeleted(packageName, returnCode, null);
17762                } catch (RemoteException e) {
17763                    Log.i(TAG, "Observer no longer exists.");
17764                } //end catch
17765            } //end run
17766        });
17767    }
17768
17769    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17770        if (pkg.staticSharedLibName != null) {
17771            return pkg.manifestPackageName;
17772        }
17773        return pkg.packageName;
17774    }
17775
17776    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17777        // Handle renamed packages
17778        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17779        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17780
17781        // Is this a static library?
17782        SparseArray<SharedLibraryEntry> versionedLib =
17783                mStaticLibsByDeclaringPackage.get(packageName);
17784        if (versionedLib == null || versionedLib.size() <= 0) {
17785            return packageName;
17786        }
17787
17788        // Figure out which lib versions the caller can see
17789        SparseIntArray versionsCallerCanSee = null;
17790        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17791        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17792                && callingAppId != Process.ROOT_UID) {
17793            versionsCallerCanSee = new SparseIntArray();
17794            String libName = versionedLib.valueAt(0).info.getName();
17795            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17796            if (uidPackages != null) {
17797                for (String uidPackage : uidPackages) {
17798                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17799                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17800                    if (libIdx >= 0) {
17801                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17802                        versionsCallerCanSee.append(libVersion, libVersion);
17803                    }
17804                }
17805            }
17806        }
17807
17808        // Caller can see nothing - done
17809        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17810            return packageName;
17811        }
17812
17813        // Find the version the caller can see and the app version code
17814        SharedLibraryEntry highestVersion = null;
17815        final int versionCount = versionedLib.size();
17816        for (int i = 0; i < versionCount; i++) {
17817            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17818            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17819                    libEntry.info.getVersion()) < 0) {
17820                continue;
17821            }
17822            // TODO: We will change version code to long, so in the new API it is long
17823            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17824            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17825                if (libVersionCode == versionCode) {
17826                    return libEntry.apk;
17827                }
17828            } else if (highestVersion == null) {
17829                highestVersion = libEntry;
17830            } else if (libVersionCode  > highestVersion.info
17831                    .getDeclaringPackage().getVersionCode()) {
17832                highestVersion = libEntry;
17833            }
17834        }
17835
17836        if (highestVersion != null) {
17837            return highestVersion.apk;
17838        }
17839
17840        return packageName;
17841    }
17842
17843    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17844        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17845              || callingUid == Process.SYSTEM_UID) {
17846            return true;
17847        }
17848        final int callingUserId = UserHandle.getUserId(callingUid);
17849        // If the caller installed the pkgName, then allow it to silently uninstall.
17850        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17851            return true;
17852        }
17853
17854        // Allow package verifier to silently uninstall.
17855        if (mRequiredVerifierPackage != null &&
17856                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17857            return true;
17858        }
17859
17860        // Allow package uninstaller to silently uninstall.
17861        if (mRequiredUninstallerPackage != null &&
17862                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17863            return true;
17864        }
17865
17866        // Allow storage manager to silently uninstall.
17867        if (mStorageManagerPackage != null &&
17868                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17869            return true;
17870        }
17871        return false;
17872    }
17873
17874    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17875        int[] result = EMPTY_INT_ARRAY;
17876        for (int userId : userIds) {
17877            if (getBlockUninstallForUser(packageName, userId)) {
17878                result = ArrayUtils.appendInt(result, userId);
17879            }
17880        }
17881        return result;
17882    }
17883
17884    @Override
17885    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17886        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17887    }
17888
17889    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17890        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17891                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17892        try {
17893            if (dpm != null) {
17894                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17895                        /* callingUserOnly =*/ false);
17896                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17897                        : deviceOwnerComponentName.getPackageName();
17898                // Does the package contains the device owner?
17899                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17900                // this check is probably not needed, since DO should be registered as a device
17901                // admin on some user too. (Original bug for this: b/17657954)
17902                if (packageName.equals(deviceOwnerPackageName)) {
17903                    return true;
17904                }
17905                // Does it contain a device admin for any user?
17906                int[] users;
17907                if (userId == UserHandle.USER_ALL) {
17908                    users = sUserManager.getUserIds();
17909                } else {
17910                    users = new int[]{userId};
17911                }
17912                for (int i = 0; i < users.length; ++i) {
17913                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17914                        return true;
17915                    }
17916                }
17917            }
17918        } catch (RemoteException e) {
17919        }
17920        return false;
17921    }
17922
17923    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17924        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17925    }
17926
17927    /**
17928     *  This method is an internal method that could be get invoked either
17929     *  to delete an installed package or to clean up a failed installation.
17930     *  After deleting an installed package, a broadcast is sent to notify any
17931     *  listeners that the package has been removed. For cleaning up a failed
17932     *  installation, the broadcast is not necessary since the package's
17933     *  installation wouldn't have sent the initial broadcast either
17934     *  The key steps in deleting a package are
17935     *  deleting the package information in internal structures like mPackages,
17936     *  deleting the packages base directories through installd
17937     *  updating mSettings to reflect current status
17938     *  persisting settings for later use
17939     *  sending a broadcast if necessary
17940     */
17941    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17942        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17943        final boolean res;
17944
17945        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17946                ? UserHandle.USER_ALL : userId;
17947
17948        if (isPackageDeviceAdmin(packageName, removeUser)) {
17949            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17950            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17951        }
17952
17953        PackageSetting uninstalledPs = null;
17954        PackageParser.Package pkg = null;
17955
17956        // for the uninstall-updates case and restricted profiles, remember the per-
17957        // user handle installed state
17958        int[] allUsers;
17959        synchronized (mPackages) {
17960            uninstalledPs = mSettings.mPackages.get(packageName);
17961            if (uninstalledPs == null) {
17962                Slog.w(TAG, "Not removing non-existent package " + packageName);
17963                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17964            }
17965
17966            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17967                    && uninstalledPs.versionCode != versionCode) {
17968                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17969                        + uninstalledPs.versionCode + " != " + versionCode);
17970                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17971            }
17972
17973            // Static shared libs can be declared by any package, so let us not
17974            // allow removing a package if it provides a lib others depend on.
17975            pkg = mPackages.get(packageName);
17976            if (pkg != null && pkg.staticSharedLibName != null) {
17977                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17978                        pkg.staticSharedLibVersion);
17979                if (libEntry != null) {
17980                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17981                            libEntry.info, 0, userId);
17982                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17983                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17984                                + " hosting lib " + libEntry.info.getName() + " version "
17985                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17986                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17987                    }
17988                }
17989            }
17990
17991            allUsers = sUserManager.getUserIds();
17992            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17993        }
17994
17995        final int freezeUser;
17996        if (isUpdatedSystemApp(uninstalledPs)
17997                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17998            // We're downgrading a system app, which will apply to all users, so
17999            // freeze them all during the downgrade
18000            freezeUser = UserHandle.USER_ALL;
18001        } else {
18002            freezeUser = removeUser;
18003        }
18004
18005        synchronized (mInstallLock) {
18006            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18007            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18008                    deleteFlags, "deletePackageX")) {
18009                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18010                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18011            }
18012            synchronized (mPackages) {
18013                if (res) {
18014                    if (pkg != null) {
18015                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18016                    }
18017                    updateSequenceNumberLP(packageName, info.removedUsers);
18018                    updateInstantAppInstallerLocked(packageName);
18019                }
18020            }
18021        }
18022
18023        if (res) {
18024            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18025            info.sendPackageRemovedBroadcasts(killApp);
18026            info.sendSystemPackageUpdatedBroadcasts();
18027            info.sendSystemPackageAppearedBroadcasts();
18028        }
18029        // Force a gc here.
18030        Runtime.getRuntime().gc();
18031        // Delete the resources here after sending the broadcast to let
18032        // other processes clean up before deleting resources.
18033        if (info.args != null) {
18034            synchronized (mInstallLock) {
18035                info.args.doPostDeleteLI(true);
18036            }
18037        }
18038
18039        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18040    }
18041
18042    static class PackageRemovedInfo {
18043        final PackageSender packageSender;
18044        String removedPackage;
18045        String installerPackageName;
18046        int uid = -1;
18047        int removedAppId = -1;
18048        int[] origUsers;
18049        int[] removedUsers = null;
18050        int[] broadcastUsers = null;
18051        SparseArray<Integer> installReasons;
18052        boolean isRemovedPackageSystemUpdate = false;
18053        boolean isUpdate;
18054        boolean dataRemoved;
18055        boolean removedForAllUsers;
18056        boolean isStaticSharedLib;
18057        // Clean up resources deleted packages.
18058        InstallArgs args = null;
18059        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18060        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18061
18062        PackageRemovedInfo(PackageSender packageSender) {
18063            this.packageSender = packageSender;
18064        }
18065
18066        void sendPackageRemovedBroadcasts(boolean killApp) {
18067            sendPackageRemovedBroadcastInternal(killApp);
18068            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18069            for (int i = 0; i < childCount; i++) {
18070                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18071                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18072            }
18073        }
18074
18075        void sendSystemPackageUpdatedBroadcasts() {
18076            if (isRemovedPackageSystemUpdate) {
18077                sendSystemPackageUpdatedBroadcastsInternal();
18078                final int childCount = (removedChildPackages != null)
18079                        ? removedChildPackages.size() : 0;
18080                for (int i = 0; i < childCount; i++) {
18081                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18082                    if (childInfo.isRemovedPackageSystemUpdate) {
18083                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18084                    }
18085                }
18086            }
18087        }
18088
18089        void sendSystemPackageAppearedBroadcasts() {
18090            final int packageCount = (appearedChildPackages != null)
18091                    ? appearedChildPackages.size() : 0;
18092            for (int i = 0; i < packageCount; i++) {
18093                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18094                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18095                    true, UserHandle.getAppId(installedInfo.uid),
18096                    installedInfo.newUsers);
18097            }
18098        }
18099
18100        private void sendSystemPackageUpdatedBroadcastsInternal() {
18101            Bundle extras = new Bundle(2);
18102            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18103            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18104            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18105                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18106            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18107                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18108            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18109                null, null, 0, removedPackage, null, null);
18110            if (installerPackageName != null) {
18111                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18112                        removedPackage, extras, 0 /*flags*/,
18113                        installerPackageName, null, null);
18114                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18115                        removedPackage, extras, 0 /*flags*/,
18116                        installerPackageName, null, null);
18117            }
18118        }
18119
18120        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18121            // Don't send static shared library removal broadcasts as these
18122            // libs are visible only the the apps that depend on them an one
18123            // cannot remove the library if it has a dependency.
18124            if (isStaticSharedLib) {
18125                return;
18126            }
18127            Bundle extras = new Bundle(2);
18128            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18129            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18130            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18131            if (isUpdate || isRemovedPackageSystemUpdate) {
18132                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18133            }
18134            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18135            if (removedPackage != null) {
18136                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18137                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
18138                if (installerPackageName != null) {
18139                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18140                            removedPackage, extras, 0 /*flags*/,
18141                            installerPackageName, null, broadcastUsers);
18142                }
18143                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18144                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18145                        removedPackage, extras,
18146                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18147                        null, null, broadcastUsers);
18148                }
18149            }
18150            if (removedAppId >= 0) {
18151                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras,
18152                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, null, null, broadcastUsers);
18153            }
18154        }
18155
18156        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18157            removedUsers = userIds;
18158            if (removedUsers == null) {
18159                broadcastUsers = null;
18160                return;
18161            }
18162
18163            broadcastUsers = EMPTY_INT_ARRAY;
18164            for (int i = userIds.length - 1; i >= 0; --i) {
18165                final int userId = userIds[i];
18166                if (deletedPackageSetting.getInstantApp(userId)) {
18167                    continue;
18168                }
18169                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18170            }
18171        }
18172    }
18173
18174    /*
18175     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18176     * flag is not set, the data directory is removed as well.
18177     * make sure this flag is set for partially installed apps. If not its meaningless to
18178     * delete a partially installed application.
18179     */
18180    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18181            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18182        String packageName = ps.name;
18183        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18184        // Retrieve object to delete permissions for shared user later on
18185        final PackageParser.Package deletedPkg;
18186        final PackageSetting deletedPs;
18187        // reader
18188        synchronized (mPackages) {
18189            deletedPkg = mPackages.get(packageName);
18190            deletedPs = mSettings.mPackages.get(packageName);
18191            if (outInfo != null) {
18192                outInfo.removedPackage = packageName;
18193                outInfo.installerPackageName = ps.installerPackageName;
18194                outInfo.isStaticSharedLib = deletedPkg != null
18195                        && deletedPkg.staticSharedLibName != null;
18196                outInfo.populateUsers(deletedPs == null ? null
18197                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18198            }
18199        }
18200
18201        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
18202
18203        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18204            final PackageParser.Package resolvedPkg;
18205            if (deletedPkg != null) {
18206                resolvedPkg = deletedPkg;
18207            } else {
18208                // We don't have a parsed package when it lives on an ejected
18209                // adopted storage device, so fake something together
18210                resolvedPkg = new PackageParser.Package(ps.name);
18211                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18212            }
18213            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18214                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18215            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18216            if (outInfo != null) {
18217                outInfo.dataRemoved = true;
18218            }
18219            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18220        }
18221
18222        int removedAppId = -1;
18223
18224        // writer
18225        synchronized (mPackages) {
18226            boolean installedStateChanged = false;
18227            if (deletedPs != null) {
18228                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18229                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18230                    clearDefaultBrowserIfNeeded(packageName);
18231                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18232                    removedAppId = mSettings.removePackageLPw(packageName);
18233                    if (outInfo != null) {
18234                        outInfo.removedAppId = removedAppId;
18235                    }
18236                    updatePermissionsLPw(deletedPs.name, null, 0);
18237                    if (deletedPs.sharedUser != null) {
18238                        // Remove permissions associated with package. Since runtime
18239                        // permissions are per user we have to kill the removed package
18240                        // or packages running under the shared user of the removed
18241                        // package if revoking the permissions requested only by the removed
18242                        // package is successful and this causes a change in gids.
18243                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18244                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18245                                    userId);
18246                            if (userIdToKill == UserHandle.USER_ALL
18247                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18248                                // If gids changed for this user, kill all affected packages.
18249                                mHandler.post(new Runnable() {
18250                                    @Override
18251                                    public void run() {
18252                                        // This has to happen with no lock held.
18253                                        killApplication(deletedPs.name, deletedPs.appId,
18254                                                KILL_APP_REASON_GIDS_CHANGED);
18255                                    }
18256                                });
18257                                break;
18258                            }
18259                        }
18260                    }
18261                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18262                }
18263                // make sure to preserve per-user disabled state if this removal was just
18264                // a downgrade of a system app to the factory package
18265                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18266                    if (DEBUG_REMOVE) {
18267                        Slog.d(TAG, "Propagating install state across downgrade");
18268                    }
18269                    for (int userId : allUserHandles) {
18270                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18271                        if (DEBUG_REMOVE) {
18272                            Slog.d(TAG, "    user " + userId + " => " + installed);
18273                        }
18274                        if (installed != ps.getInstalled(userId)) {
18275                            installedStateChanged = true;
18276                        }
18277                        ps.setInstalled(installed, userId);
18278                    }
18279                }
18280            }
18281            // can downgrade to reader
18282            if (writeSettings) {
18283                // Save settings now
18284                mSettings.writeLPr();
18285            }
18286            if (installedStateChanged) {
18287                mSettings.writeKernelMappingLPr(ps);
18288            }
18289        }
18290        if (removedAppId != -1) {
18291            // A user ID was deleted here. Go through all users and remove it
18292            // from KeyStore.
18293            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18294        }
18295    }
18296
18297    static boolean locationIsPrivileged(File path) {
18298        try {
18299            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
18300                    .getCanonicalPath();
18301            return path.getCanonicalPath().startsWith(privilegedAppDir);
18302        } catch (IOException e) {
18303            Slog.e(TAG, "Unable to access code path " + path);
18304        }
18305        return false;
18306    }
18307
18308    /*
18309     * Tries to delete system package.
18310     */
18311    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18312            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18313            boolean writeSettings) {
18314        if (deletedPs.parentPackageName != null) {
18315            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18316            return false;
18317        }
18318
18319        final boolean applyUserRestrictions
18320                = (allUserHandles != null) && (outInfo.origUsers != null);
18321        final PackageSetting disabledPs;
18322        // Confirm if the system package has been updated
18323        // An updated system app can be deleted. This will also have to restore
18324        // the system pkg from system partition
18325        // reader
18326        synchronized (mPackages) {
18327            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18328        }
18329
18330        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18331                + " disabledPs=" + disabledPs);
18332
18333        if (disabledPs == null) {
18334            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18335            return false;
18336        } else if (DEBUG_REMOVE) {
18337            Slog.d(TAG, "Deleting system pkg from data partition");
18338        }
18339
18340        if (DEBUG_REMOVE) {
18341            if (applyUserRestrictions) {
18342                Slog.d(TAG, "Remembering install states:");
18343                for (int userId : allUserHandles) {
18344                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18345                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18346                }
18347            }
18348        }
18349
18350        // Delete the updated package
18351        outInfo.isRemovedPackageSystemUpdate = true;
18352        if (outInfo.removedChildPackages != null) {
18353            final int childCount = (deletedPs.childPackageNames != null)
18354                    ? deletedPs.childPackageNames.size() : 0;
18355            for (int i = 0; i < childCount; i++) {
18356                String childPackageName = deletedPs.childPackageNames.get(i);
18357                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18358                        .contains(childPackageName)) {
18359                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18360                            childPackageName);
18361                    if (childInfo != null) {
18362                        childInfo.isRemovedPackageSystemUpdate = true;
18363                    }
18364                }
18365            }
18366        }
18367
18368        if (disabledPs.versionCode < deletedPs.versionCode) {
18369            // Delete data for downgrades
18370            flags &= ~PackageManager.DELETE_KEEP_DATA;
18371        } else {
18372            // Preserve data by setting flag
18373            flags |= PackageManager.DELETE_KEEP_DATA;
18374        }
18375
18376        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18377                outInfo, writeSettings, disabledPs.pkg);
18378        if (!ret) {
18379            return false;
18380        }
18381
18382        // writer
18383        synchronized (mPackages) {
18384            // Reinstate the old system package
18385            enableSystemPackageLPw(disabledPs.pkg);
18386            // Remove any native libraries from the upgraded package.
18387            removeNativeBinariesLI(deletedPs);
18388        }
18389
18390        // Install the system package
18391        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18392        int parseFlags = mDefParseFlags
18393                | PackageParser.PARSE_MUST_BE_APK
18394                | PackageParser.PARSE_IS_SYSTEM
18395                | PackageParser.PARSE_IS_SYSTEM_DIR;
18396        if (locationIsPrivileged(disabledPs.codePath)) {
18397            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
18398        }
18399
18400        final PackageParser.Package newPkg;
18401        try {
18402            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
18403                0 /* currentTime */, null);
18404        } catch (PackageManagerException e) {
18405            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18406                    + e.getMessage());
18407            return false;
18408        }
18409
18410        try {
18411            // update shared libraries for the newly re-installed system package
18412            updateSharedLibrariesLPr(newPkg, null);
18413        } catch (PackageManagerException e) {
18414            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18415        }
18416
18417        prepareAppDataAfterInstallLIF(newPkg);
18418
18419        // writer
18420        synchronized (mPackages) {
18421            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
18422
18423            // Propagate the permissions state as we do not want to drop on the floor
18424            // runtime permissions. The update permissions method below will take
18425            // care of removing obsolete permissions and grant install permissions.
18426            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
18427            updatePermissionsLPw(newPkg.packageName, newPkg,
18428                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
18429
18430            if (applyUserRestrictions) {
18431                boolean installedStateChanged = false;
18432                if (DEBUG_REMOVE) {
18433                    Slog.d(TAG, "Propagating install state across reinstall");
18434                }
18435                for (int userId : allUserHandles) {
18436                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18437                    if (DEBUG_REMOVE) {
18438                        Slog.d(TAG, "    user " + userId + " => " + installed);
18439                    }
18440                    if (installed != ps.getInstalled(userId)) {
18441                        installedStateChanged = true;
18442                    }
18443                    ps.setInstalled(installed, userId);
18444
18445                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18446                }
18447                // Regardless of writeSettings we need to ensure that this restriction
18448                // state propagation is persisted
18449                mSettings.writeAllUsersPackageRestrictionsLPr();
18450                if (installedStateChanged) {
18451                    mSettings.writeKernelMappingLPr(ps);
18452                }
18453            }
18454            // can downgrade to reader here
18455            if (writeSettings) {
18456                mSettings.writeLPr();
18457            }
18458        }
18459        return true;
18460    }
18461
18462    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18463            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18464            PackageRemovedInfo outInfo, boolean writeSettings,
18465            PackageParser.Package replacingPackage) {
18466        synchronized (mPackages) {
18467            if (outInfo != null) {
18468                outInfo.uid = ps.appId;
18469            }
18470
18471            if (outInfo != null && outInfo.removedChildPackages != null) {
18472                final int childCount = (ps.childPackageNames != null)
18473                        ? ps.childPackageNames.size() : 0;
18474                for (int i = 0; i < childCount; i++) {
18475                    String childPackageName = ps.childPackageNames.get(i);
18476                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18477                    if (childPs == null) {
18478                        return false;
18479                    }
18480                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18481                            childPackageName);
18482                    if (childInfo != null) {
18483                        childInfo.uid = childPs.appId;
18484                    }
18485                }
18486            }
18487        }
18488
18489        // Delete package data from internal structures and also remove data if flag is set
18490        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18491
18492        // Delete the child packages data
18493        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18494        for (int i = 0; i < childCount; i++) {
18495            PackageSetting childPs;
18496            synchronized (mPackages) {
18497                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18498            }
18499            if (childPs != null) {
18500                PackageRemovedInfo childOutInfo = (outInfo != null
18501                        && outInfo.removedChildPackages != null)
18502                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18503                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18504                        && (replacingPackage != null
18505                        && !replacingPackage.hasChildPackage(childPs.name))
18506                        ? flags & ~DELETE_KEEP_DATA : flags;
18507                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18508                        deleteFlags, writeSettings);
18509            }
18510        }
18511
18512        // Delete application code and resources only for parent packages
18513        if (ps.parentPackageName == null) {
18514            if (deleteCodeAndResources && (outInfo != null)) {
18515                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18516                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18517                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18518            }
18519        }
18520
18521        return true;
18522    }
18523
18524    @Override
18525    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18526            int userId) {
18527        mContext.enforceCallingOrSelfPermission(
18528                android.Manifest.permission.DELETE_PACKAGES, null);
18529        synchronized (mPackages) {
18530            // Cannot block uninstall of static shared libs as they are
18531            // considered a part of the using app (emulating static linking).
18532            // Also static libs are installed always on internal storage.
18533            PackageParser.Package pkg = mPackages.get(packageName);
18534            if (pkg != null && pkg.staticSharedLibName != null) {
18535                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18536                        + " providing static shared library: " + pkg.staticSharedLibName);
18537                return false;
18538            }
18539            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18540            mSettings.writePackageRestrictionsLPr(userId);
18541        }
18542        return true;
18543    }
18544
18545    @Override
18546    public boolean getBlockUninstallForUser(String packageName, int userId) {
18547        synchronized (mPackages) {
18548            return mSettings.getBlockUninstallLPr(userId, packageName);
18549        }
18550    }
18551
18552    @Override
18553    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18554        int callingUid = Binder.getCallingUid();
18555        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
18556            throw new SecurityException(
18557                    "setRequiredForSystemUser can only be run by the system or root");
18558        }
18559        synchronized (mPackages) {
18560            PackageSetting ps = mSettings.mPackages.get(packageName);
18561            if (ps == null) {
18562                Log.w(TAG, "Package doesn't exist: " + packageName);
18563                return false;
18564            }
18565            if (systemUserApp) {
18566                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18567            } else {
18568                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18569            }
18570            mSettings.writeLPr();
18571        }
18572        return true;
18573    }
18574
18575    /*
18576     * This method handles package deletion in general
18577     */
18578    private boolean deletePackageLIF(String packageName, UserHandle user,
18579            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18580            PackageRemovedInfo outInfo, boolean writeSettings,
18581            PackageParser.Package replacingPackage) {
18582        if (packageName == null) {
18583            Slog.w(TAG, "Attempt to delete null packageName.");
18584            return false;
18585        }
18586
18587        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18588
18589        PackageSetting ps;
18590        synchronized (mPackages) {
18591            ps = mSettings.mPackages.get(packageName);
18592            if (ps == null) {
18593                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18594                return false;
18595            }
18596
18597            if (ps.parentPackageName != null && (!isSystemApp(ps)
18598                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18599                if (DEBUG_REMOVE) {
18600                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18601                            + ((user == null) ? UserHandle.USER_ALL : user));
18602                }
18603                final int removedUserId = (user != null) ? user.getIdentifier()
18604                        : UserHandle.USER_ALL;
18605                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18606                    return false;
18607                }
18608                markPackageUninstalledForUserLPw(ps, user);
18609                scheduleWritePackageRestrictionsLocked(user);
18610                return true;
18611            }
18612        }
18613
18614        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18615                && user.getIdentifier() != UserHandle.USER_ALL)) {
18616            // The caller is asking that the package only be deleted for a single
18617            // user.  To do this, we just mark its uninstalled state and delete
18618            // its data. If this is a system app, we only allow this to happen if
18619            // they have set the special DELETE_SYSTEM_APP which requests different
18620            // semantics than normal for uninstalling system apps.
18621            markPackageUninstalledForUserLPw(ps, user);
18622
18623            if (!isSystemApp(ps)) {
18624                // Do not uninstall the APK if an app should be cached
18625                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18626                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18627                    // Other user still have this package installed, so all
18628                    // we need to do is clear this user's data and save that
18629                    // it is uninstalled.
18630                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18631                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18632                        return false;
18633                    }
18634                    scheduleWritePackageRestrictionsLocked(user);
18635                    return true;
18636                } else {
18637                    // We need to set it back to 'installed' so the uninstall
18638                    // broadcasts will be sent correctly.
18639                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18640                    ps.setInstalled(true, user.getIdentifier());
18641                    mSettings.writeKernelMappingLPr(ps);
18642                }
18643            } else {
18644                // This is a system app, so we assume that the
18645                // other users still have this package installed, so all
18646                // we need to do is clear this user's data and save that
18647                // it is uninstalled.
18648                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18649                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18650                    return false;
18651                }
18652                scheduleWritePackageRestrictionsLocked(user);
18653                return true;
18654            }
18655        }
18656
18657        // If we are deleting a composite package for all users, keep track
18658        // of result for each child.
18659        if (ps.childPackageNames != null && outInfo != null) {
18660            synchronized (mPackages) {
18661                final int childCount = ps.childPackageNames.size();
18662                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18663                for (int i = 0; i < childCount; i++) {
18664                    String childPackageName = ps.childPackageNames.get(i);
18665                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18666                    childInfo.removedPackage = childPackageName;
18667                    childInfo.installerPackageName = ps.installerPackageName;
18668                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18669                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18670                    if (childPs != null) {
18671                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18672                    }
18673                }
18674            }
18675        }
18676
18677        boolean ret = false;
18678        if (isSystemApp(ps)) {
18679            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18680            // When an updated system application is deleted we delete the existing resources
18681            // as well and fall back to existing code in system partition
18682            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18683        } else {
18684            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18685            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18686                    outInfo, writeSettings, replacingPackage);
18687        }
18688
18689        // Take a note whether we deleted the package for all users
18690        if (outInfo != null) {
18691            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18692            if (outInfo.removedChildPackages != null) {
18693                synchronized (mPackages) {
18694                    final int childCount = outInfo.removedChildPackages.size();
18695                    for (int i = 0; i < childCount; i++) {
18696                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18697                        if (childInfo != null) {
18698                            childInfo.removedForAllUsers = mPackages.get(
18699                                    childInfo.removedPackage) == null;
18700                        }
18701                    }
18702                }
18703            }
18704            // If we uninstalled an update to a system app there may be some
18705            // child packages that appeared as they are declared in the system
18706            // app but were not declared in the update.
18707            if (isSystemApp(ps)) {
18708                synchronized (mPackages) {
18709                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18710                    final int childCount = (updatedPs.childPackageNames != null)
18711                            ? updatedPs.childPackageNames.size() : 0;
18712                    for (int i = 0; i < childCount; i++) {
18713                        String childPackageName = updatedPs.childPackageNames.get(i);
18714                        if (outInfo.removedChildPackages == null
18715                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18716                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18717                            if (childPs == null) {
18718                                continue;
18719                            }
18720                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18721                            installRes.name = childPackageName;
18722                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18723                            installRes.pkg = mPackages.get(childPackageName);
18724                            installRes.uid = childPs.pkg.applicationInfo.uid;
18725                            if (outInfo.appearedChildPackages == null) {
18726                                outInfo.appearedChildPackages = new ArrayMap<>();
18727                            }
18728                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18729                        }
18730                    }
18731                }
18732            }
18733        }
18734
18735        return ret;
18736    }
18737
18738    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18739        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18740                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18741        for (int nextUserId : userIds) {
18742            if (DEBUG_REMOVE) {
18743                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18744            }
18745            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18746                    false /*installed*/,
18747                    true /*stopped*/,
18748                    true /*notLaunched*/,
18749                    false /*hidden*/,
18750                    false /*suspended*/,
18751                    false /*instantApp*/,
18752                    null /*lastDisableAppCaller*/,
18753                    null /*enabledComponents*/,
18754                    null /*disabledComponents*/,
18755                    ps.readUserState(nextUserId).domainVerificationStatus,
18756                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18757        }
18758        mSettings.writeKernelMappingLPr(ps);
18759    }
18760
18761    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18762            PackageRemovedInfo outInfo) {
18763        final PackageParser.Package pkg;
18764        synchronized (mPackages) {
18765            pkg = mPackages.get(ps.name);
18766        }
18767
18768        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18769                : new int[] {userId};
18770        for (int nextUserId : userIds) {
18771            if (DEBUG_REMOVE) {
18772                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18773                        + nextUserId);
18774            }
18775
18776            destroyAppDataLIF(pkg, userId,
18777                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18778            destroyAppProfilesLIF(pkg, userId);
18779            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18780            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18781            schedulePackageCleaning(ps.name, nextUserId, false);
18782            synchronized (mPackages) {
18783                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18784                    scheduleWritePackageRestrictionsLocked(nextUserId);
18785                }
18786                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18787            }
18788        }
18789
18790        if (outInfo != null) {
18791            outInfo.removedPackage = ps.name;
18792            outInfo.installerPackageName = ps.installerPackageName;
18793            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18794            outInfo.removedAppId = ps.appId;
18795            outInfo.removedUsers = userIds;
18796            outInfo.broadcastUsers = userIds;
18797        }
18798
18799        return true;
18800    }
18801
18802    private final class ClearStorageConnection implements ServiceConnection {
18803        IMediaContainerService mContainerService;
18804
18805        @Override
18806        public void onServiceConnected(ComponentName name, IBinder service) {
18807            synchronized (this) {
18808                mContainerService = IMediaContainerService.Stub
18809                        .asInterface(Binder.allowBlocking(service));
18810                notifyAll();
18811            }
18812        }
18813
18814        @Override
18815        public void onServiceDisconnected(ComponentName name) {
18816        }
18817    }
18818
18819    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18820        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18821
18822        final boolean mounted;
18823        if (Environment.isExternalStorageEmulated()) {
18824            mounted = true;
18825        } else {
18826            final String status = Environment.getExternalStorageState();
18827
18828            mounted = status.equals(Environment.MEDIA_MOUNTED)
18829                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18830        }
18831
18832        if (!mounted) {
18833            return;
18834        }
18835
18836        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18837        int[] users;
18838        if (userId == UserHandle.USER_ALL) {
18839            users = sUserManager.getUserIds();
18840        } else {
18841            users = new int[] { userId };
18842        }
18843        final ClearStorageConnection conn = new ClearStorageConnection();
18844        if (mContext.bindServiceAsUser(
18845                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18846            try {
18847                for (int curUser : users) {
18848                    long timeout = SystemClock.uptimeMillis() + 5000;
18849                    synchronized (conn) {
18850                        long now;
18851                        while (conn.mContainerService == null &&
18852                                (now = SystemClock.uptimeMillis()) < timeout) {
18853                            try {
18854                                conn.wait(timeout - now);
18855                            } catch (InterruptedException e) {
18856                            }
18857                        }
18858                    }
18859                    if (conn.mContainerService == null) {
18860                        return;
18861                    }
18862
18863                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18864                    clearDirectory(conn.mContainerService,
18865                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18866                    if (allData) {
18867                        clearDirectory(conn.mContainerService,
18868                                userEnv.buildExternalStorageAppDataDirs(packageName));
18869                        clearDirectory(conn.mContainerService,
18870                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18871                    }
18872                }
18873            } finally {
18874                mContext.unbindService(conn);
18875            }
18876        }
18877    }
18878
18879    @Override
18880    public void clearApplicationProfileData(String packageName) {
18881        enforceSystemOrRoot("Only the system can clear all profile data");
18882
18883        final PackageParser.Package pkg;
18884        synchronized (mPackages) {
18885            pkg = mPackages.get(packageName);
18886        }
18887
18888        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18889            synchronized (mInstallLock) {
18890                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18891            }
18892        }
18893    }
18894
18895    @Override
18896    public void clearApplicationUserData(final String packageName,
18897            final IPackageDataObserver observer, final int userId) {
18898        mContext.enforceCallingOrSelfPermission(
18899                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18900
18901        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18902                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18903
18904        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18905            throw new SecurityException("Cannot clear data for a protected package: "
18906                    + packageName);
18907        }
18908        // Queue up an async operation since the package deletion may take a little while.
18909        mHandler.post(new Runnable() {
18910            public void run() {
18911                mHandler.removeCallbacks(this);
18912                final boolean succeeded;
18913                try (PackageFreezer freezer = freezePackage(packageName,
18914                        "clearApplicationUserData")) {
18915                    synchronized (mInstallLock) {
18916                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18917                    }
18918                    clearExternalStorageDataSync(packageName, userId, true);
18919                    synchronized (mPackages) {
18920                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18921                                packageName, userId);
18922                    }
18923                }
18924                if (succeeded) {
18925                    // invoke DeviceStorageMonitor's update method to clear any notifications
18926                    DeviceStorageMonitorInternal dsm = LocalServices
18927                            .getService(DeviceStorageMonitorInternal.class);
18928                    if (dsm != null) {
18929                        dsm.checkMemory();
18930                    }
18931                }
18932                if(observer != null) {
18933                    try {
18934                        observer.onRemoveCompleted(packageName, succeeded);
18935                    } catch (RemoteException e) {
18936                        Log.i(TAG, "Observer no longer exists.");
18937                    }
18938                } //end if observer
18939            } //end run
18940        });
18941    }
18942
18943    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18944        if (packageName == null) {
18945            Slog.w(TAG, "Attempt to delete null packageName.");
18946            return false;
18947        }
18948
18949        // Try finding details about the requested package
18950        PackageParser.Package pkg;
18951        synchronized (mPackages) {
18952            pkg = mPackages.get(packageName);
18953            if (pkg == null) {
18954                final PackageSetting ps = mSettings.mPackages.get(packageName);
18955                if (ps != null) {
18956                    pkg = ps.pkg;
18957                }
18958            }
18959
18960            if (pkg == null) {
18961                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18962                return false;
18963            }
18964
18965            PackageSetting ps = (PackageSetting) pkg.mExtras;
18966            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18967        }
18968
18969        clearAppDataLIF(pkg, userId,
18970                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18971
18972        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18973        removeKeystoreDataIfNeeded(userId, appId);
18974
18975        UserManagerInternal umInternal = getUserManagerInternal();
18976        final int flags;
18977        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18978            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18979        } else if (umInternal.isUserRunning(userId)) {
18980            flags = StorageManager.FLAG_STORAGE_DE;
18981        } else {
18982            flags = 0;
18983        }
18984        prepareAppDataContentsLIF(pkg, userId, flags);
18985
18986        return true;
18987    }
18988
18989    /**
18990     * Reverts user permission state changes (permissions and flags) in
18991     * all packages for a given user.
18992     *
18993     * @param userId The device user for which to do a reset.
18994     */
18995    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18996        final int packageCount = mPackages.size();
18997        for (int i = 0; i < packageCount; i++) {
18998            PackageParser.Package pkg = mPackages.valueAt(i);
18999            PackageSetting ps = (PackageSetting) pkg.mExtras;
19000            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19001        }
19002    }
19003
19004    private void resetNetworkPolicies(int userId) {
19005        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19006    }
19007
19008    /**
19009     * Reverts user permission state changes (permissions and flags).
19010     *
19011     * @param ps The package for which to reset.
19012     * @param userId The device user for which to do a reset.
19013     */
19014    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19015            final PackageSetting ps, final int userId) {
19016        if (ps.pkg == null) {
19017            return;
19018        }
19019
19020        // These are flags that can change base on user actions.
19021        final int userSettableMask = FLAG_PERMISSION_USER_SET
19022                | FLAG_PERMISSION_USER_FIXED
19023                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19024                | FLAG_PERMISSION_REVIEW_REQUIRED;
19025
19026        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19027                | FLAG_PERMISSION_POLICY_FIXED;
19028
19029        boolean writeInstallPermissions = false;
19030        boolean writeRuntimePermissions = false;
19031
19032        final int permissionCount = ps.pkg.requestedPermissions.size();
19033        for (int i = 0; i < permissionCount; i++) {
19034            String permission = ps.pkg.requestedPermissions.get(i);
19035
19036            BasePermission bp = mSettings.mPermissions.get(permission);
19037            if (bp == null) {
19038                continue;
19039            }
19040
19041            // If shared user we just reset the state to which only this app contributed.
19042            if (ps.sharedUser != null) {
19043                boolean used = false;
19044                final int packageCount = ps.sharedUser.packages.size();
19045                for (int j = 0; j < packageCount; j++) {
19046                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19047                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19048                            && pkg.pkg.requestedPermissions.contains(permission)) {
19049                        used = true;
19050                        break;
19051                    }
19052                }
19053                if (used) {
19054                    continue;
19055                }
19056            }
19057
19058            PermissionsState permissionsState = ps.getPermissionsState();
19059
19060            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
19061
19062            // Always clear the user settable flags.
19063            final boolean hasInstallState = permissionsState.getInstallPermissionState(
19064                    bp.name) != null;
19065            // If permission review is enabled and this is a legacy app, mark the
19066            // permission as requiring a review as this is the initial state.
19067            int flags = 0;
19068            if (mPermissionReviewRequired
19069                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19070                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19071            }
19072            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19073                if (hasInstallState) {
19074                    writeInstallPermissions = true;
19075                } else {
19076                    writeRuntimePermissions = true;
19077                }
19078            }
19079
19080            // Below is only runtime permission handling.
19081            if (!bp.isRuntime()) {
19082                continue;
19083            }
19084
19085            // Never clobber system or policy.
19086            if ((oldFlags & policyOrSystemFlags) != 0) {
19087                continue;
19088            }
19089
19090            // If this permission was granted by default, make sure it is.
19091            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19092                if (permissionsState.grantRuntimePermission(bp, userId)
19093                        != PERMISSION_OPERATION_FAILURE) {
19094                    writeRuntimePermissions = true;
19095                }
19096            // If permission review is enabled the permissions for a legacy apps
19097            // are represented as constantly granted runtime ones, so don't revoke.
19098            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19099                // Otherwise, reset the permission.
19100                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19101                switch (revokeResult) {
19102                    case PERMISSION_OPERATION_SUCCESS:
19103                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19104                        writeRuntimePermissions = true;
19105                        final int appId = ps.appId;
19106                        mHandler.post(new Runnable() {
19107                            @Override
19108                            public void run() {
19109                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19110                            }
19111                        });
19112                    } break;
19113                }
19114            }
19115        }
19116
19117        // Synchronously write as we are taking permissions away.
19118        if (writeRuntimePermissions) {
19119            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19120        }
19121
19122        // Synchronously write as we are taking permissions away.
19123        if (writeInstallPermissions) {
19124            mSettings.writeLPr();
19125        }
19126    }
19127
19128    /**
19129     * Remove entries from the keystore daemon. Will only remove it if the
19130     * {@code appId} is valid.
19131     */
19132    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19133        if (appId < 0) {
19134            return;
19135        }
19136
19137        final KeyStore keyStore = KeyStore.getInstance();
19138        if (keyStore != null) {
19139            if (userId == UserHandle.USER_ALL) {
19140                for (final int individual : sUserManager.getUserIds()) {
19141                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19142                }
19143            } else {
19144                keyStore.clearUid(UserHandle.getUid(userId, appId));
19145            }
19146        } else {
19147            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19148        }
19149    }
19150
19151    @Override
19152    public void deleteApplicationCacheFiles(final String packageName,
19153            final IPackageDataObserver observer) {
19154        final int userId = UserHandle.getCallingUserId();
19155        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19156    }
19157
19158    @Override
19159    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19160            final IPackageDataObserver observer) {
19161        mContext.enforceCallingOrSelfPermission(
19162                android.Manifest.permission.DELETE_CACHE_FILES, null);
19163        enforceCrossUserPermission(Binder.getCallingUid(), userId,
19164                /* requireFullPermission= */ true, /* checkShell= */ false,
19165                "delete application cache files");
19166
19167        final PackageParser.Package pkg;
19168        synchronized (mPackages) {
19169            pkg = mPackages.get(packageName);
19170        }
19171
19172        // Queue up an async operation since the package deletion may take a little while.
19173        mHandler.post(new Runnable() {
19174            public void run() {
19175                synchronized (mInstallLock) {
19176                    final int flags = StorageManager.FLAG_STORAGE_DE
19177                            | StorageManager.FLAG_STORAGE_CE;
19178                    // We're only clearing cache files, so we don't care if the
19179                    // app is unfrozen and still able to run
19180                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19181                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19182                }
19183                clearExternalStorageDataSync(packageName, userId, false);
19184                if (observer != null) {
19185                    try {
19186                        observer.onRemoveCompleted(packageName, true);
19187                    } catch (RemoteException e) {
19188                        Log.i(TAG, "Observer no longer exists.");
19189                    }
19190                }
19191            }
19192        });
19193    }
19194
19195    @Override
19196    public void getPackageSizeInfo(final String packageName, int userHandle,
19197            final IPackageStatsObserver observer) {
19198        throw new UnsupportedOperationException(
19199                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19200    }
19201
19202    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19203        final PackageSetting ps;
19204        synchronized (mPackages) {
19205            ps = mSettings.mPackages.get(packageName);
19206            if (ps == null) {
19207                Slog.w(TAG, "Failed to find settings for " + packageName);
19208                return false;
19209            }
19210        }
19211
19212        final String[] packageNames = { packageName };
19213        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19214        final String[] codePaths = { ps.codePathString };
19215
19216        try {
19217            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19218                    ps.appId, ceDataInodes, codePaths, stats);
19219
19220            // For now, ignore code size of packages on system partition
19221            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19222                stats.codeSize = 0;
19223            }
19224
19225            // External clients expect these to be tracked separately
19226            stats.dataSize -= stats.cacheSize;
19227
19228        } catch (InstallerException e) {
19229            Slog.w(TAG, String.valueOf(e));
19230            return false;
19231        }
19232
19233        return true;
19234    }
19235
19236    private int getUidTargetSdkVersionLockedLPr(int uid) {
19237        Object obj = mSettings.getUserIdLPr(uid);
19238        if (obj instanceof SharedUserSetting) {
19239            final SharedUserSetting sus = (SharedUserSetting) obj;
19240            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19241            final Iterator<PackageSetting> it = sus.packages.iterator();
19242            while (it.hasNext()) {
19243                final PackageSetting ps = it.next();
19244                if (ps.pkg != null) {
19245                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19246                    if (v < vers) vers = v;
19247                }
19248            }
19249            return vers;
19250        } else if (obj instanceof PackageSetting) {
19251            final PackageSetting ps = (PackageSetting) obj;
19252            if (ps.pkg != null) {
19253                return ps.pkg.applicationInfo.targetSdkVersion;
19254            }
19255        }
19256        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19257    }
19258
19259    @Override
19260    public void addPreferredActivity(IntentFilter filter, int match,
19261            ComponentName[] set, ComponentName activity, int userId) {
19262        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19263                "Adding preferred");
19264    }
19265
19266    private void addPreferredActivityInternal(IntentFilter filter, int match,
19267            ComponentName[] set, ComponentName activity, boolean always, int userId,
19268            String opname) {
19269        // writer
19270        int callingUid = Binder.getCallingUid();
19271        enforceCrossUserPermission(callingUid, userId,
19272                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19273        if (filter.countActions() == 0) {
19274            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19275            return;
19276        }
19277        synchronized (mPackages) {
19278            if (mContext.checkCallingOrSelfPermission(
19279                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19280                    != PackageManager.PERMISSION_GRANTED) {
19281                if (getUidTargetSdkVersionLockedLPr(callingUid)
19282                        < Build.VERSION_CODES.FROYO) {
19283                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19284                            + callingUid);
19285                    return;
19286                }
19287                mContext.enforceCallingOrSelfPermission(
19288                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19289            }
19290
19291            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19292            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19293                    + userId + ":");
19294            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19295            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19296            scheduleWritePackageRestrictionsLocked(userId);
19297            postPreferredActivityChangedBroadcast(userId);
19298        }
19299    }
19300
19301    private void postPreferredActivityChangedBroadcast(int userId) {
19302        mHandler.post(() -> {
19303            final IActivityManager am = ActivityManager.getService();
19304            if (am == null) {
19305                return;
19306            }
19307
19308            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19309            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19310            try {
19311                am.broadcastIntent(null, intent, null, null,
19312                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19313                        null, false, false, userId);
19314            } catch (RemoteException e) {
19315            }
19316        });
19317    }
19318
19319    @Override
19320    public void replacePreferredActivity(IntentFilter filter, int match,
19321            ComponentName[] set, ComponentName activity, int userId) {
19322        if (filter.countActions() != 1) {
19323            throw new IllegalArgumentException(
19324                    "replacePreferredActivity expects filter to have only 1 action.");
19325        }
19326        if (filter.countDataAuthorities() != 0
19327                || filter.countDataPaths() != 0
19328                || filter.countDataSchemes() > 1
19329                || filter.countDataTypes() != 0) {
19330            throw new IllegalArgumentException(
19331                    "replacePreferredActivity expects filter to have no data authorities, " +
19332                    "paths, or types; and at most one scheme.");
19333        }
19334
19335        final int callingUid = Binder.getCallingUid();
19336        enforceCrossUserPermission(callingUid, userId,
19337                true /* requireFullPermission */, false /* checkShell */,
19338                "replace preferred activity");
19339        synchronized (mPackages) {
19340            if (mContext.checkCallingOrSelfPermission(
19341                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19342                    != PackageManager.PERMISSION_GRANTED) {
19343                if (getUidTargetSdkVersionLockedLPr(callingUid)
19344                        < Build.VERSION_CODES.FROYO) {
19345                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19346                            + Binder.getCallingUid());
19347                    return;
19348                }
19349                mContext.enforceCallingOrSelfPermission(
19350                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19351            }
19352
19353            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19354            if (pir != null) {
19355                // Get all of the existing entries that exactly match this filter.
19356                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19357                if (existing != null && existing.size() == 1) {
19358                    PreferredActivity cur = existing.get(0);
19359                    if (DEBUG_PREFERRED) {
19360                        Slog.i(TAG, "Checking replace of preferred:");
19361                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19362                        if (!cur.mPref.mAlways) {
19363                            Slog.i(TAG, "  -- CUR; not mAlways!");
19364                        } else {
19365                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19366                            Slog.i(TAG, "  -- CUR: mSet="
19367                                    + Arrays.toString(cur.mPref.mSetComponents));
19368                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19369                            Slog.i(TAG, "  -- NEW: mMatch="
19370                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19371                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19372                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19373                        }
19374                    }
19375                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19376                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19377                            && cur.mPref.sameSet(set)) {
19378                        // Setting the preferred activity to what it happens to be already
19379                        if (DEBUG_PREFERRED) {
19380                            Slog.i(TAG, "Replacing with same preferred activity "
19381                                    + cur.mPref.mShortComponent + " for user "
19382                                    + userId + ":");
19383                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19384                        }
19385                        return;
19386                    }
19387                }
19388
19389                if (existing != null) {
19390                    if (DEBUG_PREFERRED) {
19391                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19392                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19393                    }
19394                    for (int i = 0; i < existing.size(); i++) {
19395                        PreferredActivity pa = existing.get(i);
19396                        if (DEBUG_PREFERRED) {
19397                            Slog.i(TAG, "Removing existing preferred activity "
19398                                    + pa.mPref.mComponent + ":");
19399                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19400                        }
19401                        pir.removeFilter(pa);
19402                    }
19403                }
19404            }
19405            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19406                    "Replacing preferred");
19407        }
19408    }
19409
19410    @Override
19411    public void clearPackagePreferredActivities(String packageName) {
19412        final int uid = Binder.getCallingUid();
19413        // writer
19414        synchronized (mPackages) {
19415            PackageParser.Package pkg = mPackages.get(packageName);
19416            if (pkg == null || pkg.applicationInfo.uid != uid) {
19417                if (mContext.checkCallingOrSelfPermission(
19418                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19419                        != PackageManager.PERMISSION_GRANTED) {
19420                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
19421                            < Build.VERSION_CODES.FROYO) {
19422                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19423                                + Binder.getCallingUid());
19424                        return;
19425                    }
19426                    mContext.enforceCallingOrSelfPermission(
19427                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19428                }
19429            }
19430
19431            int user = UserHandle.getCallingUserId();
19432            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19433                scheduleWritePackageRestrictionsLocked(user);
19434            }
19435        }
19436    }
19437
19438    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19439    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19440        ArrayList<PreferredActivity> removed = null;
19441        boolean changed = false;
19442        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19443            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19444            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19445            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19446                continue;
19447            }
19448            Iterator<PreferredActivity> it = pir.filterIterator();
19449            while (it.hasNext()) {
19450                PreferredActivity pa = it.next();
19451                // Mark entry for removal only if it matches the package name
19452                // and the entry is of type "always".
19453                if (packageName == null ||
19454                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19455                                && pa.mPref.mAlways)) {
19456                    if (removed == null) {
19457                        removed = new ArrayList<PreferredActivity>();
19458                    }
19459                    removed.add(pa);
19460                }
19461            }
19462            if (removed != null) {
19463                for (int j=0; j<removed.size(); j++) {
19464                    PreferredActivity pa = removed.get(j);
19465                    pir.removeFilter(pa);
19466                }
19467                changed = true;
19468            }
19469        }
19470        if (changed) {
19471            postPreferredActivityChangedBroadcast(userId);
19472        }
19473        return changed;
19474    }
19475
19476    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19477    private void clearIntentFilterVerificationsLPw(int userId) {
19478        final int packageCount = mPackages.size();
19479        for (int i = 0; i < packageCount; i++) {
19480            PackageParser.Package pkg = mPackages.valueAt(i);
19481            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19482        }
19483    }
19484
19485    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19486    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19487        if (userId == UserHandle.USER_ALL) {
19488            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19489                    sUserManager.getUserIds())) {
19490                for (int oneUserId : sUserManager.getUserIds()) {
19491                    scheduleWritePackageRestrictionsLocked(oneUserId);
19492                }
19493            }
19494        } else {
19495            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19496                scheduleWritePackageRestrictionsLocked(userId);
19497            }
19498        }
19499    }
19500
19501    /** Clears state for all users, and touches intent filter verification policy */
19502    void clearDefaultBrowserIfNeeded(String packageName) {
19503        for (int oneUserId : sUserManager.getUserIds()) {
19504            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19505        }
19506    }
19507
19508    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19509        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19510        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19511            if (packageName.equals(defaultBrowserPackageName)) {
19512                setDefaultBrowserPackageName(null, userId);
19513            }
19514        }
19515    }
19516
19517    @Override
19518    public void resetApplicationPreferences(int userId) {
19519        mContext.enforceCallingOrSelfPermission(
19520                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19521        final long identity = Binder.clearCallingIdentity();
19522        // writer
19523        try {
19524            synchronized (mPackages) {
19525                clearPackagePreferredActivitiesLPw(null, userId);
19526                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19527                // TODO: We have to reset the default SMS and Phone. This requires
19528                // significant refactoring to keep all default apps in the package
19529                // manager (cleaner but more work) or have the services provide
19530                // callbacks to the package manager to request a default app reset.
19531                applyFactoryDefaultBrowserLPw(userId);
19532                clearIntentFilterVerificationsLPw(userId);
19533                primeDomainVerificationsLPw(userId);
19534                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19535                scheduleWritePackageRestrictionsLocked(userId);
19536            }
19537            resetNetworkPolicies(userId);
19538        } finally {
19539            Binder.restoreCallingIdentity(identity);
19540        }
19541    }
19542
19543    @Override
19544    public int getPreferredActivities(List<IntentFilter> outFilters,
19545            List<ComponentName> outActivities, String packageName) {
19546
19547        int num = 0;
19548        final int userId = UserHandle.getCallingUserId();
19549        // reader
19550        synchronized (mPackages) {
19551            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19552            if (pir != null) {
19553                final Iterator<PreferredActivity> it = pir.filterIterator();
19554                while (it.hasNext()) {
19555                    final PreferredActivity pa = it.next();
19556                    if (packageName == null
19557                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19558                                    && pa.mPref.mAlways)) {
19559                        if (outFilters != null) {
19560                            outFilters.add(new IntentFilter(pa));
19561                        }
19562                        if (outActivities != null) {
19563                            outActivities.add(pa.mPref.mComponent);
19564                        }
19565                    }
19566                }
19567            }
19568        }
19569
19570        return num;
19571    }
19572
19573    @Override
19574    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19575            int userId) {
19576        int callingUid = Binder.getCallingUid();
19577        if (callingUid != Process.SYSTEM_UID) {
19578            throw new SecurityException(
19579                    "addPersistentPreferredActivity can only be run by the system");
19580        }
19581        if (filter.countActions() == 0) {
19582            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19583            return;
19584        }
19585        synchronized (mPackages) {
19586            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19587                    ":");
19588            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19589            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19590                    new PersistentPreferredActivity(filter, activity));
19591            scheduleWritePackageRestrictionsLocked(userId);
19592            postPreferredActivityChangedBroadcast(userId);
19593        }
19594    }
19595
19596    @Override
19597    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19598        int callingUid = Binder.getCallingUid();
19599        if (callingUid != Process.SYSTEM_UID) {
19600            throw new SecurityException(
19601                    "clearPackagePersistentPreferredActivities can only be run by the system");
19602        }
19603        ArrayList<PersistentPreferredActivity> removed = null;
19604        boolean changed = false;
19605        synchronized (mPackages) {
19606            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19607                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19608                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19609                        .valueAt(i);
19610                if (userId != thisUserId) {
19611                    continue;
19612                }
19613                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19614                while (it.hasNext()) {
19615                    PersistentPreferredActivity ppa = it.next();
19616                    // Mark entry for removal only if it matches the package name.
19617                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19618                        if (removed == null) {
19619                            removed = new ArrayList<PersistentPreferredActivity>();
19620                        }
19621                        removed.add(ppa);
19622                    }
19623                }
19624                if (removed != null) {
19625                    for (int j=0; j<removed.size(); j++) {
19626                        PersistentPreferredActivity ppa = removed.get(j);
19627                        ppir.removeFilter(ppa);
19628                    }
19629                    changed = true;
19630                }
19631            }
19632
19633            if (changed) {
19634                scheduleWritePackageRestrictionsLocked(userId);
19635                postPreferredActivityChangedBroadcast(userId);
19636            }
19637        }
19638    }
19639
19640    /**
19641     * Common machinery for picking apart a restored XML blob and passing
19642     * it to a caller-supplied functor to be applied to the running system.
19643     */
19644    private void restoreFromXml(XmlPullParser parser, int userId,
19645            String expectedStartTag, BlobXmlRestorer functor)
19646            throws IOException, XmlPullParserException {
19647        int type;
19648        while ((type = parser.next()) != XmlPullParser.START_TAG
19649                && type != XmlPullParser.END_DOCUMENT) {
19650        }
19651        if (type != XmlPullParser.START_TAG) {
19652            // oops didn't find a start tag?!
19653            if (DEBUG_BACKUP) {
19654                Slog.e(TAG, "Didn't find start tag during restore");
19655            }
19656            return;
19657        }
19658Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19659        // this is supposed to be TAG_PREFERRED_BACKUP
19660        if (!expectedStartTag.equals(parser.getName())) {
19661            if (DEBUG_BACKUP) {
19662                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19663            }
19664            return;
19665        }
19666
19667        // skip interfering stuff, then we're aligned with the backing implementation
19668        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19669Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19670        functor.apply(parser, userId);
19671    }
19672
19673    private interface BlobXmlRestorer {
19674        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19675    }
19676
19677    /**
19678     * Non-Binder method, support for the backup/restore mechanism: write the
19679     * full set of preferred activities in its canonical XML format.  Returns the
19680     * XML output as a byte array, or null if there is none.
19681     */
19682    @Override
19683    public byte[] getPreferredActivityBackup(int userId) {
19684        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19685            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19686        }
19687
19688        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19689        try {
19690            final XmlSerializer serializer = new FastXmlSerializer();
19691            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19692            serializer.startDocument(null, true);
19693            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19694
19695            synchronized (mPackages) {
19696                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19697            }
19698
19699            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19700            serializer.endDocument();
19701            serializer.flush();
19702        } catch (Exception e) {
19703            if (DEBUG_BACKUP) {
19704                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19705            }
19706            return null;
19707        }
19708
19709        return dataStream.toByteArray();
19710    }
19711
19712    @Override
19713    public void restorePreferredActivities(byte[] backup, int userId) {
19714        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19715            throw new SecurityException("Only the system may call restorePreferredActivities()");
19716        }
19717
19718        try {
19719            final XmlPullParser parser = Xml.newPullParser();
19720            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19721            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19722                    new BlobXmlRestorer() {
19723                        @Override
19724                        public void apply(XmlPullParser parser, int userId)
19725                                throws XmlPullParserException, IOException {
19726                            synchronized (mPackages) {
19727                                mSettings.readPreferredActivitiesLPw(parser, userId);
19728                            }
19729                        }
19730                    } );
19731        } catch (Exception e) {
19732            if (DEBUG_BACKUP) {
19733                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19734            }
19735        }
19736    }
19737
19738    /**
19739     * Non-Binder method, support for the backup/restore mechanism: write the
19740     * default browser (etc) settings in its canonical XML format.  Returns the default
19741     * browser XML representation as a byte array, or null if there is none.
19742     */
19743    @Override
19744    public byte[] getDefaultAppsBackup(int userId) {
19745        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19746            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19747        }
19748
19749        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19750        try {
19751            final XmlSerializer serializer = new FastXmlSerializer();
19752            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19753            serializer.startDocument(null, true);
19754            serializer.startTag(null, TAG_DEFAULT_APPS);
19755
19756            synchronized (mPackages) {
19757                mSettings.writeDefaultAppsLPr(serializer, userId);
19758            }
19759
19760            serializer.endTag(null, TAG_DEFAULT_APPS);
19761            serializer.endDocument();
19762            serializer.flush();
19763        } catch (Exception e) {
19764            if (DEBUG_BACKUP) {
19765                Slog.e(TAG, "Unable to write default apps for backup", e);
19766            }
19767            return null;
19768        }
19769
19770        return dataStream.toByteArray();
19771    }
19772
19773    @Override
19774    public void restoreDefaultApps(byte[] backup, int userId) {
19775        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19776            throw new SecurityException("Only the system may call restoreDefaultApps()");
19777        }
19778
19779        try {
19780            final XmlPullParser parser = Xml.newPullParser();
19781            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19782            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19783                    new BlobXmlRestorer() {
19784                        @Override
19785                        public void apply(XmlPullParser parser, int userId)
19786                                throws XmlPullParserException, IOException {
19787                            synchronized (mPackages) {
19788                                mSettings.readDefaultAppsLPw(parser, userId);
19789                            }
19790                        }
19791                    } );
19792        } catch (Exception e) {
19793            if (DEBUG_BACKUP) {
19794                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19795            }
19796        }
19797    }
19798
19799    @Override
19800    public byte[] getIntentFilterVerificationBackup(int userId) {
19801        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19802            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19803        }
19804
19805        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19806        try {
19807            final XmlSerializer serializer = new FastXmlSerializer();
19808            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19809            serializer.startDocument(null, true);
19810            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19811
19812            synchronized (mPackages) {
19813                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19814            }
19815
19816            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19817            serializer.endDocument();
19818            serializer.flush();
19819        } catch (Exception e) {
19820            if (DEBUG_BACKUP) {
19821                Slog.e(TAG, "Unable to write default apps for backup", e);
19822            }
19823            return null;
19824        }
19825
19826        return dataStream.toByteArray();
19827    }
19828
19829    @Override
19830    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19831        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19832            throw new SecurityException("Only the system may call restorePreferredActivities()");
19833        }
19834
19835        try {
19836            final XmlPullParser parser = Xml.newPullParser();
19837            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19838            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19839                    new BlobXmlRestorer() {
19840                        @Override
19841                        public void apply(XmlPullParser parser, int userId)
19842                                throws XmlPullParserException, IOException {
19843                            synchronized (mPackages) {
19844                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19845                                mSettings.writeLPr();
19846                            }
19847                        }
19848                    } );
19849        } catch (Exception e) {
19850            if (DEBUG_BACKUP) {
19851                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19852            }
19853        }
19854    }
19855
19856    @Override
19857    public byte[] getPermissionGrantBackup(int userId) {
19858        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19859            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19860        }
19861
19862        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19863        try {
19864            final XmlSerializer serializer = new FastXmlSerializer();
19865            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19866            serializer.startDocument(null, true);
19867            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19868
19869            synchronized (mPackages) {
19870                serializeRuntimePermissionGrantsLPr(serializer, userId);
19871            }
19872
19873            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19874            serializer.endDocument();
19875            serializer.flush();
19876        } catch (Exception e) {
19877            if (DEBUG_BACKUP) {
19878                Slog.e(TAG, "Unable to write default apps for backup", e);
19879            }
19880            return null;
19881        }
19882
19883        return dataStream.toByteArray();
19884    }
19885
19886    @Override
19887    public void restorePermissionGrants(byte[] backup, int userId) {
19888        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19889            throw new SecurityException("Only the system may call restorePermissionGrants()");
19890        }
19891
19892        try {
19893            final XmlPullParser parser = Xml.newPullParser();
19894            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19895            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19896                    new BlobXmlRestorer() {
19897                        @Override
19898                        public void apply(XmlPullParser parser, int userId)
19899                                throws XmlPullParserException, IOException {
19900                            synchronized (mPackages) {
19901                                processRestoredPermissionGrantsLPr(parser, userId);
19902                            }
19903                        }
19904                    } );
19905        } catch (Exception e) {
19906            if (DEBUG_BACKUP) {
19907                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19908            }
19909        }
19910    }
19911
19912    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19913            throws IOException {
19914        serializer.startTag(null, TAG_ALL_GRANTS);
19915
19916        final int N = mSettings.mPackages.size();
19917        for (int i = 0; i < N; i++) {
19918            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19919            boolean pkgGrantsKnown = false;
19920
19921            PermissionsState packagePerms = ps.getPermissionsState();
19922
19923            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19924                final int grantFlags = state.getFlags();
19925                // only look at grants that are not system/policy fixed
19926                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19927                    final boolean isGranted = state.isGranted();
19928                    // And only back up the user-twiddled state bits
19929                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19930                        final String packageName = mSettings.mPackages.keyAt(i);
19931                        if (!pkgGrantsKnown) {
19932                            serializer.startTag(null, TAG_GRANT);
19933                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19934                            pkgGrantsKnown = true;
19935                        }
19936
19937                        final boolean userSet =
19938                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19939                        final boolean userFixed =
19940                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19941                        final boolean revoke =
19942                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19943
19944                        serializer.startTag(null, TAG_PERMISSION);
19945                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19946                        if (isGranted) {
19947                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19948                        }
19949                        if (userSet) {
19950                            serializer.attribute(null, ATTR_USER_SET, "true");
19951                        }
19952                        if (userFixed) {
19953                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19954                        }
19955                        if (revoke) {
19956                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19957                        }
19958                        serializer.endTag(null, TAG_PERMISSION);
19959                    }
19960                }
19961            }
19962
19963            if (pkgGrantsKnown) {
19964                serializer.endTag(null, TAG_GRANT);
19965            }
19966        }
19967
19968        serializer.endTag(null, TAG_ALL_GRANTS);
19969    }
19970
19971    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19972            throws XmlPullParserException, IOException {
19973        String pkgName = null;
19974        int outerDepth = parser.getDepth();
19975        int type;
19976        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19977                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19978            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19979                continue;
19980            }
19981
19982            final String tagName = parser.getName();
19983            if (tagName.equals(TAG_GRANT)) {
19984                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19985                if (DEBUG_BACKUP) {
19986                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19987                }
19988            } else if (tagName.equals(TAG_PERMISSION)) {
19989
19990                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19991                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19992
19993                int newFlagSet = 0;
19994                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19995                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19996                }
19997                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19998                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19999                }
20000                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20001                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20002                }
20003                if (DEBUG_BACKUP) {
20004                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
20005                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20006                }
20007                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20008                if (ps != null) {
20009                    // Already installed so we apply the grant immediately
20010                    if (DEBUG_BACKUP) {
20011                        Slog.v(TAG, "        + already installed; applying");
20012                    }
20013                    PermissionsState perms = ps.getPermissionsState();
20014                    BasePermission bp = mSettings.mPermissions.get(permName);
20015                    if (bp != null) {
20016                        if (isGranted) {
20017                            perms.grantRuntimePermission(bp, userId);
20018                        }
20019                        if (newFlagSet != 0) {
20020                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20021                        }
20022                    }
20023                } else {
20024                    // Need to wait for post-restore install to apply the grant
20025                    if (DEBUG_BACKUP) {
20026                        Slog.v(TAG, "        - not yet installed; saving for later");
20027                    }
20028                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20029                            isGranted, newFlagSet, userId);
20030                }
20031            } else {
20032                PackageManagerService.reportSettingsProblem(Log.WARN,
20033                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20034                XmlUtils.skipCurrentTag(parser);
20035            }
20036        }
20037
20038        scheduleWriteSettingsLocked();
20039        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20040    }
20041
20042    @Override
20043    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20044            int sourceUserId, int targetUserId, int flags) {
20045        mContext.enforceCallingOrSelfPermission(
20046                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20047        int callingUid = Binder.getCallingUid();
20048        enforceOwnerRights(ownerPackage, callingUid);
20049        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20050        if (intentFilter.countActions() == 0) {
20051            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20052            return;
20053        }
20054        synchronized (mPackages) {
20055            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20056                    ownerPackage, targetUserId, flags);
20057            CrossProfileIntentResolver resolver =
20058                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20059            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20060            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20061            if (existing != null) {
20062                int size = existing.size();
20063                for (int i = 0; i < size; i++) {
20064                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20065                        return;
20066                    }
20067                }
20068            }
20069            resolver.addFilter(newFilter);
20070            scheduleWritePackageRestrictionsLocked(sourceUserId);
20071        }
20072    }
20073
20074    @Override
20075    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20076        mContext.enforceCallingOrSelfPermission(
20077                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20078        int callingUid = Binder.getCallingUid();
20079        enforceOwnerRights(ownerPackage, callingUid);
20080        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20081        synchronized (mPackages) {
20082            CrossProfileIntentResolver resolver =
20083                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20084            ArraySet<CrossProfileIntentFilter> set =
20085                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20086            for (CrossProfileIntentFilter filter : set) {
20087                if (filter.getOwnerPackage().equals(ownerPackage)) {
20088                    resolver.removeFilter(filter);
20089                }
20090            }
20091            scheduleWritePackageRestrictionsLocked(sourceUserId);
20092        }
20093    }
20094
20095    // Enforcing that callingUid is owning pkg on userId
20096    private void enforceOwnerRights(String pkg, int callingUid) {
20097        // The system owns everything.
20098        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20099            return;
20100        }
20101        int callingUserId = UserHandle.getUserId(callingUid);
20102        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20103        if (pi == null) {
20104            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20105                    + callingUserId);
20106        }
20107        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20108            throw new SecurityException("Calling uid " + callingUid
20109                    + " does not own package " + pkg);
20110        }
20111    }
20112
20113    @Override
20114    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20115        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20116    }
20117
20118    /**
20119     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20120     * then reports the most likely home activity or null if there are more than one.
20121     */
20122    public ComponentName getDefaultHomeActivity(int userId) {
20123        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20124        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20125        if (cn != null) {
20126            return cn;
20127        }
20128
20129        // Find the launcher with the highest priority and return that component if there are no
20130        // other home activity with the same priority.
20131        int lastPriority = Integer.MIN_VALUE;
20132        ComponentName lastComponent = null;
20133        final int size = allHomeCandidates.size();
20134        for (int i = 0; i < size; i++) {
20135            final ResolveInfo ri = allHomeCandidates.get(i);
20136            if (ri.priority > lastPriority) {
20137                lastComponent = ri.activityInfo.getComponentName();
20138                lastPriority = ri.priority;
20139            } else if (ri.priority == lastPriority) {
20140                // Two components found with same priority.
20141                lastComponent = null;
20142            }
20143        }
20144        return lastComponent;
20145    }
20146
20147    private Intent getHomeIntent() {
20148        Intent intent = new Intent(Intent.ACTION_MAIN);
20149        intent.addCategory(Intent.CATEGORY_HOME);
20150        intent.addCategory(Intent.CATEGORY_DEFAULT);
20151        return intent;
20152    }
20153
20154    private IntentFilter getHomeFilter() {
20155        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20156        filter.addCategory(Intent.CATEGORY_HOME);
20157        filter.addCategory(Intent.CATEGORY_DEFAULT);
20158        return filter;
20159    }
20160
20161    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20162            int userId) {
20163        Intent intent  = getHomeIntent();
20164        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20165                PackageManager.GET_META_DATA, userId);
20166        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20167                true, false, false, userId);
20168
20169        allHomeCandidates.clear();
20170        if (list != null) {
20171            for (ResolveInfo ri : list) {
20172                allHomeCandidates.add(ri);
20173            }
20174        }
20175        return (preferred == null || preferred.activityInfo == null)
20176                ? null
20177                : new ComponentName(preferred.activityInfo.packageName,
20178                        preferred.activityInfo.name);
20179    }
20180
20181    @Override
20182    public void setHomeActivity(ComponentName comp, int userId) {
20183        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20184        getHomeActivitiesAsUser(homeActivities, userId);
20185
20186        boolean found = false;
20187
20188        final int size = homeActivities.size();
20189        final ComponentName[] set = new ComponentName[size];
20190        for (int i = 0; i < size; i++) {
20191            final ResolveInfo candidate = homeActivities.get(i);
20192            final ActivityInfo info = candidate.activityInfo;
20193            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20194            set[i] = activityName;
20195            if (!found && activityName.equals(comp)) {
20196                found = true;
20197            }
20198        }
20199        if (!found) {
20200            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20201                    + userId);
20202        }
20203        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20204                set, comp, userId);
20205    }
20206
20207    private @Nullable String getSetupWizardPackageName() {
20208        final Intent intent = new Intent(Intent.ACTION_MAIN);
20209        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20210
20211        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20212                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20213                        | MATCH_DISABLED_COMPONENTS,
20214                UserHandle.myUserId());
20215        if (matches.size() == 1) {
20216            return matches.get(0).getComponentInfo().packageName;
20217        } else {
20218            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20219                    + ": matches=" + matches);
20220            return null;
20221        }
20222    }
20223
20224    private @Nullable String getStorageManagerPackageName() {
20225        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20226
20227        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20228                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20229                        | MATCH_DISABLED_COMPONENTS,
20230                UserHandle.myUserId());
20231        if (matches.size() == 1) {
20232            return matches.get(0).getComponentInfo().packageName;
20233        } else {
20234            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20235                    + matches.size() + ": matches=" + matches);
20236            return null;
20237        }
20238    }
20239
20240    @Override
20241    public void setApplicationEnabledSetting(String appPackageName,
20242            int newState, int flags, int userId, String callingPackage) {
20243        if (!sUserManager.exists(userId)) return;
20244        if (callingPackage == null) {
20245            callingPackage = Integer.toString(Binder.getCallingUid());
20246        }
20247        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20248    }
20249
20250    @Override
20251    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20252        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20253        synchronized (mPackages) {
20254            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20255            if (pkgSetting != null) {
20256                pkgSetting.setUpdateAvailable(updateAvailable);
20257            }
20258        }
20259    }
20260
20261    @Override
20262    public void setComponentEnabledSetting(ComponentName componentName,
20263            int newState, int flags, int userId) {
20264        if (!sUserManager.exists(userId)) return;
20265        setEnabledSetting(componentName.getPackageName(),
20266                componentName.getClassName(), newState, flags, userId, null);
20267    }
20268
20269    private void setEnabledSetting(final String packageName, String className, int newState,
20270            final int flags, int userId, String callingPackage) {
20271        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20272              || newState == COMPONENT_ENABLED_STATE_ENABLED
20273              || newState == COMPONENT_ENABLED_STATE_DISABLED
20274              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20275              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20276            throw new IllegalArgumentException("Invalid new component state: "
20277                    + newState);
20278        }
20279        PackageSetting pkgSetting;
20280        final int uid = Binder.getCallingUid();
20281        final int permission;
20282        if (uid == Process.SYSTEM_UID) {
20283            permission = PackageManager.PERMISSION_GRANTED;
20284        } else {
20285            permission = mContext.checkCallingOrSelfPermission(
20286                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20287        }
20288        enforceCrossUserPermission(uid, userId,
20289                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20290        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20291        boolean sendNow = false;
20292        boolean isApp = (className == null);
20293        String componentName = isApp ? packageName : className;
20294        int packageUid = -1;
20295        ArrayList<String> components;
20296
20297        // writer
20298        synchronized (mPackages) {
20299            pkgSetting = mSettings.mPackages.get(packageName);
20300            if (pkgSetting == null) {
20301                if (className == null) {
20302                    throw new IllegalArgumentException("Unknown package: " + packageName);
20303                }
20304                throw new IllegalArgumentException(
20305                        "Unknown component: " + packageName + "/" + className);
20306            }
20307        }
20308
20309        // Limit who can change which apps
20310        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
20311            // Don't allow apps that don't have permission to modify other apps
20312            if (!allowedByPermission) {
20313                throw new SecurityException(
20314                        "Permission Denial: attempt to change component state from pid="
20315                        + Binder.getCallingPid()
20316                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
20317            }
20318            // Don't allow changing protected packages.
20319            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20320                throw new SecurityException("Cannot disable a protected package: " + packageName);
20321            }
20322        }
20323
20324        synchronized (mPackages) {
20325            if (uid == Process.SHELL_UID
20326                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20327                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20328                // unless it is a test package.
20329                int oldState = pkgSetting.getEnabled(userId);
20330                if (className == null
20331                    &&
20332                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20333                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20334                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20335                    &&
20336                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20337                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
20338                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20339                    // ok
20340                } else {
20341                    throw new SecurityException(
20342                            "Shell cannot change component state for " + packageName + "/"
20343                            + className + " to " + newState);
20344                }
20345            }
20346            if (className == null) {
20347                // We're dealing with an application/package level state change
20348                if (pkgSetting.getEnabled(userId) == newState) {
20349                    // Nothing to do
20350                    return;
20351                }
20352                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20353                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20354                    // Don't care about who enables an app.
20355                    callingPackage = null;
20356                }
20357                pkgSetting.setEnabled(newState, userId, callingPackage);
20358                // pkgSetting.pkg.mSetEnabled = newState;
20359            } else {
20360                // We're dealing with a component level state change
20361                // First, verify that this is a valid class name.
20362                PackageParser.Package pkg = pkgSetting.pkg;
20363                if (pkg == null || !pkg.hasComponentClassName(className)) {
20364                    if (pkg != null &&
20365                            pkg.applicationInfo.targetSdkVersion >=
20366                                    Build.VERSION_CODES.JELLY_BEAN) {
20367                        throw new IllegalArgumentException("Component class " + className
20368                                + " does not exist in " + packageName);
20369                    } else {
20370                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20371                                + className + " does not exist in " + packageName);
20372                    }
20373                }
20374                switch (newState) {
20375                case COMPONENT_ENABLED_STATE_ENABLED:
20376                    if (!pkgSetting.enableComponentLPw(className, userId)) {
20377                        return;
20378                    }
20379                    break;
20380                case COMPONENT_ENABLED_STATE_DISABLED:
20381                    if (!pkgSetting.disableComponentLPw(className, userId)) {
20382                        return;
20383                    }
20384                    break;
20385                case COMPONENT_ENABLED_STATE_DEFAULT:
20386                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
20387                        return;
20388                    }
20389                    break;
20390                default:
20391                    Slog.e(TAG, "Invalid new component state: " + newState);
20392                    return;
20393                }
20394            }
20395            scheduleWritePackageRestrictionsLocked(userId);
20396            updateSequenceNumberLP(packageName, new int[] { userId });
20397            final long callingId = Binder.clearCallingIdentity();
20398            try {
20399                updateInstantAppInstallerLocked(packageName);
20400            } finally {
20401                Binder.restoreCallingIdentity(callingId);
20402            }
20403            components = mPendingBroadcasts.get(userId, packageName);
20404            final boolean newPackage = components == null;
20405            if (newPackage) {
20406                components = new ArrayList<String>();
20407            }
20408            if (!components.contains(componentName)) {
20409                components.add(componentName);
20410            }
20411            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20412                sendNow = true;
20413                // Purge entry from pending broadcast list if another one exists already
20414                // since we are sending one right away.
20415                mPendingBroadcasts.remove(userId, packageName);
20416            } else {
20417                if (newPackage) {
20418                    mPendingBroadcasts.put(userId, packageName, components);
20419                }
20420                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20421                    // Schedule a message
20422                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20423                }
20424            }
20425        }
20426
20427        long callingId = Binder.clearCallingIdentity();
20428        try {
20429            if (sendNow) {
20430                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20431                sendPackageChangedBroadcast(packageName,
20432                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20433            }
20434        } finally {
20435            Binder.restoreCallingIdentity(callingId);
20436        }
20437    }
20438
20439    @Override
20440    public void flushPackageRestrictionsAsUser(int userId) {
20441        if (!sUserManager.exists(userId)) {
20442            return;
20443        }
20444        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20445                false /* checkShell */, "flushPackageRestrictions");
20446        synchronized (mPackages) {
20447            mSettings.writePackageRestrictionsLPr(userId);
20448            mDirtyUsers.remove(userId);
20449            if (mDirtyUsers.isEmpty()) {
20450                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20451            }
20452        }
20453    }
20454
20455    private void sendPackageChangedBroadcast(String packageName,
20456            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20457        if (DEBUG_INSTALL)
20458            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20459                    + componentNames);
20460        Bundle extras = new Bundle(4);
20461        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20462        String nameList[] = new String[componentNames.size()];
20463        componentNames.toArray(nameList);
20464        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20465        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20466        extras.putInt(Intent.EXTRA_UID, packageUid);
20467        // If this is not reporting a change of the overall package, then only send it
20468        // to registered receivers.  We don't want to launch a swath of apps for every
20469        // little component state change.
20470        final int flags = !componentNames.contains(packageName)
20471                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20472        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20473                new int[] {UserHandle.getUserId(packageUid)});
20474    }
20475
20476    @Override
20477    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20478        if (!sUserManager.exists(userId)) return;
20479        final int uid = Binder.getCallingUid();
20480        final int permission = mContext.checkCallingOrSelfPermission(
20481                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20482        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20483        enforceCrossUserPermission(uid, userId,
20484                true /* requireFullPermission */, true /* checkShell */, "stop package");
20485        // writer
20486        synchronized (mPackages) {
20487            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20488                    allowedByPermission, uid, userId)) {
20489                scheduleWritePackageRestrictionsLocked(userId);
20490            }
20491        }
20492    }
20493
20494    @Override
20495    public String getInstallerPackageName(String packageName) {
20496        // reader
20497        synchronized (mPackages) {
20498            return mSettings.getInstallerPackageNameLPr(packageName);
20499        }
20500    }
20501
20502    public boolean isOrphaned(String packageName) {
20503        // reader
20504        synchronized (mPackages) {
20505            return mSettings.isOrphaned(packageName);
20506        }
20507    }
20508
20509    @Override
20510    public int getApplicationEnabledSetting(String packageName, int userId) {
20511        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20512        int uid = Binder.getCallingUid();
20513        enforceCrossUserPermission(uid, userId,
20514                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20515        // reader
20516        synchronized (mPackages) {
20517            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20518        }
20519    }
20520
20521    @Override
20522    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
20523        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20524        int uid = Binder.getCallingUid();
20525        enforceCrossUserPermission(uid, userId,
20526                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
20527        // reader
20528        synchronized (mPackages) {
20529            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
20530        }
20531    }
20532
20533    @Override
20534    public void enterSafeMode() {
20535        enforceSystemOrRoot("Only the system can request entering safe mode");
20536
20537        if (!mSystemReady) {
20538            mSafeMode = true;
20539        }
20540    }
20541
20542    @Override
20543    public void systemReady() {
20544        mSystemReady = true;
20545        final ContentResolver resolver = mContext.getContentResolver();
20546        ContentObserver co = new ContentObserver(mHandler) {
20547            @Override
20548            public void onChange(boolean selfChange) {
20549                mEphemeralAppsDisabled =
20550                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20551                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20552            }
20553        };
20554        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20555                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20556                false, co, UserHandle.USER_SYSTEM);
20557        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20558                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20559        co.onChange(true);
20560
20561        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20562        // disabled after already being started.
20563        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20564                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20565
20566        // Read the compatibilty setting when the system is ready.
20567        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20568                mContext.getContentResolver(),
20569                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20570        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20571        if (DEBUG_SETTINGS) {
20572            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20573        }
20574
20575        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20576
20577        synchronized (mPackages) {
20578            // Verify that all of the preferred activity components actually
20579            // exist.  It is possible for applications to be updated and at
20580            // that point remove a previously declared activity component that
20581            // had been set as a preferred activity.  We try to clean this up
20582            // the next time we encounter that preferred activity, but it is
20583            // possible for the user flow to never be able to return to that
20584            // situation so here we do a sanity check to make sure we haven't
20585            // left any junk around.
20586            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20587            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20588                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20589                removed.clear();
20590                for (PreferredActivity pa : pir.filterSet()) {
20591                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20592                        removed.add(pa);
20593                    }
20594                }
20595                if (removed.size() > 0) {
20596                    for (int r=0; r<removed.size(); r++) {
20597                        PreferredActivity pa = removed.get(r);
20598                        Slog.w(TAG, "Removing dangling preferred activity: "
20599                                + pa.mPref.mComponent);
20600                        pir.removeFilter(pa);
20601                    }
20602                    mSettings.writePackageRestrictionsLPr(
20603                            mSettings.mPreferredActivities.keyAt(i));
20604                }
20605            }
20606
20607            for (int userId : UserManagerService.getInstance().getUserIds()) {
20608                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20609                    grantPermissionsUserIds = ArrayUtils.appendInt(
20610                            grantPermissionsUserIds, userId);
20611                }
20612            }
20613        }
20614        sUserManager.systemReady();
20615
20616        // If we upgraded grant all default permissions before kicking off.
20617        for (int userId : grantPermissionsUserIds) {
20618            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20619        }
20620
20621        // If we did not grant default permissions, we preload from this the
20622        // default permission exceptions lazily to ensure we don't hit the
20623        // disk on a new user creation.
20624        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20625            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20626        }
20627
20628        // Kick off any messages waiting for system ready
20629        if (mPostSystemReadyMessages != null) {
20630            for (Message msg : mPostSystemReadyMessages) {
20631                msg.sendToTarget();
20632            }
20633            mPostSystemReadyMessages = null;
20634        }
20635
20636        // Watch for external volumes that come and go over time
20637        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20638        storage.registerListener(mStorageListener);
20639
20640        mInstallerService.systemReady();
20641        mPackageDexOptimizer.systemReady();
20642
20643        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20644                StorageManagerInternal.class);
20645        StorageManagerInternal.addExternalStoragePolicy(
20646                new StorageManagerInternal.ExternalStorageMountPolicy() {
20647            @Override
20648            public int getMountMode(int uid, String packageName) {
20649                if (Process.isIsolated(uid)) {
20650                    return Zygote.MOUNT_EXTERNAL_NONE;
20651                }
20652                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20653                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20654                }
20655                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20656                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20657                }
20658                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20659                    return Zygote.MOUNT_EXTERNAL_READ;
20660                }
20661                return Zygote.MOUNT_EXTERNAL_WRITE;
20662            }
20663
20664            @Override
20665            public boolean hasExternalStorage(int uid, String packageName) {
20666                return true;
20667            }
20668        });
20669
20670        // Now that we're mostly running, clean up stale users and apps
20671        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20672        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20673
20674        if (mPrivappPermissionsViolations != null) {
20675            Slog.wtf(TAG,"Signature|privileged permissions not in "
20676                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
20677            mPrivappPermissionsViolations = null;
20678        }
20679    }
20680
20681    public void waitForAppDataPrepared() {
20682        if (mPrepareAppDataFuture == null) {
20683            return;
20684        }
20685        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20686        mPrepareAppDataFuture = null;
20687    }
20688
20689    @Override
20690    public boolean isSafeMode() {
20691        return mSafeMode;
20692    }
20693
20694    @Override
20695    public boolean hasSystemUidErrors() {
20696        return mHasSystemUidErrors;
20697    }
20698
20699    static String arrayToString(int[] array) {
20700        StringBuffer buf = new StringBuffer(128);
20701        buf.append('[');
20702        if (array != null) {
20703            for (int i=0; i<array.length; i++) {
20704                if (i > 0) buf.append(", ");
20705                buf.append(array[i]);
20706            }
20707        }
20708        buf.append(']');
20709        return buf.toString();
20710    }
20711
20712    static class DumpState {
20713        public static final int DUMP_LIBS = 1 << 0;
20714        public static final int DUMP_FEATURES = 1 << 1;
20715        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20716        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20717        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20718        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20719        public static final int DUMP_PERMISSIONS = 1 << 6;
20720        public static final int DUMP_PACKAGES = 1 << 7;
20721        public static final int DUMP_SHARED_USERS = 1 << 8;
20722        public static final int DUMP_MESSAGES = 1 << 9;
20723        public static final int DUMP_PROVIDERS = 1 << 10;
20724        public static final int DUMP_VERIFIERS = 1 << 11;
20725        public static final int DUMP_PREFERRED = 1 << 12;
20726        public static final int DUMP_PREFERRED_XML = 1 << 13;
20727        public static final int DUMP_KEYSETS = 1 << 14;
20728        public static final int DUMP_VERSION = 1 << 15;
20729        public static final int DUMP_INSTALLS = 1 << 16;
20730        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20731        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20732        public static final int DUMP_FROZEN = 1 << 19;
20733        public static final int DUMP_DEXOPT = 1 << 20;
20734        public static final int DUMP_COMPILER_STATS = 1 << 21;
20735        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
20736        public static final int DUMP_CHANGES = 1 << 23;
20737
20738        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20739
20740        private int mTypes;
20741
20742        private int mOptions;
20743
20744        private boolean mTitlePrinted;
20745
20746        private SharedUserSetting mSharedUser;
20747
20748        public boolean isDumping(int type) {
20749            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20750                return true;
20751            }
20752
20753            return (mTypes & type) != 0;
20754        }
20755
20756        public void setDump(int type) {
20757            mTypes |= type;
20758        }
20759
20760        public boolean isOptionEnabled(int option) {
20761            return (mOptions & option) != 0;
20762        }
20763
20764        public void setOptionEnabled(int option) {
20765            mOptions |= option;
20766        }
20767
20768        public boolean onTitlePrinted() {
20769            final boolean printed = mTitlePrinted;
20770            mTitlePrinted = true;
20771            return printed;
20772        }
20773
20774        public boolean getTitlePrinted() {
20775            return mTitlePrinted;
20776        }
20777
20778        public void setTitlePrinted(boolean enabled) {
20779            mTitlePrinted = enabled;
20780        }
20781
20782        public SharedUserSetting getSharedUser() {
20783            return mSharedUser;
20784        }
20785
20786        public void setSharedUser(SharedUserSetting user) {
20787            mSharedUser = user;
20788        }
20789    }
20790
20791    @Override
20792    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20793            FileDescriptor err, String[] args, ShellCallback callback,
20794            ResultReceiver resultReceiver) {
20795        (new PackageManagerShellCommand(this)).exec(
20796                this, in, out, err, args, callback, resultReceiver);
20797    }
20798
20799    @Override
20800    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20801        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20802
20803        DumpState dumpState = new DumpState();
20804        boolean fullPreferred = false;
20805        boolean checkin = false;
20806
20807        String packageName = null;
20808        ArraySet<String> permissionNames = null;
20809
20810        int opti = 0;
20811        while (opti < args.length) {
20812            String opt = args[opti];
20813            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20814                break;
20815            }
20816            opti++;
20817
20818            if ("-a".equals(opt)) {
20819                // Right now we only know how to print all.
20820            } else if ("-h".equals(opt)) {
20821                pw.println("Package manager dump options:");
20822                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20823                pw.println("    --checkin: dump for a checkin");
20824                pw.println("    -f: print details of intent filters");
20825                pw.println("    -h: print this help");
20826                pw.println("  cmd may be one of:");
20827                pw.println("    l[ibraries]: list known shared libraries");
20828                pw.println("    f[eatures]: list device features");
20829                pw.println("    k[eysets]: print known keysets");
20830                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20831                pw.println("    perm[issions]: dump permissions");
20832                pw.println("    permission [name ...]: dump declaration and use of given permission");
20833                pw.println("    pref[erred]: print preferred package settings");
20834                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20835                pw.println("    prov[iders]: dump content providers");
20836                pw.println("    p[ackages]: dump installed packages");
20837                pw.println("    s[hared-users]: dump shared user IDs");
20838                pw.println("    m[essages]: print collected runtime messages");
20839                pw.println("    v[erifiers]: print package verifier info");
20840                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20841                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20842                pw.println("    version: print database version info");
20843                pw.println("    write: write current settings now");
20844                pw.println("    installs: details about install sessions");
20845                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20846                pw.println("    dexopt: dump dexopt state");
20847                pw.println("    compiler-stats: dump compiler statistics");
20848                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20849                pw.println("    <package.name>: info about given package");
20850                return;
20851            } else if ("--checkin".equals(opt)) {
20852                checkin = true;
20853            } else if ("-f".equals(opt)) {
20854                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20855            } else if ("--proto".equals(opt)) {
20856                dumpProto(fd);
20857                return;
20858            } else {
20859                pw.println("Unknown argument: " + opt + "; use -h for help");
20860            }
20861        }
20862
20863        // Is the caller requesting to dump a particular piece of data?
20864        if (opti < args.length) {
20865            String cmd = args[opti];
20866            opti++;
20867            // Is this a package name?
20868            if ("android".equals(cmd) || cmd.contains(".")) {
20869                packageName = cmd;
20870                // When dumping a single package, we always dump all of its
20871                // filter information since the amount of data will be reasonable.
20872                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20873            } else if ("check-permission".equals(cmd)) {
20874                if (opti >= args.length) {
20875                    pw.println("Error: check-permission missing permission argument");
20876                    return;
20877                }
20878                String perm = args[opti];
20879                opti++;
20880                if (opti >= args.length) {
20881                    pw.println("Error: check-permission missing package argument");
20882                    return;
20883                }
20884
20885                String pkg = args[opti];
20886                opti++;
20887                int user = UserHandle.getUserId(Binder.getCallingUid());
20888                if (opti < args.length) {
20889                    try {
20890                        user = Integer.parseInt(args[opti]);
20891                    } catch (NumberFormatException e) {
20892                        pw.println("Error: check-permission user argument is not a number: "
20893                                + args[opti]);
20894                        return;
20895                    }
20896                }
20897
20898                // Normalize package name to handle renamed packages and static libs
20899                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20900
20901                pw.println(checkPermission(perm, pkg, user));
20902                return;
20903            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20904                dumpState.setDump(DumpState.DUMP_LIBS);
20905            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20906                dumpState.setDump(DumpState.DUMP_FEATURES);
20907            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20908                if (opti >= args.length) {
20909                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20910                            | DumpState.DUMP_SERVICE_RESOLVERS
20911                            | DumpState.DUMP_RECEIVER_RESOLVERS
20912                            | DumpState.DUMP_CONTENT_RESOLVERS);
20913                } else {
20914                    while (opti < args.length) {
20915                        String name = args[opti];
20916                        if ("a".equals(name) || "activity".equals(name)) {
20917                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20918                        } else if ("s".equals(name) || "service".equals(name)) {
20919                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20920                        } else if ("r".equals(name) || "receiver".equals(name)) {
20921                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20922                        } else if ("c".equals(name) || "content".equals(name)) {
20923                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20924                        } else {
20925                            pw.println("Error: unknown resolver table type: " + name);
20926                            return;
20927                        }
20928                        opti++;
20929                    }
20930                }
20931            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20932                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20933            } else if ("permission".equals(cmd)) {
20934                if (opti >= args.length) {
20935                    pw.println("Error: permission requires permission name");
20936                    return;
20937                }
20938                permissionNames = new ArraySet<>();
20939                while (opti < args.length) {
20940                    permissionNames.add(args[opti]);
20941                    opti++;
20942                }
20943                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20944                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20945            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20946                dumpState.setDump(DumpState.DUMP_PREFERRED);
20947            } else if ("preferred-xml".equals(cmd)) {
20948                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20949                if (opti < args.length && "--full".equals(args[opti])) {
20950                    fullPreferred = true;
20951                    opti++;
20952                }
20953            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20954                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20955            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20956                dumpState.setDump(DumpState.DUMP_PACKAGES);
20957            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20958                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20959            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20960                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20961            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20962                dumpState.setDump(DumpState.DUMP_MESSAGES);
20963            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20964                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20965            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20966                    || "intent-filter-verifiers".equals(cmd)) {
20967                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20968            } else if ("version".equals(cmd)) {
20969                dumpState.setDump(DumpState.DUMP_VERSION);
20970            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20971                dumpState.setDump(DumpState.DUMP_KEYSETS);
20972            } else if ("installs".equals(cmd)) {
20973                dumpState.setDump(DumpState.DUMP_INSTALLS);
20974            } else if ("frozen".equals(cmd)) {
20975                dumpState.setDump(DumpState.DUMP_FROZEN);
20976            } else if ("dexopt".equals(cmd)) {
20977                dumpState.setDump(DumpState.DUMP_DEXOPT);
20978            } else if ("compiler-stats".equals(cmd)) {
20979                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20980            } else if ("enabled-overlays".equals(cmd)) {
20981                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
20982            } else if ("changes".equals(cmd)) {
20983                dumpState.setDump(DumpState.DUMP_CHANGES);
20984            } else if ("write".equals(cmd)) {
20985                synchronized (mPackages) {
20986                    mSettings.writeLPr();
20987                    pw.println("Settings written.");
20988                    return;
20989                }
20990            }
20991        }
20992
20993        if (checkin) {
20994            pw.println("vers,1");
20995        }
20996
20997        // reader
20998        synchronized (mPackages) {
20999            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21000                if (!checkin) {
21001                    if (dumpState.onTitlePrinted())
21002                        pw.println();
21003                    pw.println("Database versions:");
21004                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21005                }
21006            }
21007
21008            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21009                if (!checkin) {
21010                    if (dumpState.onTitlePrinted())
21011                        pw.println();
21012                    pw.println("Verifiers:");
21013                    pw.print("  Required: ");
21014                    pw.print(mRequiredVerifierPackage);
21015                    pw.print(" (uid=");
21016                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21017                            UserHandle.USER_SYSTEM));
21018                    pw.println(")");
21019                } else if (mRequiredVerifierPackage != null) {
21020                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21021                    pw.print(",");
21022                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21023                            UserHandle.USER_SYSTEM));
21024                }
21025            }
21026
21027            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21028                    packageName == null) {
21029                if (mIntentFilterVerifierComponent != null) {
21030                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21031                    if (!checkin) {
21032                        if (dumpState.onTitlePrinted())
21033                            pw.println();
21034                        pw.println("Intent Filter Verifier:");
21035                        pw.print("  Using: ");
21036                        pw.print(verifierPackageName);
21037                        pw.print(" (uid=");
21038                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21039                                UserHandle.USER_SYSTEM));
21040                        pw.println(")");
21041                    } else if (verifierPackageName != null) {
21042                        pw.print("ifv,"); pw.print(verifierPackageName);
21043                        pw.print(",");
21044                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21045                                UserHandle.USER_SYSTEM));
21046                    }
21047                } else {
21048                    pw.println();
21049                    pw.println("No Intent Filter Verifier available!");
21050                }
21051            }
21052
21053            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21054                boolean printedHeader = false;
21055                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21056                while (it.hasNext()) {
21057                    String libName = it.next();
21058                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21059                    if (versionedLib == null) {
21060                        continue;
21061                    }
21062                    final int versionCount = versionedLib.size();
21063                    for (int i = 0; i < versionCount; i++) {
21064                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21065                        if (!checkin) {
21066                            if (!printedHeader) {
21067                                if (dumpState.onTitlePrinted())
21068                                    pw.println();
21069                                pw.println("Libraries:");
21070                                printedHeader = true;
21071                            }
21072                            pw.print("  ");
21073                        } else {
21074                            pw.print("lib,");
21075                        }
21076                        pw.print(libEntry.info.getName());
21077                        if (libEntry.info.isStatic()) {
21078                            pw.print(" version=" + libEntry.info.getVersion());
21079                        }
21080                        if (!checkin) {
21081                            pw.print(" -> ");
21082                        }
21083                        if (libEntry.path != null) {
21084                            pw.print(" (jar) ");
21085                            pw.print(libEntry.path);
21086                        } else {
21087                            pw.print(" (apk) ");
21088                            pw.print(libEntry.apk);
21089                        }
21090                        pw.println();
21091                    }
21092                }
21093            }
21094
21095            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21096                if (dumpState.onTitlePrinted())
21097                    pw.println();
21098                if (!checkin) {
21099                    pw.println("Features:");
21100                }
21101
21102                synchronized (mAvailableFeatures) {
21103                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21104                        if (checkin) {
21105                            pw.print("feat,");
21106                            pw.print(feat.name);
21107                            pw.print(",");
21108                            pw.println(feat.version);
21109                        } else {
21110                            pw.print("  ");
21111                            pw.print(feat.name);
21112                            if (feat.version > 0) {
21113                                pw.print(" version=");
21114                                pw.print(feat.version);
21115                            }
21116                            pw.println();
21117                        }
21118                    }
21119                }
21120            }
21121
21122            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21123                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21124                        : "Activity Resolver Table:", "  ", packageName,
21125                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21126                    dumpState.setTitlePrinted(true);
21127                }
21128            }
21129            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21130                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21131                        : "Receiver Resolver Table:", "  ", packageName,
21132                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21133                    dumpState.setTitlePrinted(true);
21134                }
21135            }
21136            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21137                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21138                        : "Service Resolver Table:", "  ", packageName,
21139                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21140                    dumpState.setTitlePrinted(true);
21141                }
21142            }
21143            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21144                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21145                        : "Provider Resolver Table:", "  ", packageName,
21146                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21147                    dumpState.setTitlePrinted(true);
21148                }
21149            }
21150
21151            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21152                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21153                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21154                    int user = mSettings.mPreferredActivities.keyAt(i);
21155                    if (pir.dump(pw,
21156                            dumpState.getTitlePrinted()
21157                                ? "\nPreferred Activities User " + user + ":"
21158                                : "Preferred Activities User " + user + ":", "  ",
21159                            packageName, true, false)) {
21160                        dumpState.setTitlePrinted(true);
21161                    }
21162                }
21163            }
21164
21165            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21166                pw.flush();
21167                FileOutputStream fout = new FileOutputStream(fd);
21168                BufferedOutputStream str = new BufferedOutputStream(fout);
21169                XmlSerializer serializer = new FastXmlSerializer();
21170                try {
21171                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21172                    serializer.startDocument(null, true);
21173                    serializer.setFeature(
21174                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21175                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21176                    serializer.endDocument();
21177                    serializer.flush();
21178                } catch (IllegalArgumentException e) {
21179                    pw.println("Failed writing: " + e);
21180                } catch (IllegalStateException e) {
21181                    pw.println("Failed writing: " + e);
21182                } catch (IOException e) {
21183                    pw.println("Failed writing: " + e);
21184                }
21185            }
21186
21187            if (!checkin
21188                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21189                    && packageName == null) {
21190                pw.println();
21191                int count = mSettings.mPackages.size();
21192                if (count == 0) {
21193                    pw.println("No applications!");
21194                    pw.println();
21195                } else {
21196                    final String prefix = "  ";
21197                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21198                    if (allPackageSettings.size() == 0) {
21199                        pw.println("No domain preferred apps!");
21200                        pw.println();
21201                    } else {
21202                        pw.println("App verification status:");
21203                        pw.println();
21204                        count = 0;
21205                        for (PackageSetting ps : allPackageSettings) {
21206                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21207                            if (ivi == null || ivi.getPackageName() == null) continue;
21208                            pw.println(prefix + "Package: " + ivi.getPackageName());
21209                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21210                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21211                            pw.println();
21212                            count++;
21213                        }
21214                        if (count == 0) {
21215                            pw.println(prefix + "No app verification established.");
21216                            pw.println();
21217                        }
21218                        for (int userId : sUserManager.getUserIds()) {
21219                            pw.println("App linkages for user " + userId + ":");
21220                            pw.println();
21221                            count = 0;
21222                            for (PackageSetting ps : allPackageSettings) {
21223                                final long status = ps.getDomainVerificationStatusForUser(userId);
21224                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21225                                        && !DEBUG_DOMAIN_VERIFICATION) {
21226                                    continue;
21227                                }
21228                                pw.println(prefix + "Package: " + ps.name);
21229                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21230                                String statusStr = IntentFilterVerificationInfo.
21231                                        getStatusStringFromValue(status);
21232                                pw.println(prefix + "Status:  " + statusStr);
21233                                pw.println();
21234                                count++;
21235                            }
21236                            if (count == 0) {
21237                                pw.println(prefix + "No configured app linkages.");
21238                                pw.println();
21239                            }
21240                        }
21241                    }
21242                }
21243            }
21244
21245            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21246                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21247                if (packageName == null && permissionNames == null) {
21248                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
21249                        if (iperm == 0) {
21250                            if (dumpState.onTitlePrinted())
21251                                pw.println();
21252                            pw.println("AppOp Permissions:");
21253                        }
21254                        pw.print("  AppOp Permission ");
21255                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
21256                        pw.println(":");
21257                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
21258                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
21259                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
21260                        }
21261                    }
21262                }
21263            }
21264
21265            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21266                boolean printedSomething = false;
21267                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21268                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21269                        continue;
21270                    }
21271                    if (!printedSomething) {
21272                        if (dumpState.onTitlePrinted())
21273                            pw.println();
21274                        pw.println("Registered ContentProviders:");
21275                        printedSomething = true;
21276                    }
21277                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21278                    pw.print("    "); pw.println(p.toString());
21279                }
21280                printedSomething = false;
21281                for (Map.Entry<String, PackageParser.Provider> entry :
21282                        mProvidersByAuthority.entrySet()) {
21283                    PackageParser.Provider p = entry.getValue();
21284                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21285                        continue;
21286                    }
21287                    if (!printedSomething) {
21288                        if (dumpState.onTitlePrinted())
21289                            pw.println();
21290                        pw.println("ContentProvider Authorities:");
21291                        printedSomething = true;
21292                    }
21293                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21294                    pw.print("    "); pw.println(p.toString());
21295                    if (p.info != null && p.info.applicationInfo != null) {
21296                        final String appInfo = p.info.applicationInfo.toString();
21297                        pw.print("      applicationInfo="); pw.println(appInfo);
21298                    }
21299                }
21300            }
21301
21302            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21303                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21304            }
21305
21306            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21307                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21308            }
21309
21310            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21311                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21312            }
21313
21314            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21315                if (dumpState.onTitlePrinted()) pw.println();
21316                pw.println("Package Changes:");
21317                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21318                final int K = mChangedPackages.size();
21319                for (int i = 0; i < K; i++) {
21320                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21321                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21322                    final int N = changes.size();
21323                    if (N == 0) {
21324                        pw.print("    "); pw.println("No packages changed");
21325                    } else {
21326                        for (int j = 0; j < N; j++) {
21327                            final String pkgName = changes.valueAt(j);
21328                            final int sequenceNumber = changes.keyAt(j);
21329                            pw.print("    ");
21330                            pw.print("seq=");
21331                            pw.print(sequenceNumber);
21332                            pw.print(", package=");
21333                            pw.println(pkgName);
21334                        }
21335                    }
21336                }
21337            }
21338
21339            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21340                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21341            }
21342
21343            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21344                // XXX should handle packageName != null by dumping only install data that
21345                // the given package is involved with.
21346                if (dumpState.onTitlePrinted()) pw.println();
21347
21348                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21349                ipw.println();
21350                ipw.println("Frozen packages:");
21351                ipw.increaseIndent();
21352                if (mFrozenPackages.size() == 0) {
21353                    ipw.println("(none)");
21354                } else {
21355                    for (int i = 0; i < mFrozenPackages.size(); i++) {
21356                        ipw.println(mFrozenPackages.valueAt(i));
21357                    }
21358                }
21359                ipw.decreaseIndent();
21360            }
21361
21362            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21363                if (dumpState.onTitlePrinted()) pw.println();
21364                dumpDexoptStateLPr(pw, packageName);
21365            }
21366
21367            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21368                if (dumpState.onTitlePrinted()) pw.println();
21369                dumpCompilerStatsLPr(pw, packageName);
21370            }
21371
21372            if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) {
21373                if (dumpState.onTitlePrinted()) pw.println();
21374                dumpEnabledOverlaysLPr(pw);
21375            }
21376
21377            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21378                if (dumpState.onTitlePrinted()) pw.println();
21379                mSettings.dumpReadMessagesLPr(pw, dumpState);
21380
21381                pw.println();
21382                pw.println("Package warning messages:");
21383                BufferedReader in = null;
21384                String line = null;
21385                try {
21386                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21387                    while ((line = in.readLine()) != null) {
21388                        if (line.contains("ignored: updated version")) continue;
21389                        pw.println(line);
21390                    }
21391                } catch (IOException ignored) {
21392                } finally {
21393                    IoUtils.closeQuietly(in);
21394                }
21395            }
21396
21397            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21398                BufferedReader in = null;
21399                String line = null;
21400                try {
21401                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21402                    while ((line = in.readLine()) != null) {
21403                        if (line.contains("ignored: updated version")) continue;
21404                        pw.print("msg,");
21405                        pw.println(line);
21406                    }
21407                } catch (IOException ignored) {
21408                } finally {
21409                    IoUtils.closeQuietly(in);
21410                }
21411            }
21412        }
21413
21414        // PackageInstaller should be called outside of mPackages lock
21415        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21416            // XXX should handle packageName != null by dumping only install data that
21417            // the given package is involved with.
21418            if (dumpState.onTitlePrinted()) pw.println();
21419            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21420        }
21421    }
21422
21423    private void dumpProto(FileDescriptor fd) {
21424        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21425
21426        synchronized (mPackages) {
21427            final long requiredVerifierPackageToken =
21428                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21429            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21430            proto.write(
21431                    PackageServiceDumpProto.PackageShortProto.UID,
21432                    getPackageUid(
21433                            mRequiredVerifierPackage,
21434                            MATCH_DEBUG_TRIAGED_MISSING,
21435                            UserHandle.USER_SYSTEM));
21436            proto.end(requiredVerifierPackageToken);
21437
21438            if (mIntentFilterVerifierComponent != null) {
21439                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21440                final long verifierPackageToken =
21441                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21442                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21443                proto.write(
21444                        PackageServiceDumpProto.PackageShortProto.UID,
21445                        getPackageUid(
21446                                verifierPackageName,
21447                                MATCH_DEBUG_TRIAGED_MISSING,
21448                                UserHandle.USER_SYSTEM));
21449                proto.end(verifierPackageToken);
21450            }
21451
21452            dumpSharedLibrariesProto(proto);
21453            dumpFeaturesProto(proto);
21454            mSettings.dumpPackagesProto(proto);
21455            mSettings.dumpSharedUsersProto(proto);
21456            dumpMessagesProto(proto);
21457        }
21458        proto.flush();
21459    }
21460
21461    private void dumpMessagesProto(ProtoOutputStream proto) {
21462        BufferedReader in = null;
21463        String line = null;
21464        try {
21465            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
21466            while ((line = in.readLine()) != null) {
21467                if (line.contains("ignored: updated version")) continue;
21468                proto.write(PackageServiceDumpProto.MESSAGES, line);
21469            }
21470        } catch (IOException ignored) {
21471        } finally {
21472            IoUtils.closeQuietly(in);
21473        }
21474    }
21475
21476    private void dumpFeaturesProto(ProtoOutputStream proto) {
21477        synchronized (mAvailableFeatures) {
21478            final int count = mAvailableFeatures.size();
21479            for (int i = 0; i < count; i++) {
21480                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
21481                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
21482                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
21483                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
21484                proto.end(featureToken);
21485            }
21486        }
21487    }
21488
21489    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21490        final int count = mSharedLibraries.size();
21491        for (int i = 0; i < count; i++) {
21492            final String libName = mSharedLibraries.keyAt(i);
21493            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21494            if (versionedLib == null) {
21495                continue;
21496            }
21497            final int versionCount = versionedLib.size();
21498            for (int j = 0; j < versionCount; j++) {
21499                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21500                final long sharedLibraryToken =
21501                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21502                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21503                final boolean isJar = (libEntry.path != null);
21504                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21505                if (isJar) {
21506                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21507                } else {
21508                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21509                }
21510                proto.end(sharedLibraryToken);
21511            }
21512        }
21513    }
21514
21515    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21516        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21517        ipw.println();
21518        ipw.println("Dexopt state:");
21519        ipw.increaseIndent();
21520        Collection<PackageParser.Package> packages = null;
21521        if (packageName != null) {
21522            PackageParser.Package targetPackage = mPackages.get(packageName);
21523            if (targetPackage != null) {
21524                packages = Collections.singletonList(targetPackage);
21525            } else {
21526                ipw.println("Unable to find package: " + packageName);
21527                return;
21528            }
21529        } else {
21530            packages = mPackages.values();
21531        }
21532
21533        for (PackageParser.Package pkg : packages) {
21534            ipw.println("[" + pkg.packageName + "]");
21535            ipw.increaseIndent();
21536            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
21537            ipw.decreaseIndent();
21538        }
21539    }
21540
21541    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21542        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21543        ipw.println();
21544        ipw.println("Compiler stats:");
21545        ipw.increaseIndent();
21546        Collection<PackageParser.Package> packages = null;
21547        if (packageName != null) {
21548            PackageParser.Package targetPackage = mPackages.get(packageName);
21549            if (targetPackage != null) {
21550                packages = Collections.singletonList(targetPackage);
21551            } else {
21552                ipw.println("Unable to find package: " + packageName);
21553                return;
21554            }
21555        } else {
21556            packages = mPackages.values();
21557        }
21558
21559        for (PackageParser.Package pkg : packages) {
21560            ipw.println("[" + pkg.packageName + "]");
21561            ipw.increaseIndent();
21562
21563            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21564            if (stats == null) {
21565                ipw.println("(No recorded stats)");
21566            } else {
21567                stats.dump(ipw);
21568            }
21569            ipw.decreaseIndent();
21570        }
21571    }
21572
21573    private void dumpEnabledOverlaysLPr(PrintWriter pw) {
21574        pw.println("Enabled overlay paths:");
21575        final int N = mEnabledOverlayPaths.size();
21576        for (int i = 0; i < N; i++) {
21577            final int userId = mEnabledOverlayPaths.keyAt(i);
21578            pw.println(String.format("    User %d:", userId));
21579            final ArrayMap<String, ArrayList<String>> userSpecificOverlays =
21580                mEnabledOverlayPaths.valueAt(i);
21581            final int M = userSpecificOverlays.size();
21582            for (int j = 0; j < M; j++) {
21583                final String targetPackageName = userSpecificOverlays.keyAt(j);
21584                final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j);
21585                pw.println(String.format("        %s: %s", targetPackageName, overlayPackagePaths));
21586            }
21587        }
21588    }
21589
21590    private String dumpDomainString(String packageName) {
21591        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21592                .getList();
21593        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21594
21595        ArraySet<String> result = new ArraySet<>();
21596        if (iviList.size() > 0) {
21597            for (IntentFilterVerificationInfo ivi : iviList) {
21598                for (String host : ivi.getDomains()) {
21599                    result.add(host);
21600                }
21601            }
21602        }
21603        if (filters != null && filters.size() > 0) {
21604            for (IntentFilter filter : filters) {
21605                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21606                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21607                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21608                    result.addAll(filter.getHostsList());
21609                }
21610            }
21611        }
21612
21613        StringBuilder sb = new StringBuilder(result.size() * 16);
21614        for (String domain : result) {
21615            if (sb.length() > 0) sb.append(" ");
21616            sb.append(domain);
21617        }
21618        return sb.toString();
21619    }
21620
21621    // ------- apps on sdcard specific code -------
21622    static final boolean DEBUG_SD_INSTALL = false;
21623
21624    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21625
21626    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21627
21628    private boolean mMediaMounted = false;
21629
21630    static String getEncryptKey() {
21631        try {
21632            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21633                    SD_ENCRYPTION_KEYSTORE_NAME);
21634            if (sdEncKey == null) {
21635                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21636                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21637                if (sdEncKey == null) {
21638                    Slog.e(TAG, "Failed to create encryption keys");
21639                    return null;
21640                }
21641            }
21642            return sdEncKey;
21643        } catch (NoSuchAlgorithmException nsae) {
21644            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21645            return null;
21646        } catch (IOException ioe) {
21647            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21648            return null;
21649        }
21650    }
21651
21652    /*
21653     * Update media status on PackageManager.
21654     */
21655    @Override
21656    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
21657        int callingUid = Binder.getCallingUid();
21658        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
21659            throw new SecurityException("Media status can only be updated by the system");
21660        }
21661        // reader; this apparently protects mMediaMounted, but should probably
21662        // be a different lock in that case.
21663        synchronized (mPackages) {
21664            Log.i(TAG, "Updating external media status from "
21665                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
21666                    + (mediaStatus ? "mounted" : "unmounted"));
21667            if (DEBUG_SD_INSTALL)
21668                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
21669                        + ", mMediaMounted=" + mMediaMounted);
21670            if (mediaStatus == mMediaMounted) {
21671                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
21672                        : 0, -1);
21673                mHandler.sendMessage(msg);
21674                return;
21675            }
21676            mMediaMounted = mediaStatus;
21677        }
21678        // Queue up an async operation since the package installation may take a
21679        // little while.
21680        mHandler.post(new Runnable() {
21681            public void run() {
21682                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
21683            }
21684        });
21685    }
21686
21687    /**
21688     * Called by StorageManagerService when the initial ASECs to scan are available.
21689     * Should block until all the ASEC containers are finished being scanned.
21690     */
21691    public void scanAvailableAsecs() {
21692        updateExternalMediaStatusInner(true, false, false);
21693    }
21694
21695    /*
21696     * Collect information of applications on external media, map them against
21697     * existing containers and update information based on current mount status.
21698     * Please note that we always have to report status if reportStatus has been
21699     * set to true especially when unloading packages.
21700     */
21701    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
21702            boolean externalStorage) {
21703        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
21704        int[] uidArr = EmptyArray.INT;
21705
21706        final String[] list = PackageHelper.getSecureContainerList();
21707        if (ArrayUtils.isEmpty(list)) {
21708            Log.i(TAG, "No secure containers found");
21709        } else {
21710            // Process list of secure containers and categorize them
21711            // as active or stale based on their package internal state.
21712
21713            // reader
21714            synchronized (mPackages) {
21715                for (String cid : list) {
21716                    // Leave stages untouched for now; installer service owns them
21717                    if (PackageInstallerService.isStageName(cid)) continue;
21718
21719                    if (DEBUG_SD_INSTALL)
21720                        Log.i(TAG, "Processing container " + cid);
21721                    String pkgName = getAsecPackageName(cid);
21722                    if (pkgName == null) {
21723                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
21724                        continue;
21725                    }
21726                    if (DEBUG_SD_INSTALL)
21727                        Log.i(TAG, "Looking for pkg : " + pkgName);
21728
21729                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
21730                    if (ps == null) {
21731                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
21732                        continue;
21733                    }
21734
21735                    /*
21736                     * Skip packages that are not external if we're unmounting
21737                     * external storage.
21738                     */
21739                    if (externalStorage && !isMounted && !isExternal(ps)) {
21740                        continue;
21741                    }
21742
21743                    final AsecInstallArgs args = new AsecInstallArgs(cid,
21744                            getAppDexInstructionSets(ps), ps.isForwardLocked());
21745                    // The package status is changed only if the code path
21746                    // matches between settings and the container id.
21747                    if (ps.codePathString != null
21748                            && ps.codePathString.startsWith(args.getCodePath())) {
21749                        if (DEBUG_SD_INSTALL) {
21750                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
21751                                    + " at code path: " + ps.codePathString);
21752                        }
21753
21754                        // We do have a valid package installed on sdcard
21755                        processCids.put(args, ps.codePathString);
21756                        final int uid = ps.appId;
21757                        if (uid != -1) {
21758                            uidArr = ArrayUtils.appendInt(uidArr, uid);
21759                        }
21760                    } else {
21761                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
21762                                + ps.codePathString);
21763                    }
21764                }
21765            }
21766
21767            Arrays.sort(uidArr);
21768        }
21769
21770        // Process packages with valid entries.
21771        if (isMounted) {
21772            if (DEBUG_SD_INSTALL)
21773                Log.i(TAG, "Loading packages");
21774            loadMediaPackages(processCids, uidArr, externalStorage);
21775            startCleaningPackages();
21776            mInstallerService.onSecureContainersAvailable();
21777        } else {
21778            if (DEBUG_SD_INSTALL)
21779                Log.i(TAG, "Unloading packages");
21780            unloadMediaPackages(processCids, uidArr, reportStatus);
21781        }
21782    }
21783
21784    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21785            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21786        final int size = infos.size();
21787        final String[] packageNames = new String[size];
21788        final int[] packageUids = new int[size];
21789        for (int i = 0; i < size; i++) {
21790            final ApplicationInfo info = infos.get(i);
21791            packageNames[i] = info.packageName;
21792            packageUids[i] = info.uid;
21793        }
21794        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21795                finishedReceiver);
21796    }
21797
21798    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21799            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21800        sendResourcesChangedBroadcast(mediaStatus, replacing,
21801                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21802    }
21803
21804    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21805            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21806        int size = pkgList.length;
21807        if (size > 0) {
21808            // Send broadcasts here
21809            Bundle extras = new Bundle();
21810            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21811            if (uidArr != null) {
21812                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21813            }
21814            if (replacing) {
21815                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21816            }
21817            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21818                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21819            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21820        }
21821    }
21822
21823   /*
21824     * Look at potentially valid container ids from processCids If package
21825     * information doesn't match the one on record or package scanning fails,
21826     * the cid is added to list of removeCids. We currently don't delete stale
21827     * containers.
21828     */
21829    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
21830            boolean externalStorage) {
21831        ArrayList<String> pkgList = new ArrayList<String>();
21832        Set<AsecInstallArgs> keys = processCids.keySet();
21833
21834        for (AsecInstallArgs args : keys) {
21835            String codePath = processCids.get(args);
21836            if (DEBUG_SD_INSTALL)
21837                Log.i(TAG, "Loading container : " + args.cid);
21838            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
21839            try {
21840                // Make sure there are no container errors first.
21841                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
21842                    Slog.e(TAG, "Failed to mount cid : " + args.cid
21843                            + " when installing from sdcard");
21844                    continue;
21845                }
21846                // Check code path here.
21847                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
21848                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
21849                            + " does not match one in settings " + codePath);
21850                    continue;
21851                }
21852                // Parse package
21853                int parseFlags = mDefParseFlags;
21854                if (args.isExternalAsec()) {
21855                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21856                }
21857                if (args.isFwdLocked()) {
21858                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21859                }
21860
21861                synchronized (mInstallLock) {
21862                    PackageParser.Package pkg = null;
21863                    try {
21864                        // Sadly we don't know the package name yet to freeze it
21865                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21866                                SCAN_IGNORE_FROZEN, 0, null);
21867                    } catch (PackageManagerException e) {
21868                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21869                    }
21870                    // Scan the package
21871                    if (pkg != null) {
21872                        /*
21873                         * TODO why is the lock being held? doPostInstall is
21874                         * called in other places without the lock. This needs
21875                         * to be straightened out.
21876                         */
21877                        // writer
21878                        synchronized (mPackages) {
21879                            retCode = PackageManager.INSTALL_SUCCEEDED;
21880                            pkgList.add(pkg.packageName);
21881                            // Post process args
21882                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21883                                    pkg.applicationInfo.uid);
21884                        }
21885                    } else {
21886                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21887                    }
21888                }
21889
21890            } finally {
21891                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21892                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21893                }
21894            }
21895        }
21896        // writer
21897        synchronized (mPackages) {
21898            // If the platform SDK has changed since the last time we booted,
21899            // we need to re-grant app permission to catch any new ones that
21900            // appear. This is really a hack, and means that apps can in some
21901            // cases get permissions that the user didn't initially explicitly
21902            // allow... it would be nice to have some better way to handle
21903            // this situation.
21904            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21905                    : mSettings.getInternalVersion();
21906            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21907                    : StorageManager.UUID_PRIVATE_INTERNAL;
21908
21909            int updateFlags = UPDATE_PERMISSIONS_ALL;
21910            if (ver.sdkVersion != mSdkVersion) {
21911                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21912                        + mSdkVersion + "; regranting permissions for external");
21913                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21914            }
21915            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21916
21917            // Yay, everything is now upgraded
21918            ver.forceCurrent();
21919
21920            // can downgrade to reader
21921            // Persist settings
21922            mSettings.writeLPr();
21923        }
21924        // Send a broadcast to let everyone know we are done processing
21925        if (pkgList.size() > 0) {
21926            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21927        }
21928    }
21929
21930   /*
21931     * Utility method to unload a list of specified containers
21932     */
21933    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21934        // Just unmount all valid containers.
21935        for (AsecInstallArgs arg : cidArgs) {
21936            synchronized (mInstallLock) {
21937                arg.doPostDeleteLI(false);
21938           }
21939       }
21940   }
21941
21942    /*
21943     * Unload packages mounted on external media. This involves deleting package
21944     * data from internal structures, sending broadcasts about disabled packages,
21945     * gc'ing to free up references, unmounting all secure containers
21946     * corresponding to packages on external media, and posting a
21947     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21948     * that we always have to post this message if status has been requested no
21949     * matter what.
21950     */
21951    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21952            final boolean reportStatus) {
21953        if (DEBUG_SD_INSTALL)
21954            Log.i(TAG, "unloading media packages");
21955        ArrayList<String> pkgList = new ArrayList<String>();
21956        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21957        final Set<AsecInstallArgs> keys = processCids.keySet();
21958        for (AsecInstallArgs args : keys) {
21959            String pkgName = args.getPackageName();
21960            if (DEBUG_SD_INSTALL)
21961                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21962            // Delete package internally
21963            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
21964            synchronized (mInstallLock) {
21965                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21966                final boolean res;
21967                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21968                        "unloadMediaPackages")) {
21969                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21970                            null);
21971                }
21972                if (res) {
21973                    pkgList.add(pkgName);
21974                } else {
21975                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21976                    failedList.add(args);
21977                }
21978            }
21979        }
21980
21981        // reader
21982        synchronized (mPackages) {
21983            // We didn't update the settings after removing each package;
21984            // write them now for all packages.
21985            mSettings.writeLPr();
21986        }
21987
21988        // We have to absolutely send UPDATED_MEDIA_STATUS only
21989        // after confirming that all the receivers processed the ordered
21990        // broadcast when packages get disabled, force a gc to clean things up.
21991        // and unload all the containers.
21992        if (pkgList.size() > 0) {
21993            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21994                    new IIntentReceiver.Stub() {
21995                public void performReceive(Intent intent, int resultCode, String data,
21996                        Bundle extras, boolean ordered, boolean sticky,
21997                        int sendingUser) throws RemoteException {
21998                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21999                            reportStatus ? 1 : 0, 1, keys);
22000                    mHandler.sendMessage(msg);
22001                }
22002            });
22003        } else {
22004            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
22005                    keys);
22006            mHandler.sendMessage(msg);
22007        }
22008    }
22009
22010    private void loadPrivatePackages(final VolumeInfo vol) {
22011        mHandler.post(new Runnable() {
22012            @Override
22013            public void run() {
22014                loadPrivatePackagesInner(vol);
22015            }
22016        });
22017    }
22018
22019    private void loadPrivatePackagesInner(VolumeInfo vol) {
22020        final String volumeUuid = vol.fsUuid;
22021        if (TextUtils.isEmpty(volumeUuid)) {
22022            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22023            return;
22024        }
22025
22026        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22027        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22028        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22029
22030        final VersionInfo ver;
22031        final List<PackageSetting> packages;
22032        synchronized (mPackages) {
22033            ver = mSettings.findOrCreateVersion(volumeUuid);
22034            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22035        }
22036
22037        for (PackageSetting ps : packages) {
22038            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22039            synchronized (mInstallLock) {
22040                final PackageParser.Package pkg;
22041                try {
22042                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22043                    loaded.add(pkg.applicationInfo);
22044
22045                } catch (PackageManagerException e) {
22046                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22047                }
22048
22049                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22050                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22051                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22052                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22053                }
22054            }
22055        }
22056
22057        // Reconcile app data for all started/unlocked users
22058        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22059        final UserManager um = mContext.getSystemService(UserManager.class);
22060        UserManagerInternal umInternal = getUserManagerInternal();
22061        for (UserInfo user : um.getUsers()) {
22062            final int flags;
22063            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22064                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22065            } else if (umInternal.isUserRunning(user.id)) {
22066                flags = StorageManager.FLAG_STORAGE_DE;
22067            } else {
22068                continue;
22069            }
22070
22071            try {
22072                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22073                synchronized (mInstallLock) {
22074                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22075                }
22076            } catch (IllegalStateException e) {
22077                // Device was probably ejected, and we'll process that event momentarily
22078                Slog.w(TAG, "Failed to prepare storage: " + e);
22079            }
22080        }
22081
22082        synchronized (mPackages) {
22083            int updateFlags = UPDATE_PERMISSIONS_ALL;
22084            if (ver.sdkVersion != mSdkVersion) {
22085                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22086                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22087                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22088            }
22089            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22090
22091            // Yay, everything is now upgraded
22092            ver.forceCurrent();
22093
22094            mSettings.writeLPr();
22095        }
22096
22097        for (PackageFreezer freezer : freezers) {
22098            freezer.close();
22099        }
22100
22101        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22102        sendResourcesChangedBroadcast(true, false, loaded, null);
22103    }
22104
22105    private void unloadPrivatePackages(final VolumeInfo vol) {
22106        mHandler.post(new Runnable() {
22107            @Override
22108            public void run() {
22109                unloadPrivatePackagesInner(vol);
22110            }
22111        });
22112    }
22113
22114    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22115        final String volumeUuid = vol.fsUuid;
22116        if (TextUtils.isEmpty(volumeUuid)) {
22117            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22118            return;
22119        }
22120
22121        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22122        synchronized (mInstallLock) {
22123        synchronized (mPackages) {
22124            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22125            for (PackageSetting ps : packages) {
22126                if (ps.pkg == null) continue;
22127
22128                final ApplicationInfo info = ps.pkg.applicationInfo;
22129                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22130                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22131
22132                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22133                        "unloadPrivatePackagesInner")) {
22134                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22135                            false, null)) {
22136                        unloaded.add(info);
22137                    } else {
22138                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22139                    }
22140                }
22141
22142                // Try very hard to release any references to this package
22143                // so we don't risk the system server being killed due to
22144                // open FDs
22145                AttributeCache.instance().removePackage(ps.name);
22146            }
22147
22148            mSettings.writeLPr();
22149        }
22150        }
22151
22152        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22153        sendResourcesChangedBroadcast(false, false, unloaded, null);
22154
22155        // Try very hard to release any references to this path so we don't risk
22156        // the system server being killed due to open FDs
22157        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22158
22159        for (int i = 0; i < 3; i++) {
22160            System.gc();
22161            System.runFinalization();
22162        }
22163    }
22164
22165    private void assertPackageKnown(String volumeUuid, String packageName)
22166            throws PackageManagerException {
22167        synchronized (mPackages) {
22168            // Normalize package name to handle renamed packages
22169            packageName = normalizePackageNameLPr(packageName);
22170
22171            final PackageSetting ps = mSettings.mPackages.get(packageName);
22172            if (ps == null) {
22173                throw new PackageManagerException("Package " + packageName + " is unknown");
22174            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22175                throw new PackageManagerException(
22176                        "Package " + packageName + " found on unknown volume " + volumeUuid
22177                                + "; expected volume " + ps.volumeUuid);
22178            }
22179        }
22180    }
22181
22182    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22183            throws PackageManagerException {
22184        synchronized (mPackages) {
22185            // Normalize package name to handle renamed packages
22186            packageName = normalizePackageNameLPr(packageName);
22187
22188            final PackageSetting ps = mSettings.mPackages.get(packageName);
22189            if (ps == null) {
22190                throw new PackageManagerException("Package " + packageName + " is unknown");
22191            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22192                throw new PackageManagerException(
22193                        "Package " + packageName + " found on unknown volume " + volumeUuid
22194                                + "; expected volume " + ps.volumeUuid);
22195            } else if (!ps.getInstalled(userId)) {
22196                throw new PackageManagerException(
22197                        "Package " + packageName + " not installed for user " + userId);
22198            }
22199        }
22200    }
22201
22202    private List<String> collectAbsoluteCodePaths() {
22203        synchronized (mPackages) {
22204            List<String> codePaths = new ArrayList<>();
22205            final int packageCount = mSettings.mPackages.size();
22206            for (int i = 0; i < packageCount; i++) {
22207                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22208                codePaths.add(ps.codePath.getAbsolutePath());
22209            }
22210            return codePaths;
22211        }
22212    }
22213
22214    /**
22215     * Examine all apps present on given mounted volume, and destroy apps that
22216     * aren't expected, either due to uninstallation or reinstallation on
22217     * another volume.
22218     */
22219    private void reconcileApps(String volumeUuid) {
22220        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22221        List<File> filesToDelete = null;
22222
22223        final File[] files = FileUtils.listFilesOrEmpty(
22224                Environment.getDataAppDirectory(volumeUuid));
22225        for (File file : files) {
22226            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22227                    && !PackageInstallerService.isStageName(file.getName());
22228            if (!isPackage) {
22229                // Ignore entries which are not packages
22230                continue;
22231            }
22232
22233            String absolutePath = file.getAbsolutePath();
22234
22235            boolean pathValid = false;
22236            final int absoluteCodePathCount = absoluteCodePaths.size();
22237            for (int i = 0; i < absoluteCodePathCount; i++) {
22238                String absoluteCodePath = absoluteCodePaths.get(i);
22239                if (absolutePath.startsWith(absoluteCodePath)) {
22240                    pathValid = true;
22241                    break;
22242                }
22243            }
22244
22245            if (!pathValid) {
22246                if (filesToDelete == null) {
22247                    filesToDelete = new ArrayList<>();
22248                }
22249                filesToDelete.add(file);
22250            }
22251        }
22252
22253        if (filesToDelete != null) {
22254            final int fileToDeleteCount = filesToDelete.size();
22255            for (int i = 0; i < fileToDeleteCount; i++) {
22256                File fileToDelete = filesToDelete.get(i);
22257                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22258                synchronized (mInstallLock) {
22259                    removeCodePathLI(fileToDelete);
22260                }
22261            }
22262        }
22263    }
22264
22265    /**
22266     * Reconcile all app data for the given user.
22267     * <p>
22268     * Verifies that directories exist and that ownership and labeling is
22269     * correct for all installed apps on all mounted volumes.
22270     */
22271    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22272        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22273        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22274            final String volumeUuid = vol.getFsUuid();
22275            synchronized (mInstallLock) {
22276                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22277            }
22278        }
22279    }
22280
22281    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22282            boolean migrateAppData) {
22283        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22284    }
22285
22286    /**
22287     * Reconcile all app data on given mounted volume.
22288     * <p>
22289     * Destroys app data that isn't expected, either due to uninstallation or
22290     * reinstallation on another volume.
22291     * <p>
22292     * Verifies that directories exist and that ownership and labeling is
22293     * correct for all installed apps.
22294     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22295     */
22296    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22297            boolean migrateAppData, boolean onlyCoreApps) {
22298        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22299                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22300        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22301
22302        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22303        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22304
22305        // First look for stale data that doesn't belong, and check if things
22306        // have changed since we did our last restorecon
22307        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22308            if (StorageManager.isFileEncryptedNativeOrEmulated()
22309                    && !StorageManager.isUserKeyUnlocked(userId)) {
22310                throw new RuntimeException(
22311                        "Yikes, someone asked us to reconcile CE storage while " + userId
22312                                + " was still locked; this would have caused massive data loss!");
22313            }
22314
22315            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22316            for (File file : files) {
22317                final String packageName = file.getName();
22318                try {
22319                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22320                } catch (PackageManagerException e) {
22321                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22322                    try {
22323                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22324                                StorageManager.FLAG_STORAGE_CE, 0);
22325                    } catch (InstallerException e2) {
22326                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22327                    }
22328                }
22329            }
22330        }
22331        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22332            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22333            for (File file : files) {
22334                final String packageName = file.getName();
22335                try {
22336                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22337                } catch (PackageManagerException e) {
22338                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22339                    try {
22340                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22341                                StorageManager.FLAG_STORAGE_DE, 0);
22342                    } catch (InstallerException e2) {
22343                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22344                    }
22345                }
22346            }
22347        }
22348
22349        // Ensure that data directories are ready to roll for all packages
22350        // installed for this volume and user
22351        final List<PackageSetting> packages;
22352        synchronized (mPackages) {
22353            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22354        }
22355        int preparedCount = 0;
22356        for (PackageSetting ps : packages) {
22357            final String packageName = ps.name;
22358            if (ps.pkg == null) {
22359                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22360                // TODO: might be due to legacy ASEC apps; we should circle back
22361                // and reconcile again once they're scanned
22362                continue;
22363            }
22364            // Skip non-core apps if requested
22365            if (onlyCoreApps && !ps.pkg.coreApp) {
22366                result.add(packageName);
22367                continue;
22368            }
22369
22370            if (ps.getInstalled(userId)) {
22371                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22372                preparedCount++;
22373            }
22374        }
22375
22376        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22377        return result;
22378    }
22379
22380    /**
22381     * Prepare app data for the given app just after it was installed or
22382     * upgraded. This method carefully only touches users that it's installed
22383     * for, and it forces a restorecon to handle any seinfo changes.
22384     * <p>
22385     * Verifies that directories exist and that ownership and labeling is
22386     * correct for all installed apps. If there is an ownership mismatch, it
22387     * will try recovering system apps by wiping data; third-party app data is
22388     * left intact.
22389     * <p>
22390     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22391     */
22392    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22393        final PackageSetting ps;
22394        synchronized (mPackages) {
22395            ps = mSettings.mPackages.get(pkg.packageName);
22396            mSettings.writeKernelMappingLPr(ps);
22397        }
22398
22399        final UserManager um = mContext.getSystemService(UserManager.class);
22400        UserManagerInternal umInternal = getUserManagerInternal();
22401        for (UserInfo user : um.getUsers()) {
22402            final int flags;
22403            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22404                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22405            } else if (umInternal.isUserRunning(user.id)) {
22406                flags = StorageManager.FLAG_STORAGE_DE;
22407            } else {
22408                continue;
22409            }
22410
22411            if (ps.getInstalled(user.id)) {
22412                // TODO: when user data is locked, mark that we're still dirty
22413                prepareAppDataLIF(pkg, user.id, flags);
22414            }
22415        }
22416    }
22417
22418    /**
22419     * Prepare app data for the given app.
22420     * <p>
22421     * Verifies that directories exist and that ownership and labeling is
22422     * correct for all installed apps. If there is an ownership mismatch, this
22423     * will try recovering system apps by wiping data; third-party app data is
22424     * left intact.
22425     */
22426    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22427        if (pkg == null) {
22428            Slog.wtf(TAG, "Package was null!", new Throwable());
22429            return;
22430        }
22431        prepareAppDataLeafLIF(pkg, userId, flags);
22432        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22433        for (int i = 0; i < childCount; i++) {
22434            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22435        }
22436    }
22437
22438    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22439            boolean maybeMigrateAppData) {
22440        prepareAppDataLIF(pkg, userId, flags);
22441
22442        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22443            // We may have just shuffled around app data directories, so
22444            // prepare them one more time
22445            prepareAppDataLIF(pkg, userId, flags);
22446        }
22447    }
22448
22449    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22450        if (DEBUG_APP_DATA) {
22451            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22452                    + Integer.toHexString(flags));
22453        }
22454
22455        final String volumeUuid = pkg.volumeUuid;
22456        final String packageName = pkg.packageName;
22457        final ApplicationInfo app = pkg.applicationInfo;
22458        final int appId = UserHandle.getAppId(app.uid);
22459
22460        Preconditions.checkNotNull(app.seInfo);
22461
22462        long ceDataInode = -1;
22463        try {
22464            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22465                    appId, app.seInfo, app.targetSdkVersion);
22466        } catch (InstallerException e) {
22467            if (app.isSystemApp()) {
22468                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22469                        + ", but trying to recover: " + e);
22470                destroyAppDataLeafLIF(pkg, userId, flags);
22471                try {
22472                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22473                            appId, app.seInfo, app.targetSdkVersion);
22474                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22475                } catch (InstallerException e2) {
22476                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22477                }
22478            } else {
22479                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22480            }
22481        }
22482
22483        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22484            // TODO: mark this structure as dirty so we persist it!
22485            synchronized (mPackages) {
22486                final PackageSetting ps = mSettings.mPackages.get(packageName);
22487                if (ps != null) {
22488                    ps.setCeDataInode(ceDataInode, userId);
22489                }
22490            }
22491        }
22492
22493        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22494    }
22495
22496    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22497        if (pkg == null) {
22498            Slog.wtf(TAG, "Package was null!", new Throwable());
22499            return;
22500        }
22501        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22502        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22503        for (int i = 0; i < childCount; i++) {
22504            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22505        }
22506    }
22507
22508    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22509        final String volumeUuid = pkg.volumeUuid;
22510        final String packageName = pkg.packageName;
22511        final ApplicationInfo app = pkg.applicationInfo;
22512
22513        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22514            // Create a native library symlink only if we have native libraries
22515            // and if the native libraries are 32 bit libraries. We do not provide
22516            // this symlink for 64 bit libraries.
22517            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22518                final String nativeLibPath = app.nativeLibraryDir;
22519                try {
22520                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22521                            nativeLibPath, userId);
22522                } catch (InstallerException e) {
22523                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22524                }
22525            }
22526        }
22527    }
22528
22529    /**
22530     * For system apps on non-FBE devices, this method migrates any existing
22531     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22532     * requested by the app.
22533     */
22534    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22535        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
22536                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22537            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22538                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22539            try {
22540                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22541                        storageTarget);
22542            } catch (InstallerException e) {
22543                logCriticalInfo(Log.WARN,
22544                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22545            }
22546            return true;
22547        } else {
22548            return false;
22549        }
22550    }
22551
22552    public PackageFreezer freezePackage(String packageName, String killReason) {
22553        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22554    }
22555
22556    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22557        return new PackageFreezer(packageName, userId, killReason);
22558    }
22559
22560    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22561            String killReason) {
22562        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22563    }
22564
22565    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22566            String killReason) {
22567        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22568            return new PackageFreezer();
22569        } else {
22570            return freezePackage(packageName, userId, killReason);
22571        }
22572    }
22573
22574    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22575            String killReason) {
22576        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22577    }
22578
22579    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22580            String killReason) {
22581        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22582            return new PackageFreezer();
22583        } else {
22584            return freezePackage(packageName, userId, killReason);
22585        }
22586    }
22587
22588    /**
22589     * Class that freezes and kills the given package upon creation, and
22590     * unfreezes it upon closing. This is typically used when doing surgery on
22591     * app code/data to prevent the app from running while you're working.
22592     */
22593    private class PackageFreezer implements AutoCloseable {
22594        private final String mPackageName;
22595        private final PackageFreezer[] mChildren;
22596
22597        private final boolean mWeFroze;
22598
22599        private final AtomicBoolean mClosed = new AtomicBoolean();
22600        private final CloseGuard mCloseGuard = CloseGuard.get();
22601
22602        /**
22603         * Create and return a stub freezer that doesn't actually do anything,
22604         * typically used when someone requested
22605         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22606         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22607         */
22608        public PackageFreezer() {
22609            mPackageName = null;
22610            mChildren = null;
22611            mWeFroze = false;
22612            mCloseGuard.open("close");
22613        }
22614
22615        public PackageFreezer(String packageName, int userId, String killReason) {
22616            synchronized (mPackages) {
22617                mPackageName = packageName;
22618                mWeFroze = mFrozenPackages.add(mPackageName);
22619
22620                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22621                if (ps != null) {
22622                    killApplication(ps.name, ps.appId, userId, killReason);
22623                }
22624
22625                final PackageParser.Package p = mPackages.get(packageName);
22626                if (p != null && p.childPackages != null) {
22627                    final int N = p.childPackages.size();
22628                    mChildren = new PackageFreezer[N];
22629                    for (int i = 0; i < N; i++) {
22630                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22631                                userId, killReason);
22632                    }
22633                } else {
22634                    mChildren = null;
22635                }
22636            }
22637            mCloseGuard.open("close");
22638        }
22639
22640        @Override
22641        protected void finalize() throws Throwable {
22642            try {
22643                mCloseGuard.warnIfOpen();
22644                close();
22645            } finally {
22646                super.finalize();
22647            }
22648        }
22649
22650        @Override
22651        public void close() {
22652            mCloseGuard.close();
22653            if (mClosed.compareAndSet(false, true)) {
22654                synchronized (mPackages) {
22655                    if (mWeFroze) {
22656                        mFrozenPackages.remove(mPackageName);
22657                    }
22658
22659                    if (mChildren != null) {
22660                        for (PackageFreezer freezer : mChildren) {
22661                            freezer.close();
22662                        }
22663                    }
22664                }
22665            }
22666        }
22667    }
22668
22669    /**
22670     * Verify that given package is currently frozen.
22671     */
22672    private void checkPackageFrozen(String packageName) {
22673        synchronized (mPackages) {
22674            if (!mFrozenPackages.contains(packageName)) {
22675                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22676            }
22677        }
22678    }
22679
22680    @Override
22681    public int movePackage(final String packageName, final String volumeUuid) {
22682        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22683
22684        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
22685        final int moveId = mNextMoveId.getAndIncrement();
22686        mHandler.post(new Runnable() {
22687            @Override
22688            public void run() {
22689                try {
22690                    movePackageInternal(packageName, volumeUuid, moveId, user);
22691                } catch (PackageManagerException e) {
22692                    Slog.w(TAG, "Failed to move " + packageName, e);
22693                    mMoveCallbacks.notifyStatusChanged(moveId,
22694                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22695                }
22696            }
22697        });
22698        return moveId;
22699    }
22700
22701    private void movePackageInternal(final String packageName, final String volumeUuid,
22702            final int moveId, UserHandle user) throws PackageManagerException {
22703        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22704        final PackageManager pm = mContext.getPackageManager();
22705
22706        final boolean currentAsec;
22707        final String currentVolumeUuid;
22708        final File codeFile;
22709        final String installerPackageName;
22710        final String packageAbiOverride;
22711        final int appId;
22712        final String seinfo;
22713        final String label;
22714        final int targetSdkVersion;
22715        final PackageFreezer freezer;
22716        final int[] installedUserIds;
22717
22718        // reader
22719        synchronized (mPackages) {
22720            final PackageParser.Package pkg = mPackages.get(packageName);
22721            final PackageSetting ps = mSettings.mPackages.get(packageName);
22722            if (pkg == null || ps == null) {
22723                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22724            }
22725
22726            if (pkg.applicationInfo.isSystemApp()) {
22727                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22728                        "Cannot move system application");
22729            }
22730
22731            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22732            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22733                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22734            if (isInternalStorage && !allow3rdPartyOnInternal) {
22735                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22736                        "3rd party apps are not allowed on internal storage");
22737            }
22738
22739            if (pkg.applicationInfo.isExternalAsec()) {
22740                currentAsec = true;
22741                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22742            } else if (pkg.applicationInfo.isForwardLocked()) {
22743                currentAsec = true;
22744                currentVolumeUuid = "forward_locked";
22745            } else {
22746                currentAsec = false;
22747                currentVolumeUuid = ps.volumeUuid;
22748
22749                final File probe = new File(pkg.codePath);
22750                final File probeOat = new File(probe, "oat");
22751                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22752                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22753                            "Move only supported for modern cluster style installs");
22754                }
22755            }
22756
22757            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22758                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22759                        "Package already moved to " + volumeUuid);
22760            }
22761            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22762                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22763                        "Device admin cannot be moved");
22764            }
22765
22766            if (mFrozenPackages.contains(packageName)) {
22767                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22768                        "Failed to move already frozen package");
22769            }
22770
22771            codeFile = new File(pkg.codePath);
22772            installerPackageName = ps.installerPackageName;
22773            packageAbiOverride = ps.cpuAbiOverrideString;
22774            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22775            seinfo = pkg.applicationInfo.seInfo;
22776            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22777            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22778            freezer = freezePackage(packageName, "movePackageInternal");
22779            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22780        }
22781
22782        final Bundle extras = new Bundle();
22783        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22784        extras.putString(Intent.EXTRA_TITLE, label);
22785        mMoveCallbacks.notifyCreated(moveId, extras);
22786
22787        int installFlags;
22788        final boolean moveCompleteApp;
22789        final File measurePath;
22790
22791        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22792            installFlags = INSTALL_INTERNAL;
22793            moveCompleteApp = !currentAsec;
22794            measurePath = Environment.getDataAppDirectory(volumeUuid);
22795        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22796            installFlags = INSTALL_EXTERNAL;
22797            moveCompleteApp = false;
22798            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22799        } else {
22800            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22801            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22802                    || !volume.isMountedWritable()) {
22803                freezer.close();
22804                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22805                        "Move location not mounted private volume");
22806            }
22807
22808            Preconditions.checkState(!currentAsec);
22809
22810            installFlags = INSTALL_INTERNAL;
22811            moveCompleteApp = true;
22812            measurePath = Environment.getDataAppDirectory(volumeUuid);
22813        }
22814
22815        final PackageStats stats = new PackageStats(null, -1);
22816        synchronized (mInstaller) {
22817            for (int userId : installedUserIds) {
22818                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22819                    freezer.close();
22820                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22821                            "Failed to measure package size");
22822                }
22823            }
22824        }
22825
22826        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22827                + stats.dataSize);
22828
22829        final long startFreeBytes = measurePath.getUsableSpace();
22830        final long sizeBytes;
22831        if (moveCompleteApp) {
22832            sizeBytes = stats.codeSize + stats.dataSize;
22833        } else {
22834            sizeBytes = stats.codeSize;
22835        }
22836
22837        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22838            freezer.close();
22839            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22840                    "Not enough free space to move");
22841        }
22842
22843        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22844
22845        final CountDownLatch installedLatch = new CountDownLatch(1);
22846        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22847            @Override
22848            public void onUserActionRequired(Intent intent) throws RemoteException {
22849                throw new IllegalStateException();
22850            }
22851
22852            @Override
22853            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22854                    Bundle extras) throws RemoteException {
22855                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22856                        + PackageManager.installStatusToString(returnCode, msg));
22857
22858                installedLatch.countDown();
22859                freezer.close();
22860
22861                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22862                switch (status) {
22863                    case PackageInstaller.STATUS_SUCCESS:
22864                        mMoveCallbacks.notifyStatusChanged(moveId,
22865                                PackageManager.MOVE_SUCCEEDED);
22866                        break;
22867                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22868                        mMoveCallbacks.notifyStatusChanged(moveId,
22869                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22870                        break;
22871                    default:
22872                        mMoveCallbacks.notifyStatusChanged(moveId,
22873                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22874                        break;
22875                }
22876            }
22877        };
22878
22879        final MoveInfo move;
22880        if (moveCompleteApp) {
22881            // Kick off a thread to report progress estimates
22882            new Thread() {
22883                @Override
22884                public void run() {
22885                    while (true) {
22886                        try {
22887                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22888                                break;
22889                            }
22890                        } catch (InterruptedException ignored) {
22891                        }
22892
22893                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22894                        final int progress = 10 + (int) MathUtils.constrain(
22895                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22896                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22897                    }
22898                }
22899            }.start();
22900
22901            final String dataAppName = codeFile.getName();
22902            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22903                    dataAppName, appId, seinfo, targetSdkVersion);
22904        } else {
22905            move = null;
22906        }
22907
22908        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22909
22910        final Message msg = mHandler.obtainMessage(INIT_COPY);
22911        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22912        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22913                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22914                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22915                PackageManager.INSTALL_REASON_UNKNOWN);
22916        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22917        msg.obj = params;
22918
22919        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22920                System.identityHashCode(msg.obj));
22921        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22922                System.identityHashCode(msg.obj));
22923
22924        mHandler.sendMessage(msg);
22925    }
22926
22927    @Override
22928    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22929        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22930
22931        final int realMoveId = mNextMoveId.getAndIncrement();
22932        final Bundle extras = new Bundle();
22933        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22934        mMoveCallbacks.notifyCreated(realMoveId, extras);
22935
22936        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22937            @Override
22938            public void onCreated(int moveId, Bundle extras) {
22939                // Ignored
22940            }
22941
22942            @Override
22943            public void onStatusChanged(int moveId, int status, long estMillis) {
22944                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22945            }
22946        };
22947
22948        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22949        storage.setPrimaryStorageUuid(volumeUuid, callback);
22950        return realMoveId;
22951    }
22952
22953    @Override
22954    public int getMoveStatus(int moveId) {
22955        mContext.enforceCallingOrSelfPermission(
22956                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22957        return mMoveCallbacks.mLastStatus.get(moveId);
22958    }
22959
22960    @Override
22961    public void registerMoveCallback(IPackageMoveObserver callback) {
22962        mContext.enforceCallingOrSelfPermission(
22963                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22964        mMoveCallbacks.register(callback);
22965    }
22966
22967    @Override
22968    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22969        mContext.enforceCallingOrSelfPermission(
22970                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22971        mMoveCallbacks.unregister(callback);
22972    }
22973
22974    @Override
22975    public boolean setInstallLocation(int loc) {
22976        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22977                null);
22978        if (getInstallLocation() == loc) {
22979            return true;
22980        }
22981        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22982                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22983            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22984                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22985            return true;
22986        }
22987        return false;
22988   }
22989
22990    @Override
22991    public int getInstallLocation() {
22992        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22993                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22994                PackageHelper.APP_INSTALL_AUTO);
22995    }
22996
22997    /** Called by UserManagerService */
22998    void cleanUpUser(UserManagerService userManager, int userHandle) {
22999        synchronized (mPackages) {
23000            mDirtyUsers.remove(userHandle);
23001            mUserNeedsBadging.delete(userHandle);
23002            mSettings.removeUserLPw(userHandle);
23003            mPendingBroadcasts.remove(userHandle);
23004            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23005            removeUnusedPackagesLPw(userManager, userHandle);
23006        }
23007    }
23008
23009    /**
23010     * We're removing userHandle and would like to remove any downloaded packages
23011     * that are no longer in use by any other user.
23012     * @param userHandle the user being removed
23013     */
23014    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23015        final boolean DEBUG_CLEAN_APKS = false;
23016        int [] users = userManager.getUserIds();
23017        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23018        while (psit.hasNext()) {
23019            PackageSetting ps = psit.next();
23020            if (ps.pkg == null) {
23021                continue;
23022            }
23023            final String packageName = ps.pkg.packageName;
23024            // Skip over if system app
23025            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23026                continue;
23027            }
23028            if (DEBUG_CLEAN_APKS) {
23029                Slog.i(TAG, "Checking package " + packageName);
23030            }
23031            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23032            if (keep) {
23033                if (DEBUG_CLEAN_APKS) {
23034                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23035                }
23036            } else {
23037                for (int i = 0; i < users.length; i++) {
23038                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23039                        keep = true;
23040                        if (DEBUG_CLEAN_APKS) {
23041                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23042                                    + users[i]);
23043                        }
23044                        break;
23045                    }
23046                }
23047            }
23048            if (!keep) {
23049                if (DEBUG_CLEAN_APKS) {
23050                    Slog.i(TAG, "  Removing package " + packageName);
23051                }
23052                mHandler.post(new Runnable() {
23053                    public void run() {
23054                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23055                                userHandle, 0);
23056                    } //end run
23057                });
23058            }
23059        }
23060    }
23061
23062    /** Called by UserManagerService */
23063    void createNewUser(int userId, String[] disallowedPackages) {
23064        synchronized (mInstallLock) {
23065            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23066        }
23067        synchronized (mPackages) {
23068            scheduleWritePackageRestrictionsLocked(userId);
23069            scheduleWritePackageListLocked(userId);
23070            applyFactoryDefaultBrowserLPw(userId);
23071            primeDomainVerificationsLPw(userId);
23072        }
23073    }
23074
23075    void onNewUserCreated(final int userId) {
23076        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23077        // If permission review for legacy apps is required, we represent
23078        // dagerous permissions for such apps as always granted runtime
23079        // permissions to keep per user flag state whether review is needed.
23080        // Hence, if a new user is added we have to propagate dangerous
23081        // permission grants for these legacy apps.
23082        if (mPermissionReviewRequired) {
23083            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
23084                    | UPDATE_PERMISSIONS_REPLACE_ALL);
23085        }
23086    }
23087
23088    @Override
23089    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23090        mContext.enforceCallingOrSelfPermission(
23091                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23092                "Only package verification agents can read the verifier device identity");
23093
23094        synchronized (mPackages) {
23095            return mSettings.getVerifierDeviceIdentityLPw();
23096        }
23097    }
23098
23099    @Override
23100    public void setPermissionEnforced(String permission, boolean enforced) {
23101        // TODO: Now that we no longer change GID for storage, this should to away.
23102        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23103                "setPermissionEnforced");
23104        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23105            synchronized (mPackages) {
23106                if (mSettings.mReadExternalStorageEnforced == null
23107                        || mSettings.mReadExternalStorageEnforced != enforced) {
23108                    mSettings.mReadExternalStorageEnforced = enforced;
23109                    mSettings.writeLPr();
23110                }
23111            }
23112            // kill any non-foreground processes so we restart them and
23113            // grant/revoke the GID.
23114            final IActivityManager am = ActivityManager.getService();
23115            if (am != null) {
23116                final long token = Binder.clearCallingIdentity();
23117                try {
23118                    am.killProcessesBelowForeground("setPermissionEnforcement");
23119                } catch (RemoteException e) {
23120                } finally {
23121                    Binder.restoreCallingIdentity(token);
23122                }
23123            }
23124        } else {
23125            throw new IllegalArgumentException("No selective enforcement for " + permission);
23126        }
23127    }
23128
23129    @Override
23130    @Deprecated
23131    public boolean isPermissionEnforced(String permission) {
23132        return true;
23133    }
23134
23135    @Override
23136    public boolean isStorageLow() {
23137        final long token = Binder.clearCallingIdentity();
23138        try {
23139            final DeviceStorageMonitorInternal
23140                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23141            if (dsm != null) {
23142                return dsm.isMemoryLow();
23143            } else {
23144                return false;
23145            }
23146        } finally {
23147            Binder.restoreCallingIdentity(token);
23148        }
23149    }
23150
23151    @Override
23152    public IPackageInstaller getPackageInstaller() {
23153        return mInstallerService;
23154    }
23155
23156    private boolean userNeedsBadging(int userId) {
23157        int index = mUserNeedsBadging.indexOfKey(userId);
23158        if (index < 0) {
23159            final UserInfo userInfo;
23160            final long token = Binder.clearCallingIdentity();
23161            try {
23162                userInfo = sUserManager.getUserInfo(userId);
23163            } finally {
23164                Binder.restoreCallingIdentity(token);
23165            }
23166            final boolean b;
23167            if (userInfo != null && userInfo.isManagedProfile()) {
23168                b = true;
23169            } else {
23170                b = false;
23171            }
23172            mUserNeedsBadging.put(userId, b);
23173            return b;
23174        }
23175        return mUserNeedsBadging.valueAt(index);
23176    }
23177
23178    @Override
23179    public KeySet getKeySetByAlias(String packageName, String alias) {
23180        if (packageName == null || alias == null) {
23181            return null;
23182        }
23183        synchronized(mPackages) {
23184            final PackageParser.Package pkg = mPackages.get(packageName);
23185            if (pkg == null) {
23186                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23187                throw new IllegalArgumentException("Unknown package: " + packageName);
23188            }
23189            KeySetManagerService ksms = mSettings.mKeySetManagerService;
23190            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23191        }
23192    }
23193
23194    @Override
23195    public KeySet getSigningKeySet(String packageName) {
23196        if (packageName == null) {
23197            return null;
23198        }
23199        synchronized(mPackages) {
23200            final PackageParser.Package pkg = mPackages.get(packageName);
23201            if (pkg == null) {
23202                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23203                throw new IllegalArgumentException("Unknown package: " + packageName);
23204            }
23205            if (pkg.applicationInfo.uid != Binder.getCallingUid()
23206                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
23207                throw new SecurityException("May not access signing KeySet of other apps.");
23208            }
23209            KeySetManagerService ksms = mSettings.mKeySetManagerService;
23210            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23211        }
23212    }
23213
23214    @Override
23215    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23216        if (packageName == null || ks == null) {
23217            return false;
23218        }
23219        synchronized(mPackages) {
23220            final PackageParser.Package pkg = mPackages.get(packageName);
23221            if (pkg == null) {
23222                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23223                throw new IllegalArgumentException("Unknown package: " + packageName);
23224            }
23225            IBinder ksh = ks.getToken();
23226            if (ksh instanceof KeySetHandle) {
23227                KeySetManagerService ksms = mSettings.mKeySetManagerService;
23228                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23229            }
23230            return false;
23231        }
23232    }
23233
23234    @Override
23235    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23236        if (packageName == null || ks == null) {
23237            return false;
23238        }
23239        synchronized(mPackages) {
23240            final PackageParser.Package pkg = mPackages.get(packageName);
23241            if (pkg == null) {
23242                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23243                throw new IllegalArgumentException("Unknown package: " + packageName);
23244            }
23245            IBinder ksh = ks.getToken();
23246            if (ksh instanceof KeySetHandle) {
23247                KeySetManagerService ksms = mSettings.mKeySetManagerService;
23248                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23249            }
23250            return false;
23251        }
23252    }
23253
23254    private void deletePackageIfUnusedLPr(final String packageName) {
23255        PackageSetting ps = mSettings.mPackages.get(packageName);
23256        if (ps == null) {
23257            return;
23258        }
23259        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23260            // TODO Implement atomic delete if package is unused
23261            // It is currently possible that the package will be deleted even if it is installed
23262            // after this method returns.
23263            mHandler.post(new Runnable() {
23264                public void run() {
23265                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23266                            0, PackageManager.DELETE_ALL_USERS);
23267                }
23268            });
23269        }
23270    }
23271
23272    /**
23273     * Check and throw if the given before/after packages would be considered a
23274     * downgrade.
23275     */
23276    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23277            throws PackageManagerException {
23278        if (after.versionCode < before.mVersionCode) {
23279            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23280                    "Update version code " + after.versionCode + " is older than current "
23281                    + before.mVersionCode);
23282        } else if (after.versionCode == before.mVersionCode) {
23283            if (after.baseRevisionCode < before.baseRevisionCode) {
23284                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23285                        "Update base revision code " + after.baseRevisionCode
23286                        + " is older than current " + before.baseRevisionCode);
23287            }
23288
23289            if (!ArrayUtils.isEmpty(after.splitNames)) {
23290                for (int i = 0; i < after.splitNames.length; i++) {
23291                    final String splitName = after.splitNames[i];
23292                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23293                    if (j != -1) {
23294                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23295                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23296                                    "Update split " + splitName + " revision code "
23297                                    + after.splitRevisionCodes[i] + " is older than current "
23298                                    + before.splitRevisionCodes[j]);
23299                        }
23300                    }
23301                }
23302            }
23303        }
23304    }
23305
23306    private static class MoveCallbacks extends Handler {
23307        private static final int MSG_CREATED = 1;
23308        private static final int MSG_STATUS_CHANGED = 2;
23309
23310        private final RemoteCallbackList<IPackageMoveObserver>
23311                mCallbacks = new RemoteCallbackList<>();
23312
23313        private final SparseIntArray mLastStatus = new SparseIntArray();
23314
23315        public MoveCallbacks(Looper looper) {
23316            super(looper);
23317        }
23318
23319        public void register(IPackageMoveObserver callback) {
23320            mCallbacks.register(callback);
23321        }
23322
23323        public void unregister(IPackageMoveObserver callback) {
23324            mCallbacks.unregister(callback);
23325        }
23326
23327        @Override
23328        public void handleMessage(Message msg) {
23329            final SomeArgs args = (SomeArgs) msg.obj;
23330            final int n = mCallbacks.beginBroadcast();
23331            for (int i = 0; i < n; i++) {
23332                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23333                try {
23334                    invokeCallback(callback, msg.what, args);
23335                } catch (RemoteException ignored) {
23336                }
23337            }
23338            mCallbacks.finishBroadcast();
23339            args.recycle();
23340        }
23341
23342        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23343                throws RemoteException {
23344            switch (what) {
23345                case MSG_CREATED: {
23346                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23347                    break;
23348                }
23349                case MSG_STATUS_CHANGED: {
23350                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23351                    break;
23352                }
23353            }
23354        }
23355
23356        private void notifyCreated(int moveId, Bundle extras) {
23357            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23358
23359            final SomeArgs args = SomeArgs.obtain();
23360            args.argi1 = moveId;
23361            args.arg2 = extras;
23362            obtainMessage(MSG_CREATED, args).sendToTarget();
23363        }
23364
23365        private void notifyStatusChanged(int moveId, int status) {
23366            notifyStatusChanged(moveId, status, -1);
23367        }
23368
23369        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23370            Slog.v(TAG, "Move " + moveId + " status " + status);
23371
23372            final SomeArgs args = SomeArgs.obtain();
23373            args.argi1 = moveId;
23374            args.argi2 = status;
23375            args.arg3 = estMillis;
23376            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23377
23378            synchronized (mLastStatus) {
23379                mLastStatus.put(moveId, status);
23380            }
23381        }
23382    }
23383
23384    private final static class OnPermissionChangeListeners extends Handler {
23385        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23386
23387        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23388                new RemoteCallbackList<>();
23389
23390        public OnPermissionChangeListeners(Looper looper) {
23391            super(looper);
23392        }
23393
23394        @Override
23395        public void handleMessage(Message msg) {
23396            switch (msg.what) {
23397                case MSG_ON_PERMISSIONS_CHANGED: {
23398                    final int uid = msg.arg1;
23399                    handleOnPermissionsChanged(uid);
23400                } break;
23401            }
23402        }
23403
23404        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23405            mPermissionListeners.register(listener);
23406
23407        }
23408
23409        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23410            mPermissionListeners.unregister(listener);
23411        }
23412
23413        public void onPermissionsChanged(int uid) {
23414            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23415                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23416            }
23417        }
23418
23419        private void handleOnPermissionsChanged(int uid) {
23420            final int count = mPermissionListeners.beginBroadcast();
23421            try {
23422                for (int i = 0; i < count; i++) {
23423                    IOnPermissionsChangeListener callback = mPermissionListeners
23424                            .getBroadcastItem(i);
23425                    try {
23426                        callback.onPermissionsChanged(uid);
23427                    } catch (RemoteException e) {
23428                        Log.e(TAG, "Permission listener is dead", e);
23429                    }
23430                }
23431            } finally {
23432                mPermissionListeners.finishBroadcast();
23433            }
23434        }
23435    }
23436
23437    private class PackageManagerInternalImpl extends PackageManagerInternal {
23438        @Override
23439        public void setLocationPackagesProvider(PackagesProvider provider) {
23440            synchronized (mPackages) {
23441                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
23442            }
23443        }
23444
23445        @Override
23446        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23447            synchronized (mPackages) {
23448                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
23449            }
23450        }
23451
23452        @Override
23453        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23454            synchronized (mPackages) {
23455                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
23456            }
23457        }
23458
23459        @Override
23460        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23461            synchronized (mPackages) {
23462                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
23463            }
23464        }
23465
23466        @Override
23467        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23468            synchronized (mPackages) {
23469                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
23470            }
23471        }
23472
23473        @Override
23474        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23475            synchronized (mPackages) {
23476                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
23477            }
23478        }
23479
23480        @Override
23481        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23482            synchronized (mPackages) {
23483                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
23484                        packageName, userId);
23485            }
23486        }
23487
23488        @Override
23489        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23490            synchronized (mPackages) {
23491                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23492                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
23493                        packageName, userId);
23494            }
23495        }
23496
23497        @Override
23498        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23499            synchronized (mPackages) {
23500                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
23501                        packageName, userId);
23502            }
23503        }
23504
23505        @Override
23506        public void setKeepUninstalledPackages(final List<String> packageList) {
23507            Preconditions.checkNotNull(packageList);
23508            List<String> removedFromList = null;
23509            synchronized (mPackages) {
23510                if (mKeepUninstalledPackages != null) {
23511                    final int packagesCount = mKeepUninstalledPackages.size();
23512                    for (int i = 0; i < packagesCount; i++) {
23513                        String oldPackage = mKeepUninstalledPackages.get(i);
23514                        if (packageList != null && packageList.contains(oldPackage)) {
23515                            continue;
23516                        }
23517                        if (removedFromList == null) {
23518                            removedFromList = new ArrayList<>();
23519                        }
23520                        removedFromList.add(oldPackage);
23521                    }
23522                }
23523                mKeepUninstalledPackages = new ArrayList<>(packageList);
23524                if (removedFromList != null) {
23525                    final int removedCount = removedFromList.size();
23526                    for (int i = 0; i < removedCount; i++) {
23527                        deletePackageIfUnusedLPr(removedFromList.get(i));
23528                    }
23529                }
23530            }
23531        }
23532
23533        @Override
23534        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23535            synchronized (mPackages) {
23536                // If we do not support permission review, done.
23537                if (!mPermissionReviewRequired) {
23538                    return false;
23539                }
23540
23541                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
23542                if (packageSetting == null) {
23543                    return false;
23544                }
23545
23546                // Permission review applies only to apps not supporting the new permission model.
23547                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
23548                    return false;
23549                }
23550
23551                // Legacy apps have the permission and get user consent on launch.
23552                PermissionsState permissionsState = packageSetting.getPermissionsState();
23553                return permissionsState.isPermissionReviewRequired(userId);
23554            }
23555        }
23556
23557        @Override
23558        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
23559            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
23560        }
23561
23562        @Override
23563        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23564                int userId) {
23565            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23566        }
23567
23568        @Override
23569        public void setDeviceAndProfileOwnerPackages(
23570                int deviceOwnerUserId, String deviceOwnerPackage,
23571                SparseArray<String> profileOwnerPackages) {
23572            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23573                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23574        }
23575
23576        @Override
23577        public boolean isPackageDataProtected(int userId, String packageName) {
23578            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23579        }
23580
23581        @Override
23582        public boolean isPackageEphemeral(int userId, String packageName) {
23583            synchronized (mPackages) {
23584                final PackageSetting ps = mSettings.mPackages.get(packageName);
23585                return ps != null ? ps.getInstantApp(userId) : false;
23586            }
23587        }
23588
23589        @Override
23590        public boolean wasPackageEverLaunched(String packageName, int userId) {
23591            synchronized (mPackages) {
23592                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23593            }
23594        }
23595
23596        @Override
23597        public void grantRuntimePermission(String packageName, String name, int userId,
23598                boolean overridePolicy) {
23599            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
23600                    overridePolicy);
23601        }
23602
23603        @Override
23604        public void revokeRuntimePermission(String packageName, String name, int userId,
23605                boolean overridePolicy) {
23606            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
23607                    overridePolicy);
23608        }
23609
23610        @Override
23611        public String getNameForUid(int uid) {
23612            return PackageManagerService.this.getNameForUid(uid);
23613        }
23614
23615        @Override
23616        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23617                Intent origIntent, String resolvedType, String callingPackage,
23618                Bundle verificationBundle, int userId) {
23619            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23620                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23621                    userId);
23622        }
23623
23624        @Override
23625        public void grantEphemeralAccess(int userId, Intent intent,
23626                int targetAppId, int ephemeralAppId) {
23627            synchronized (mPackages) {
23628                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23629                        targetAppId, ephemeralAppId);
23630            }
23631        }
23632
23633        @Override
23634        public boolean isInstantAppInstallerComponent(ComponentName component) {
23635            synchronized (mPackages) {
23636                return mInstantAppInstallerActivity != null
23637                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23638            }
23639        }
23640
23641        @Override
23642        public void pruneInstantApps() {
23643            synchronized (mPackages) {
23644                mInstantAppRegistry.pruneInstantAppsLPw();
23645            }
23646        }
23647
23648        @Override
23649        public String getSetupWizardPackageName() {
23650            return mSetupWizardPackage;
23651        }
23652
23653        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23654            if (policy != null) {
23655                mExternalSourcesPolicy = policy;
23656            }
23657        }
23658
23659        @Override
23660        public boolean isPackagePersistent(String packageName) {
23661            synchronized (mPackages) {
23662                PackageParser.Package pkg = mPackages.get(packageName);
23663                return pkg != null
23664                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23665                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23666                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23667                        : false;
23668            }
23669        }
23670
23671        @Override
23672        public List<PackageInfo> getOverlayPackages(int userId) {
23673            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23674            synchronized (mPackages) {
23675                for (PackageParser.Package p : mPackages.values()) {
23676                    if (p.mOverlayTarget != null) {
23677                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23678                        if (pkg != null) {
23679                            overlayPackages.add(pkg);
23680                        }
23681                    }
23682                }
23683            }
23684            return overlayPackages;
23685        }
23686
23687        @Override
23688        public List<String> getTargetPackageNames(int userId) {
23689            List<String> targetPackages = new ArrayList<>();
23690            synchronized (mPackages) {
23691                for (PackageParser.Package p : mPackages.values()) {
23692                    if (p.mOverlayTarget == null) {
23693                        targetPackages.add(p.packageName);
23694                    }
23695                }
23696            }
23697            return targetPackages;
23698        }
23699
23700        @Override
23701        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23702                @Nullable List<String> overlayPackageNames) {
23703            synchronized (mPackages) {
23704                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23705                    Slog.e(TAG, "failed to find package " + targetPackageName);
23706                    return false;
23707                }
23708
23709                ArrayList<String> paths = null;
23710                if (overlayPackageNames != null) {
23711                    final int N = overlayPackageNames.size();
23712                    paths = new ArrayList<>(N);
23713                    for (int i = 0; i < N; i++) {
23714                        final String packageName = overlayPackageNames.get(i);
23715                        final PackageParser.Package pkg = mPackages.get(packageName);
23716                        if (pkg == null) {
23717                            Slog.e(TAG, "failed to find package " + packageName);
23718                            return false;
23719                        }
23720                        paths.add(pkg.baseCodePath);
23721                    }
23722                }
23723
23724                ArrayMap<String, ArrayList<String>> userSpecificOverlays =
23725                    mEnabledOverlayPaths.get(userId);
23726                if (userSpecificOverlays == null) {
23727                    userSpecificOverlays = new ArrayMap<>();
23728                    mEnabledOverlayPaths.put(userId, userSpecificOverlays);
23729                }
23730
23731                if (paths != null && paths.size() > 0) {
23732                    userSpecificOverlays.put(targetPackageName, paths);
23733                } else {
23734                    userSpecificOverlays.remove(targetPackageName);
23735                }
23736                return true;
23737            }
23738        }
23739
23740        @Override
23741        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23742                int flags, int userId) {
23743            return resolveIntentInternal(
23744                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
23745        }
23746
23747        @Override
23748        public ResolveInfo resolveService(Intent intent, String resolvedType,
23749                int flags, int userId, int callingUid) {
23750            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23751        }
23752
23753        @Override
23754        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23755            synchronized (mPackages) {
23756                mIsolatedOwners.put(isolatedUid, ownerUid);
23757            }
23758        }
23759
23760        @Override
23761        public void removeIsolatedUid(int isolatedUid) {
23762            synchronized (mPackages) {
23763                mIsolatedOwners.delete(isolatedUid);
23764            }
23765        }
23766
23767        @Override
23768        public int getUidTargetSdkVersion(int uid) {
23769            synchronized (mPackages) {
23770                return getUidTargetSdkVersionLockedLPr(uid);
23771            }
23772        }
23773    }
23774
23775    @Override
23776    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23777        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23778        synchronized (mPackages) {
23779            final long identity = Binder.clearCallingIdentity();
23780            try {
23781                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
23782                        packageNames, userId);
23783            } finally {
23784                Binder.restoreCallingIdentity(identity);
23785            }
23786        }
23787    }
23788
23789    @Override
23790    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23791        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23792        synchronized (mPackages) {
23793            final long identity = Binder.clearCallingIdentity();
23794            try {
23795                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
23796                        packageNames, userId);
23797            } finally {
23798                Binder.restoreCallingIdentity(identity);
23799            }
23800        }
23801    }
23802
23803    private static void enforceSystemOrPhoneCaller(String tag) {
23804        int callingUid = Binder.getCallingUid();
23805        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23806            throw new SecurityException(
23807                    "Cannot call " + tag + " from UID " + callingUid);
23808        }
23809    }
23810
23811    boolean isHistoricalPackageUsageAvailable() {
23812        return mPackageUsage.isHistoricalPackageUsageAvailable();
23813    }
23814
23815    /**
23816     * Return a <b>copy</b> of the collection of packages known to the package manager.
23817     * @return A copy of the values of mPackages.
23818     */
23819    Collection<PackageParser.Package> getPackages() {
23820        synchronized (mPackages) {
23821            return new ArrayList<>(mPackages.values());
23822        }
23823    }
23824
23825    /**
23826     * Logs process start information (including base APK hash) to the security log.
23827     * @hide
23828     */
23829    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23830            String apkFile, int pid) {
23831        if (!SecurityLog.isLoggingEnabled()) {
23832            return;
23833        }
23834        Bundle data = new Bundle();
23835        data.putLong("startTimestamp", System.currentTimeMillis());
23836        data.putString("processName", processName);
23837        data.putInt("uid", uid);
23838        data.putString("seinfo", seinfo);
23839        data.putString("apkFile", apkFile);
23840        data.putInt("pid", pid);
23841        Message msg = mProcessLoggingHandler.obtainMessage(
23842                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23843        msg.setData(data);
23844        mProcessLoggingHandler.sendMessage(msg);
23845    }
23846
23847    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23848        return mCompilerStats.getPackageStats(pkgName);
23849    }
23850
23851    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23852        return getOrCreateCompilerPackageStats(pkg.packageName);
23853    }
23854
23855    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23856        return mCompilerStats.getOrCreatePackageStats(pkgName);
23857    }
23858
23859    public void deleteCompilerPackageStats(String pkgName) {
23860        mCompilerStats.deletePackageStats(pkgName);
23861    }
23862
23863    @Override
23864    public int getInstallReason(String packageName, int userId) {
23865        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23866                true /* requireFullPermission */, false /* checkShell */,
23867                "get install reason");
23868        synchronized (mPackages) {
23869            final PackageSetting ps = mSettings.mPackages.get(packageName);
23870            if (ps != null) {
23871                return ps.getInstallReason(userId);
23872            }
23873        }
23874        return PackageManager.INSTALL_REASON_UNKNOWN;
23875    }
23876
23877    @Override
23878    public boolean canRequestPackageInstalls(String packageName, int userId) {
23879        int callingUid = Binder.getCallingUid();
23880        int uid = getPackageUid(packageName, 0, userId);
23881        if (callingUid != uid && callingUid != Process.ROOT_UID
23882                && callingUid != Process.SYSTEM_UID) {
23883            throw new SecurityException(
23884                    "Caller uid " + callingUid + " does not own package " + packageName);
23885        }
23886        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
23887        if (info == null) {
23888            return false;
23889        }
23890        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23891            throw new UnsupportedOperationException(
23892                    "Operation only supported on apps targeting Android O or higher");
23893        }
23894        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23895        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23896        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23897            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
23898        }
23899        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23900            return false;
23901        }
23902        if (mExternalSourcesPolicy != null) {
23903            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23904            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23905                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23906            }
23907        }
23908        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23909    }
23910
23911    @Override
23912    public ComponentName getInstantAppResolverSettingsComponent() {
23913        return mInstantAppResolverSettingsComponent;
23914    }
23915
23916    @Override
23917    public ComponentName getInstantAppInstallerComponent() {
23918        return mInstantAppInstallerActivity == null
23919                ? null : mInstantAppInstallerActivity.getComponentName();
23920    }
23921
23922    @Override
23923    public String getInstantAppAndroidId(String packageName, int userId) {
23924        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
23925                "getInstantAppAndroidId");
23926        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23927                true /* requireFullPermission */, false /* checkShell */,
23928                "getInstantAppAndroidId");
23929        // Make sure the target is an Instant App.
23930        if (!isInstantApp(packageName, userId)) {
23931            return null;
23932        }
23933        synchronized (mPackages) {
23934            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
23935        }
23936    }
23937}
23938
23939interface PackageSender {
23940    void sendPackageBroadcast(final String action, final String pkg,
23941        final Bundle extras, final int flags, final String targetPkg,
23942        final IIntentReceiver finishedReceiver, final int[] userIds);
23943    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
23944        int appId, int... userIds);
23945}
23946