PackageManagerService.java revision a5d70a17ebd1b3ffe026879c5d9d96f04d10d4f2
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.Installer.DEXOPT_PUBLIC;
94import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
95import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
97import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
98import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
99import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
105
106import android.Manifest;
107import android.annotation.NonNull;
108import android.annotation.Nullable;
109import android.app.ActivityManager;
110import android.app.AppOpsManager;
111import android.app.IActivityManager;
112import android.app.ResourcesManager;
113import android.app.admin.IDevicePolicyManager;
114import android.app.admin.SecurityLog;
115import android.app.backup.IBackupManager;
116import android.content.BroadcastReceiver;
117import android.content.ComponentName;
118import android.content.ContentResolver;
119import android.content.Context;
120import android.content.IIntentReceiver;
121import android.content.Intent;
122import android.content.IntentFilter;
123import android.content.IntentSender;
124import android.content.IntentSender.SendIntentException;
125import android.content.ServiceConnection;
126import android.content.pm.ActivityInfo;
127import android.content.pm.ApplicationInfo;
128import android.content.pm.AppsQueryHelper;
129import android.content.pm.ChangedPackages;
130import android.content.pm.ComponentInfo;
131import android.content.pm.InstantAppRequest;
132import android.content.pm.AuxiliaryResolveInfo;
133import android.content.pm.FallbackCategoryProvider;
134import android.content.pm.FeatureInfo;
135import android.content.pm.IOnPermissionsChangeListener;
136import android.content.pm.IPackageDataObserver;
137import android.content.pm.IPackageDeleteObserver;
138import android.content.pm.IPackageDeleteObserver2;
139import android.content.pm.IPackageInstallObserver2;
140import android.content.pm.IPackageInstaller;
141import android.content.pm.IPackageManager;
142import android.content.pm.IPackageMoveObserver;
143import android.content.pm.IPackageStatsObserver;
144import android.content.pm.InstantAppInfo;
145import android.content.pm.InstantAppResolveInfo;
146import android.content.pm.InstrumentationInfo;
147import android.content.pm.IntentFilterVerificationInfo;
148import android.content.pm.KeySet;
149import android.content.pm.PackageCleanItem;
150import android.content.pm.PackageInfo;
151import android.content.pm.PackageInfoLite;
152import android.content.pm.PackageInstaller;
153import android.content.pm.PackageManager;
154import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
155import android.content.pm.PackageManagerInternal;
156import android.content.pm.PackageParser;
157import android.content.pm.PackageParser.ActivityIntentInfo;
158import android.content.pm.PackageParser.PackageLite;
159import android.content.pm.PackageParser.PackageParserException;
160import android.content.pm.PackageStats;
161import android.content.pm.PackageUserState;
162import android.content.pm.ParceledListSlice;
163import android.content.pm.PermissionGroupInfo;
164import android.content.pm.PermissionInfo;
165import android.content.pm.ProviderInfo;
166import android.content.pm.ResolveInfo;
167import android.content.pm.SELinuxUtil;
168import android.content.pm.ServiceInfo;
169import android.content.pm.SharedLibraryInfo;
170import android.content.pm.Signature;
171import android.content.pm.UserInfo;
172import android.content.pm.VerifierDeviceIdentity;
173import android.content.pm.VerifierInfo;
174import android.content.pm.VersionedPackage;
175import android.content.res.Resources;
176import android.graphics.Bitmap;
177import android.hardware.display.DisplayManager;
178import android.net.Uri;
179import android.os.Binder;
180import android.os.Build;
181import android.os.Bundle;
182import android.os.Debug;
183import android.os.Environment;
184import android.os.Environment.UserEnvironment;
185import android.os.FileUtils;
186import android.os.Handler;
187import android.os.IBinder;
188import android.os.Looper;
189import android.os.Message;
190import android.os.Parcel;
191import android.os.ParcelFileDescriptor;
192import android.os.PatternMatcher;
193import android.os.Process;
194import android.os.RemoteCallbackList;
195import android.os.RemoteException;
196import android.os.ResultReceiver;
197import android.os.SELinux;
198import android.os.ServiceManager;
199import android.os.ShellCallback;
200import android.os.SystemClock;
201import android.os.SystemProperties;
202import android.os.Trace;
203import android.os.UserHandle;
204import android.os.UserManager;
205import android.os.UserManagerInternal;
206import android.os.storage.IStorageManager;
207import android.os.storage.StorageEventListener;
208import android.os.storage.StorageManager;
209import android.os.storage.StorageManagerInternal;
210import android.os.storage.VolumeInfo;
211import android.os.storage.VolumeRecord;
212import android.provider.Settings.Global;
213import android.provider.Settings.Secure;
214import android.security.KeyStore;
215import android.security.SystemKeyStore;
216import android.service.pm.PackageServiceDumpProto;
217import android.system.ErrnoException;
218import android.system.Os;
219import android.text.TextUtils;
220import android.text.format.DateUtils;
221import android.util.ArrayMap;
222import android.util.ArraySet;
223import android.util.Base64;
224import android.util.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.BackgroundDexOptService;
276import com.android.server.pm.Installer.InstallerException;
277import com.android.server.pm.PermissionsState.PermissionState;
278import com.android.server.pm.Settings.DatabaseVersion;
279import com.android.server.pm.Settings.VersionInfo;
280import com.android.server.pm.dex.DexManager;
281import com.android.server.storage.DeviceStorageMonitorInternal;
282
283import dalvik.system.CloseGuard;
284import dalvik.system.DexFile;
285import dalvik.system.VMRuntime;
286
287import libcore.io.IoUtils;
288import libcore.util.EmptyArray;
289
290import org.xmlpull.v1.XmlPullParser;
291import org.xmlpull.v1.XmlPullParserException;
292import org.xmlpull.v1.XmlSerializer;
293
294import java.io.BufferedOutputStream;
295import java.io.BufferedReader;
296import java.io.ByteArrayInputStream;
297import java.io.ByteArrayOutputStream;
298import java.io.File;
299import java.io.FileDescriptor;
300import java.io.FileInputStream;
301import java.io.FileNotFoundException;
302import java.io.FileOutputStream;
303import java.io.FileReader;
304import java.io.FilenameFilter;
305import java.io.IOException;
306import java.io.PrintWriter;
307import java.nio.charset.StandardCharsets;
308import java.security.DigestInputStream;
309import java.security.MessageDigest;
310import java.security.NoSuchAlgorithmException;
311import java.security.PublicKey;
312import java.security.SecureRandom;
313import java.security.cert.Certificate;
314import java.security.cert.CertificateEncodingException;
315import java.security.cert.CertificateException;
316import java.text.SimpleDateFormat;
317import java.util.ArrayList;
318import java.util.Arrays;
319import java.util.Collection;
320import java.util.Collections;
321import java.util.Comparator;
322import java.util.Date;
323import java.util.HashMap;
324import java.util.HashSet;
325import java.util.Iterator;
326import java.util.List;
327import java.util.Map;
328import java.util.Objects;
329import java.util.Set;
330import java.util.concurrent.CountDownLatch;
331import java.util.concurrent.Future;
332import java.util.concurrent.TimeUnit;
333import java.util.concurrent.atomic.AtomicBoolean;
334import java.util.concurrent.atomic.AtomicInteger;
335
336/**
337 * Keep track of all those APKs everywhere.
338 * <p>
339 * Internally there are two important locks:
340 * <ul>
341 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
342 * and other related state. It is a fine-grained lock that should only be held
343 * momentarily, as it's one of the most contended locks in the system.
344 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
345 * operations typically involve heavy lifting of application data on disk. Since
346 * {@code installd} is single-threaded, and it's operations can often be slow,
347 * this lock should never be acquired while already holding {@link #mPackages}.
348 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
349 * holding {@link #mInstallLock}.
350 * </ul>
351 * Many internal methods rely on the caller to hold the appropriate locks, and
352 * this contract is expressed through method name suffixes:
353 * <ul>
354 * <li>fooLI(): the caller must hold {@link #mInstallLock}
355 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
356 * being modified must be frozen
357 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
358 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
359 * </ul>
360 * <p>
361 * Because this class is very central to the platform's security; please run all
362 * CTS and unit tests whenever making modifications:
363 *
364 * <pre>
365 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
366 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
367 * </pre>
368 */
369public class PackageManagerService extends IPackageManager.Stub {
370    static final String TAG = "PackageManager";
371    static final boolean DEBUG_SETTINGS = false;
372    static final boolean DEBUG_PREFERRED = false;
373    static final boolean DEBUG_UPGRADE = false;
374    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
375    private static final boolean DEBUG_BACKUP = false;
376    private static final boolean DEBUG_INSTALL = false;
377    private static final boolean DEBUG_REMOVE = false;
378    private static final boolean DEBUG_BROADCASTS = false;
379    private static final boolean DEBUG_SHOW_INFO = false;
380    private static final boolean DEBUG_PACKAGE_INFO = false;
381    private static final boolean DEBUG_INTENT_MATCHING = false;
382    private static final boolean DEBUG_PACKAGE_SCANNING = false;
383    private static final boolean DEBUG_VERIFY = false;
384    private static final boolean DEBUG_FILTERS = false;
385
386    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
387    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
388    // user, but by default initialize to this.
389    public static final boolean DEBUG_DEXOPT = false;
390
391    private static final boolean DEBUG_ABI_SELECTION = false;
392    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
393    private static final boolean DEBUG_TRIAGED_MISSING = false;
394    private static final boolean DEBUG_APP_DATA = false;
395
396    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
397    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
398
399    private static final boolean DISABLE_EPHEMERAL_APPS = false;
400    private static final boolean HIDE_EPHEMERAL_APIS = false;
401
402    private static final boolean ENABLE_FREE_CACHE_V2 =
403            SystemProperties.getBoolean("fw.free_cache_v2", true);
404
405    private static final int RADIO_UID = Process.PHONE_UID;
406    private static final int LOG_UID = Process.LOG_UID;
407    private static final int NFC_UID = Process.NFC_UID;
408    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
409    private static final int SHELL_UID = Process.SHELL_UID;
410
411    // Cap the size of permission trees that 3rd party apps can define
412    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
413
414    // Suffix used during package installation when copying/moving
415    // package apks to install directory.
416    private static final String INSTALL_PACKAGE_SUFFIX = "-";
417
418    static final int SCAN_NO_DEX = 1<<1;
419    static final int SCAN_FORCE_DEX = 1<<2;
420    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
421    static final int SCAN_NEW_INSTALL = 1<<4;
422    static final int SCAN_UPDATE_TIME = 1<<5;
423    static final int SCAN_BOOTING = 1<<6;
424    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
425    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
426    static final int SCAN_REPLACING = 1<<9;
427    static final int SCAN_REQUIRE_KNOWN = 1<<10;
428    static final int SCAN_MOVE = 1<<11;
429    static final int SCAN_INITIAL = 1<<12;
430    static final int SCAN_CHECK_ONLY = 1<<13;
431    static final int SCAN_DONT_KILL_APP = 1<<14;
432    static final int SCAN_IGNORE_FROZEN = 1<<15;
433    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
434    static final int SCAN_AS_INSTANT_APP = 1<<17;
435    static final int SCAN_AS_FULL_APP = 1<<18;
436    /** Should not be with the scan flags */
437    static final int FLAGS_REMOVE_CHATTY = 1<<31;
438
439    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
440
441    private static final int[] EMPTY_INT_ARRAY = new int[0];
442
443    /**
444     * Timeout (in milliseconds) after which the watchdog should declare that
445     * our handler thread is wedged.  The usual default for such things is one
446     * minute but we sometimes do very lengthy I/O operations on this thread,
447     * such as installing multi-gigabyte applications, so ours needs to be longer.
448     */
449    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
450
451    /**
452     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
453     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
454     * settings entry if available, otherwise we use the hardcoded default.  If it's been
455     * more than this long since the last fstrim, we force one during the boot sequence.
456     *
457     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
458     * one gets run at the next available charging+idle time.  This final mandatory
459     * no-fstrim check kicks in only of the other scheduling criteria is never met.
460     */
461    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
462
463    /**
464     * Whether verification is enabled by default.
465     */
466    private static final boolean DEFAULT_VERIFY_ENABLE = true;
467
468    /**
469     * The default maximum time to wait for the verification agent to return in
470     * milliseconds.
471     */
472    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
473
474    /**
475     * The default response for package verification timeout.
476     *
477     * This can be either PackageManager.VERIFICATION_ALLOW or
478     * PackageManager.VERIFICATION_REJECT.
479     */
480    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
481
482    static final String PLATFORM_PACKAGE_NAME = "android";
483
484    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
485
486    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
487            DEFAULT_CONTAINER_PACKAGE,
488            "com.android.defcontainer.DefaultContainerService");
489
490    private static final String KILL_APP_REASON_GIDS_CHANGED =
491            "permission grant or revoke changed gids";
492
493    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
494            "permissions revoked";
495
496    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
497
498    private static final String PACKAGE_SCHEME = "package";
499
500    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
501
502    /** Permission grant: not grant the permission. */
503    private static final int GRANT_DENIED = 1;
504
505    /** Permission grant: grant the permission as an install permission. */
506    private static final int GRANT_INSTALL = 2;
507
508    /** Permission grant: grant the permission as a runtime one. */
509    private static final int GRANT_RUNTIME = 3;
510
511    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
512    private static final int GRANT_UPGRADE = 4;
513
514    /** Canonical intent used to identify what counts as a "web browser" app */
515    private static final Intent sBrowserIntent;
516    static {
517        sBrowserIntent = new Intent();
518        sBrowserIntent.setAction(Intent.ACTION_VIEW);
519        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
520        sBrowserIntent.setData(Uri.parse("http:"));
521    }
522
523    /**
524     * The set of all protected actions [i.e. those actions for which a high priority
525     * intent filter is disallowed].
526     */
527    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
528    static {
529        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
530        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
531        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
532        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
533    }
534
535    // Compilation reasons.
536    public static final int REASON_FIRST_BOOT = 0;
537    public static final int REASON_BOOT = 1;
538    public static final int REASON_INSTALL = 2;
539    public static final int REASON_BACKGROUND_DEXOPT = 3;
540    public static final int REASON_AB_OTA = 4;
541    public static final int REASON_FORCED_DEXOPT = 5;
542
543    public static final int REASON_LAST = REASON_FORCED_DEXOPT;
544
545    /** All dangerous permission names in the same order as the events in MetricsEvent */
546    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
547            Manifest.permission.READ_CALENDAR,
548            Manifest.permission.WRITE_CALENDAR,
549            Manifest.permission.CAMERA,
550            Manifest.permission.READ_CONTACTS,
551            Manifest.permission.WRITE_CONTACTS,
552            Manifest.permission.GET_ACCOUNTS,
553            Manifest.permission.ACCESS_FINE_LOCATION,
554            Manifest.permission.ACCESS_COARSE_LOCATION,
555            Manifest.permission.RECORD_AUDIO,
556            Manifest.permission.READ_PHONE_STATE,
557            Manifest.permission.CALL_PHONE,
558            Manifest.permission.READ_CALL_LOG,
559            Manifest.permission.WRITE_CALL_LOG,
560            Manifest.permission.ADD_VOICEMAIL,
561            Manifest.permission.USE_SIP,
562            Manifest.permission.PROCESS_OUTGOING_CALLS,
563            Manifest.permission.READ_CELL_BROADCASTS,
564            Manifest.permission.BODY_SENSORS,
565            Manifest.permission.SEND_SMS,
566            Manifest.permission.RECEIVE_SMS,
567            Manifest.permission.READ_SMS,
568            Manifest.permission.RECEIVE_WAP_PUSH,
569            Manifest.permission.RECEIVE_MMS,
570            Manifest.permission.READ_EXTERNAL_STORAGE,
571            Manifest.permission.WRITE_EXTERNAL_STORAGE,
572            Manifest.permission.READ_PHONE_NUMBERS,
573            Manifest.permission.ANSWER_PHONE_CALLS);
574
575
576    /**
577     * Version number for the package parser cache. Increment this whenever the format or
578     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
579     */
580    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
581
582    /**
583     * Whether the package parser cache is enabled.
584     */
585    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
586
587    final ServiceThread mHandlerThread;
588
589    final PackageHandler mHandler;
590
591    private final ProcessLoggingHandler mProcessLoggingHandler;
592
593    /**
594     * Messages for {@link #mHandler} that need to wait for system ready before
595     * being dispatched.
596     */
597    private ArrayList<Message> mPostSystemReadyMessages;
598
599    final int mSdkVersion = Build.VERSION.SDK_INT;
600
601    final Context mContext;
602    final boolean mFactoryTest;
603    final boolean mOnlyCore;
604    final DisplayMetrics mMetrics;
605    final int mDefParseFlags;
606    final String[] mSeparateProcesses;
607    final boolean mIsUpgrade;
608    final boolean mIsPreNUpgrade;
609    final boolean mIsPreNMR1Upgrade;
610
611    @GuardedBy("mPackages")
612    private boolean mDexOptDialogShown;
613
614    /** The location for ASEC container files on internal storage. */
615    final String mAsecInternalPath;
616
617    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
618    // LOCK HELD.  Can be called with mInstallLock held.
619    @GuardedBy("mInstallLock")
620    final Installer mInstaller;
621
622    /** Directory where installed third-party apps stored */
623    final File mAppInstallDir;
624
625    /**
626     * Directory to which applications installed internally have their
627     * 32 bit native libraries copied.
628     */
629    private File mAppLib32InstallDir;
630
631    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
632    // apps.
633    final File mDrmAppPrivateInstallDir;
634
635    // ----------------------------------------------------------------
636
637    // Lock for state used when installing and doing other long running
638    // operations.  Methods that must be called with this lock held have
639    // the suffix "LI".
640    final Object mInstallLock = new Object();
641
642    // ----------------------------------------------------------------
643
644    // Keys are String (package name), values are Package.  This also serves
645    // as the lock for the global state.  Methods that must be called with
646    // this lock held have the prefix "LP".
647    @GuardedBy("mPackages")
648    final ArrayMap<String, PackageParser.Package> mPackages =
649            new ArrayMap<String, PackageParser.Package>();
650
651    final ArrayMap<String, Set<String>> mKnownCodebase =
652            new ArrayMap<String, Set<String>>();
653
654    // Keys are isolated uids and values are the uid of the application
655    // that created the isolated proccess.
656    @GuardedBy("mPackages")
657    final SparseIntArray mIsolatedOwners = new SparseIntArray();
658
659    // List of APK paths to load for each user and package. This data is never
660    // persisted by the package manager. Instead, the overlay manager will
661    // ensure the data is up-to-date in runtime.
662    @GuardedBy("mPackages")
663    final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths =
664        new SparseArray<ArrayMap<String, ArrayList<String>>>();
665
666    /**
667     * Tracks new system packages [received in an OTA] that we expect to
668     * find updated user-installed versions. Keys are package name, values
669     * are package location.
670     */
671    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
672    /**
673     * Tracks high priority intent filters for protected actions. During boot, certain
674     * filter actions are protected and should never be allowed to have a high priority
675     * intent filter for them. However, there is one, and only one exception -- the
676     * setup wizard. It must be able to define a high priority intent filter for these
677     * actions to ensure there are no escapes from the wizard. We need to delay processing
678     * of these during boot as we need to look at all of the system packages in order
679     * to know which component is the setup wizard.
680     */
681    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
682    /**
683     * Whether or not processing protected filters should be deferred.
684     */
685    private boolean mDeferProtectedFilters = true;
686
687    /**
688     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
689     */
690    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
691    /**
692     * Whether or not system app permissions should be promoted from install to runtime.
693     */
694    boolean mPromoteSystemApps;
695
696    @GuardedBy("mPackages")
697    final Settings mSettings;
698
699    /**
700     * Set of package names that are currently "frozen", which means active
701     * surgery is being done on the code/data for that package. The platform
702     * will refuse to launch frozen packages to avoid race conditions.
703     *
704     * @see PackageFreezer
705     */
706    @GuardedBy("mPackages")
707    final ArraySet<String> mFrozenPackages = new ArraySet<>();
708
709    final ProtectedPackages mProtectedPackages;
710
711    boolean mFirstBoot;
712
713    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
714
715    // System configuration read by SystemConfig.
716    final int[] mGlobalGids;
717    final SparseArray<ArraySet<String>> mSystemPermissions;
718    @GuardedBy("mAvailableFeatures")
719    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
720
721    // If mac_permissions.xml was found for seinfo labeling.
722    boolean mFoundPolicyFile;
723
724    private final InstantAppRegistry mInstantAppRegistry;
725
726    @GuardedBy("mPackages")
727    int mChangedPackagesSequenceNumber;
728    /**
729     * List of changed [installed, removed or updated] packages.
730     * mapping from user id -> sequence number -> package name
731     */
732    @GuardedBy("mPackages")
733    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
734    /**
735     * The sequence number of the last change to a package.
736     * mapping from user id -> package name -> sequence number
737     */
738    @GuardedBy("mPackages")
739    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
740
741    final PackageParser.Callback mPackageParserCallback = new PackageParser.Callback() {
742        @Override public boolean hasFeature(String feature) {
743            return PackageManagerService.this.hasSystemFeature(feature, 0);
744        }
745    };
746
747    public static final class SharedLibraryEntry {
748        public final String path;
749        public final String apk;
750        public final SharedLibraryInfo info;
751
752        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
753                String declaringPackageName, int declaringPackageVersionCode) {
754            path = _path;
755            apk = _apk;
756            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
757                    declaringPackageName, declaringPackageVersionCode), null);
758        }
759    }
760
761    // Currently known shared libraries.
762    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
763    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
764            new ArrayMap<>();
765
766    // All available activities, for your resolving pleasure.
767    final ActivityIntentResolver mActivities =
768            new ActivityIntentResolver();
769
770    // All available receivers, for your resolving pleasure.
771    final ActivityIntentResolver mReceivers =
772            new ActivityIntentResolver();
773
774    // All available services, for your resolving pleasure.
775    final ServiceIntentResolver mServices = new ServiceIntentResolver();
776
777    // All available providers, for your resolving pleasure.
778    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
779
780    // Mapping from provider base names (first directory in content URI codePath)
781    // to the provider information.
782    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
783            new ArrayMap<String, PackageParser.Provider>();
784
785    // Mapping from instrumentation class names to info about them.
786    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
787            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
788
789    // Mapping from permission names to info about them.
790    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
791            new ArrayMap<String, PackageParser.PermissionGroup>();
792
793    // Packages whose data we have transfered into another package, thus
794    // should no longer exist.
795    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
796
797    // Broadcast actions that are only available to the system.
798    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
799
800    /** List of packages waiting for verification. */
801    final SparseArray<PackageVerificationState> mPendingVerification
802            = new SparseArray<PackageVerificationState>();
803
804    /** Set of packages associated with each app op permission. */
805    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
806
807    final PackageInstallerService mInstallerService;
808
809    private final PackageDexOptimizer mPackageDexOptimizer;
810    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
811    // is used by other apps).
812    private final DexManager mDexManager;
813
814    private AtomicInteger mNextMoveId = new AtomicInteger();
815    private final MoveCallbacks mMoveCallbacks;
816
817    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
818
819    // Cache of users who need badging.
820    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
821
822    /** Token for keys in mPendingVerification. */
823    private int mPendingVerificationToken = 0;
824
825    volatile boolean mSystemReady;
826    volatile boolean mSafeMode;
827    volatile boolean mHasSystemUidErrors;
828
829    ApplicationInfo mAndroidApplication;
830    final ActivityInfo mResolveActivity = new ActivityInfo();
831    final ResolveInfo mResolveInfo = new ResolveInfo();
832    ComponentName mResolveComponentName;
833    PackageParser.Package mPlatformPackage;
834    ComponentName mCustomResolverComponentName;
835
836    boolean mResolverReplaced = false;
837
838    private final @Nullable ComponentName mIntentFilterVerifierComponent;
839    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
840
841    private int mIntentFilterVerificationToken = 0;
842
843    /** The service connection to the ephemeral resolver */
844    final EphemeralResolverConnection mInstantAppResolverConnection;
845
846    /** Component used to install ephemeral applications */
847    ComponentName mInstantAppInstallerComponent;
848    /** Component used to show resolver settings for Instant Apps */
849    ComponentName mInstantAppResolverSettingsComponent;
850    ActivityInfo mInstantAppInstallerActivity;
851    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
852
853    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
854            = new SparseArray<IntentFilterVerificationState>();
855
856    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
857
858    // List of packages names to keep cached, even if they are uninstalled for all users
859    private List<String> mKeepUninstalledPackages;
860
861    private UserManagerInternal mUserManagerInternal;
862
863    private DeviceIdleController.LocalService mDeviceIdleController;
864
865    private File mCacheDir;
866
867    private ArraySet<String> mPrivappPermissionsViolations;
868
869    private Future<?> mPrepareAppDataFuture;
870
871    private static class IFVerificationParams {
872        PackageParser.Package pkg;
873        boolean replacing;
874        int userId;
875        int verifierUid;
876
877        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
878                int _userId, int _verifierUid) {
879            pkg = _pkg;
880            replacing = _replacing;
881            userId = _userId;
882            replacing = _replacing;
883            verifierUid = _verifierUid;
884        }
885    }
886
887    private interface IntentFilterVerifier<T extends IntentFilter> {
888        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
889                                               T filter, String packageName);
890        void startVerifications(int userId);
891        void receiveVerificationResponse(int verificationId);
892    }
893
894    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
895        private Context mContext;
896        private ComponentName mIntentFilterVerifierComponent;
897        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
898
899        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
900            mContext = context;
901            mIntentFilterVerifierComponent = verifierComponent;
902        }
903
904        private String getDefaultScheme() {
905            return IntentFilter.SCHEME_HTTPS;
906        }
907
908        @Override
909        public void startVerifications(int userId) {
910            // Launch verifications requests
911            int count = mCurrentIntentFilterVerifications.size();
912            for (int n=0; n<count; n++) {
913                int verificationId = mCurrentIntentFilterVerifications.get(n);
914                final IntentFilterVerificationState ivs =
915                        mIntentFilterVerificationStates.get(verificationId);
916
917                String packageName = ivs.getPackageName();
918
919                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
920                final int filterCount = filters.size();
921                ArraySet<String> domainsSet = new ArraySet<>();
922                for (int m=0; m<filterCount; m++) {
923                    PackageParser.ActivityIntentInfo filter = filters.get(m);
924                    domainsSet.addAll(filter.getHostsList());
925                }
926                synchronized (mPackages) {
927                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
928                            packageName, domainsSet) != null) {
929                        scheduleWriteSettingsLocked();
930                    }
931                }
932                sendVerificationRequest(userId, verificationId, ivs);
933            }
934            mCurrentIntentFilterVerifications.clear();
935        }
936
937        private void sendVerificationRequest(int userId, int verificationId,
938                IntentFilterVerificationState ivs) {
939
940            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
941            verificationIntent.putExtra(
942                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
943                    verificationId);
944            verificationIntent.putExtra(
945                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
946                    getDefaultScheme());
947            verificationIntent.putExtra(
948                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
949                    ivs.getHostsString());
950            verificationIntent.putExtra(
951                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
952                    ivs.getPackageName());
953            verificationIntent.setComponent(mIntentFilterVerifierComponent);
954            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
955
956            UserHandle user = new UserHandle(userId);
957            mContext.sendBroadcastAsUser(verificationIntent, user);
958            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
959                    "Sending IntentFilter verification broadcast");
960        }
961
962        public void receiveVerificationResponse(int verificationId) {
963            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
964
965            final boolean verified = ivs.isVerified();
966
967            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
968            final int count = filters.size();
969            if (DEBUG_DOMAIN_VERIFICATION) {
970                Slog.i(TAG, "Received verification response " + verificationId
971                        + " for " + count + " filters, verified=" + verified);
972            }
973            for (int n=0; n<count; n++) {
974                PackageParser.ActivityIntentInfo filter = filters.get(n);
975                filter.setVerified(verified);
976
977                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
978                        + " verified with result:" + verified + " and hosts:"
979                        + ivs.getHostsString());
980            }
981
982            mIntentFilterVerificationStates.remove(verificationId);
983
984            final String packageName = ivs.getPackageName();
985            IntentFilterVerificationInfo ivi = null;
986
987            synchronized (mPackages) {
988                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
989            }
990            if (ivi == null) {
991                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
992                        + verificationId + " packageName:" + packageName);
993                return;
994            }
995            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
996                    "Updating IntentFilterVerificationInfo for package " + packageName
997                            +" verificationId:" + verificationId);
998
999            synchronized (mPackages) {
1000                if (verified) {
1001                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1002                } else {
1003                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1004                }
1005                scheduleWriteSettingsLocked();
1006
1007                final int userId = ivs.getUserId();
1008                if (userId != UserHandle.USER_ALL) {
1009                    final int userStatus =
1010                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1011
1012                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1013                    boolean needUpdate = false;
1014
1015                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1016                    // already been set by the User thru the Disambiguation dialog
1017                    switch (userStatus) {
1018                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1019                            if (verified) {
1020                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1021                            } else {
1022                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1023                            }
1024                            needUpdate = true;
1025                            break;
1026
1027                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1028                            if (verified) {
1029                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1030                                needUpdate = true;
1031                            }
1032                            break;
1033
1034                        default:
1035                            // Nothing to do
1036                    }
1037
1038                    if (needUpdate) {
1039                        mSettings.updateIntentFilterVerificationStatusLPw(
1040                                packageName, updatedStatus, userId);
1041                        scheduleWritePackageRestrictionsLocked(userId);
1042                    }
1043                }
1044            }
1045        }
1046
1047        @Override
1048        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1049                    ActivityIntentInfo filter, String packageName) {
1050            if (!hasValidDomains(filter)) {
1051                return false;
1052            }
1053            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1054            if (ivs == null) {
1055                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1056                        packageName);
1057            }
1058            if (DEBUG_DOMAIN_VERIFICATION) {
1059                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1060            }
1061            ivs.addFilter(filter);
1062            return true;
1063        }
1064
1065        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1066                int userId, int verificationId, String packageName) {
1067            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1068                    verifierUid, userId, packageName);
1069            ivs.setPendingState();
1070            synchronized (mPackages) {
1071                mIntentFilterVerificationStates.append(verificationId, ivs);
1072                mCurrentIntentFilterVerifications.add(verificationId);
1073            }
1074            return ivs;
1075        }
1076    }
1077
1078    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1079        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1080                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1081                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1082    }
1083
1084    // Set of pending broadcasts for aggregating enable/disable of components.
1085    static class PendingPackageBroadcasts {
1086        // for each user id, a map of <package name -> components within that package>
1087        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1088
1089        public PendingPackageBroadcasts() {
1090            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1091        }
1092
1093        public ArrayList<String> get(int userId, String packageName) {
1094            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1095            return packages.get(packageName);
1096        }
1097
1098        public void put(int userId, String packageName, ArrayList<String> components) {
1099            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1100            packages.put(packageName, components);
1101        }
1102
1103        public void remove(int userId, String packageName) {
1104            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1105            if (packages != null) {
1106                packages.remove(packageName);
1107            }
1108        }
1109
1110        public void remove(int userId) {
1111            mUidMap.remove(userId);
1112        }
1113
1114        public int userIdCount() {
1115            return mUidMap.size();
1116        }
1117
1118        public int userIdAt(int n) {
1119            return mUidMap.keyAt(n);
1120        }
1121
1122        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1123            return mUidMap.get(userId);
1124        }
1125
1126        public int size() {
1127            // total number of pending broadcast entries across all userIds
1128            int num = 0;
1129            for (int i = 0; i< mUidMap.size(); i++) {
1130                num += mUidMap.valueAt(i).size();
1131            }
1132            return num;
1133        }
1134
1135        public void clear() {
1136            mUidMap.clear();
1137        }
1138
1139        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1140            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1141            if (map == null) {
1142                map = new ArrayMap<String, ArrayList<String>>();
1143                mUidMap.put(userId, map);
1144            }
1145            return map;
1146        }
1147    }
1148    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1149
1150    // Service Connection to remote media container service to copy
1151    // package uri's from external media onto secure containers
1152    // or internal storage.
1153    private IMediaContainerService mContainerService = null;
1154
1155    static final int SEND_PENDING_BROADCAST = 1;
1156    static final int MCS_BOUND = 3;
1157    static final int END_COPY = 4;
1158    static final int INIT_COPY = 5;
1159    static final int MCS_UNBIND = 6;
1160    static final int START_CLEANING_PACKAGE = 7;
1161    static final int FIND_INSTALL_LOC = 8;
1162    static final int POST_INSTALL = 9;
1163    static final int MCS_RECONNECT = 10;
1164    static final int MCS_GIVE_UP = 11;
1165    static final int UPDATED_MEDIA_STATUS = 12;
1166    static final int WRITE_SETTINGS = 13;
1167    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1168    static final int PACKAGE_VERIFIED = 15;
1169    static final int CHECK_PENDING_VERIFICATION = 16;
1170    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1171    static final int INTENT_FILTER_VERIFIED = 18;
1172    static final int WRITE_PACKAGE_LIST = 19;
1173    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1174
1175    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1176
1177    // Delay time in millisecs
1178    static final int BROADCAST_DELAY = 10 * 1000;
1179
1180    static UserManagerService sUserManager;
1181
1182    // Stores a list of users whose package restrictions file needs to be updated
1183    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1184
1185    final private DefaultContainerConnection mDefContainerConn =
1186            new DefaultContainerConnection();
1187    class DefaultContainerConnection implements ServiceConnection {
1188        public void onServiceConnected(ComponentName name, IBinder service) {
1189            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1190            final IMediaContainerService imcs = IMediaContainerService.Stub
1191                    .asInterface(Binder.allowBlocking(service));
1192            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1193        }
1194
1195        public void onServiceDisconnected(ComponentName name) {
1196            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1197        }
1198    }
1199
1200    // Recordkeeping of restore-after-install operations that are currently in flight
1201    // between the Package Manager and the Backup Manager
1202    static class PostInstallData {
1203        public InstallArgs args;
1204        public PackageInstalledInfo res;
1205
1206        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1207            args = _a;
1208            res = _r;
1209        }
1210    }
1211
1212    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1213    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1214
1215    // XML tags for backup/restore of various bits of state
1216    private static final String TAG_PREFERRED_BACKUP = "pa";
1217    private static final String TAG_DEFAULT_APPS = "da";
1218    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1219
1220    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1221    private static final String TAG_ALL_GRANTS = "rt-grants";
1222    private static final String TAG_GRANT = "grant";
1223    private static final String ATTR_PACKAGE_NAME = "pkg";
1224
1225    private static final String TAG_PERMISSION = "perm";
1226    private static final String ATTR_PERMISSION_NAME = "name";
1227    private static final String ATTR_IS_GRANTED = "g";
1228    private static final String ATTR_USER_SET = "set";
1229    private static final String ATTR_USER_FIXED = "fixed";
1230    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1231
1232    // System/policy permission grants are not backed up
1233    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1234            FLAG_PERMISSION_POLICY_FIXED
1235            | FLAG_PERMISSION_SYSTEM_FIXED
1236            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1237
1238    // And we back up these user-adjusted states
1239    private static final int USER_RUNTIME_GRANT_MASK =
1240            FLAG_PERMISSION_USER_SET
1241            | FLAG_PERMISSION_USER_FIXED
1242            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1243
1244    final @Nullable String mRequiredVerifierPackage;
1245    final @NonNull String mRequiredInstallerPackage;
1246    final @NonNull String mRequiredUninstallerPackage;
1247    final @Nullable String mSetupWizardPackage;
1248    final @Nullable String mStorageManagerPackage;
1249    final @NonNull String mServicesSystemSharedLibraryPackageName;
1250    final @NonNull String mSharedSystemSharedLibraryPackageName;
1251
1252    final boolean mPermissionReviewRequired;
1253
1254    private final PackageUsage mPackageUsage = new PackageUsage();
1255    private final CompilerStats mCompilerStats = new CompilerStats();
1256
1257    class PackageHandler extends Handler {
1258        private boolean mBound = false;
1259        final ArrayList<HandlerParams> mPendingInstalls =
1260            new ArrayList<HandlerParams>();
1261
1262        private boolean connectToService() {
1263            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1264                    " DefaultContainerService");
1265            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1266            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1267            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1268                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1269                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1270                mBound = true;
1271                return true;
1272            }
1273            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1274            return false;
1275        }
1276
1277        private void disconnectService() {
1278            mContainerService = null;
1279            mBound = false;
1280            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1281            mContext.unbindService(mDefContainerConn);
1282            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1283        }
1284
1285        PackageHandler(Looper looper) {
1286            super(looper);
1287        }
1288
1289        public void handleMessage(Message msg) {
1290            try {
1291                doHandleMessage(msg);
1292            } finally {
1293                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1294            }
1295        }
1296
1297        void doHandleMessage(Message msg) {
1298            switch (msg.what) {
1299                case INIT_COPY: {
1300                    HandlerParams params = (HandlerParams) msg.obj;
1301                    int idx = mPendingInstalls.size();
1302                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1303                    // If a bind was already initiated we dont really
1304                    // need to do anything. The pending install
1305                    // will be processed later on.
1306                    if (!mBound) {
1307                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1308                                System.identityHashCode(mHandler));
1309                        // If this is the only one pending we might
1310                        // have to bind to the service again.
1311                        if (!connectToService()) {
1312                            Slog.e(TAG, "Failed to bind to media container service");
1313                            params.serviceError();
1314                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1315                                    System.identityHashCode(mHandler));
1316                            if (params.traceMethod != null) {
1317                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1318                                        params.traceCookie);
1319                            }
1320                            return;
1321                        } else {
1322                            // Once we bind to the service, the first
1323                            // pending request will be processed.
1324                            mPendingInstalls.add(idx, params);
1325                        }
1326                    } else {
1327                        mPendingInstalls.add(idx, params);
1328                        // Already bound to the service. Just make
1329                        // sure we trigger off processing the first request.
1330                        if (idx == 0) {
1331                            mHandler.sendEmptyMessage(MCS_BOUND);
1332                        }
1333                    }
1334                    break;
1335                }
1336                case MCS_BOUND: {
1337                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1338                    if (msg.obj != null) {
1339                        mContainerService = (IMediaContainerService) msg.obj;
1340                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1341                                System.identityHashCode(mHandler));
1342                    }
1343                    if (mContainerService == null) {
1344                        if (!mBound) {
1345                            // Something seriously wrong since we are not bound and we are not
1346                            // waiting for connection. Bail out.
1347                            Slog.e(TAG, "Cannot bind to media container service");
1348                            for (HandlerParams params : mPendingInstalls) {
1349                                // Indicate service bind error
1350                                params.serviceError();
1351                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1352                                        System.identityHashCode(params));
1353                                if (params.traceMethod != null) {
1354                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1355                                            params.traceMethod, params.traceCookie);
1356                                }
1357                                return;
1358                            }
1359                            mPendingInstalls.clear();
1360                        } else {
1361                            Slog.w(TAG, "Waiting to connect to media container service");
1362                        }
1363                    } else if (mPendingInstalls.size() > 0) {
1364                        HandlerParams params = mPendingInstalls.get(0);
1365                        if (params != null) {
1366                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1367                                    System.identityHashCode(params));
1368                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1369                            if (params.startCopy()) {
1370                                // We are done...  look for more work or to
1371                                // go idle.
1372                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1373                                        "Checking for more work or unbind...");
1374                                // Delete pending install
1375                                if (mPendingInstalls.size() > 0) {
1376                                    mPendingInstalls.remove(0);
1377                                }
1378                                if (mPendingInstalls.size() == 0) {
1379                                    if (mBound) {
1380                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1381                                                "Posting delayed MCS_UNBIND");
1382                                        removeMessages(MCS_UNBIND);
1383                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1384                                        // Unbind after a little delay, to avoid
1385                                        // continual thrashing.
1386                                        sendMessageDelayed(ubmsg, 10000);
1387                                    }
1388                                } else {
1389                                    // There are more pending requests in queue.
1390                                    // Just post MCS_BOUND message to trigger processing
1391                                    // of next pending install.
1392                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1393                                            "Posting MCS_BOUND for next work");
1394                                    mHandler.sendEmptyMessage(MCS_BOUND);
1395                                }
1396                            }
1397                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1398                        }
1399                    } else {
1400                        // Should never happen ideally.
1401                        Slog.w(TAG, "Empty queue");
1402                    }
1403                    break;
1404                }
1405                case MCS_RECONNECT: {
1406                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1407                    if (mPendingInstalls.size() > 0) {
1408                        if (mBound) {
1409                            disconnectService();
1410                        }
1411                        if (!connectToService()) {
1412                            Slog.e(TAG, "Failed to bind to media container service");
1413                            for (HandlerParams params : mPendingInstalls) {
1414                                // Indicate service bind error
1415                                params.serviceError();
1416                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1417                                        System.identityHashCode(params));
1418                            }
1419                            mPendingInstalls.clear();
1420                        }
1421                    }
1422                    break;
1423                }
1424                case MCS_UNBIND: {
1425                    // If there is no actual work left, then time to unbind.
1426                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1427
1428                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1429                        if (mBound) {
1430                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1431
1432                            disconnectService();
1433                        }
1434                    } else if (mPendingInstalls.size() > 0) {
1435                        // There are more pending requests in queue.
1436                        // Just post MCS_BOUND message to trigger processing
1437                        // of next pending install.
1438                        mHandler.sendEmptyMessage(MCS_BOUND);
1439                    }
1440
1441                    break;
1442                }
1443                case MCS_GIVE_UP: {
1444                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1445                    HandlerParams params = mPendingInstalls.remove(0);
1446                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1447                            System.identityHashCode(params));
1448                    break;
1449                }
1450                case SEND_PENDING_BROADCAST: {
1451                    String packages[];
1452                    ArrayList<String> components[];
1453                    int size = 0;
1454                    int uids[];
1455                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1456                    synchronized (mPackages) {
1457                        if (mPendingBroadcasts == null) {
1458                            return;
1459                        }
1460                        size = mPendingBroadcasts.size();
1461                        if (size <= 0) {
1462                            // Nothing to be done. Just return
1463                            return;
1464                        }
1465                        packages = new String[size];
1466                        components = new ArrayList[size];
1467                        uids = new int[size];
1468                        int i = 0;  // filling out the above arrays
1469
1470                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1471                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1472                            Iterator<Map.Entry<String, ArrayList<String>>> it
1473                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1474                                            .entrySet().iterator();
1475                            while (it.hasNext() && i < size) {
1476                                Map.Entry<String, ArrayList<String>> ent = it.next();
1477                                packages[i] = ent.getKey();
1478                                components[i] = ent.getValue();
1479                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1480                                uids[i] = (ps != null)
1481                                        ? UserHandle.getUid(packageUserId, ps.appId)
1482                                        : -1;
1483                                i++;
1484                            }
1485                        }
1486                        size = i;
1487                        mPendingBroadcasts.clear();
1488                    }
1489                    // Send broadcasts
1490                    for (int i = 0; i < size; i++) {
1491                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1492                    }
1493                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1494                    break;
1495                }
1496                case START_CLEANING_PACKAGE: {
1497                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1498                    final String packageName = (String)msg.obj;
1499                    final int userId = msg.arg1;
1500                    final boolean andCode = msg.arg2 != 0;
1501                    synchronized (mPackages) {
1502                        if (userId == UserHandle.USER_ALL) {
1503                            int[] users = sUserManager.getUserIds();
1504                            for (int user : users) {
1505                                mSettings.addPackageToCleanLPw(
1506                                        new PackageCleanItem(user, packageName, andCode));
1507                            }
1508                        } else {
1509                            mSettings.addPackageToCleanLPw(
1510                                    new PackageCleanItem(userId, packageName, andCode));
1511                        }
1512                    }
1513                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1514                    startCleaningPackages();
1515                } break;
1516                case POST_INSTALL: {
1517                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1518
1519                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1520                    final boolean didRestore = (msg.arg2 != 0);
1521                    mRunningInstalls.delete(msg.arg1);
1522
1523                    if (data != null) {
1524                        InstallArgs args = data.args;
1525                        PackageInstalledInfo parentRes = data.res;
1526
1527                        final boolean grantPermissions = (args.installFlags
1528                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1529                        final boolean killApp = (args.installFlags
1530                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1531                        final String[] grantedPermissions = args.installGrantPermissions;
1532
1533                        // Handle the parent package
1534                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1535                                grantedPermissions, didRestore, args.installerPackageName,
1536                                args.observer);
1537
1538                        // Handle the child packages
1539                        final int childCount = (parentRes.addedChildPackages != null)
1540                                ? parentRes.addedChildPackages.size() : 0;
1541                        for (int i = 0; i < childCount; i++) {
1542                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1543                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1544                                    grantedPermissions, false, args.installerPackageName,
1545                                    args.observer);
1546                        }
1547
1548                        // Log tracing if needed
1549                        if (args.traceMethod != null) {
1550                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1551                                    args.traceCookie);
1552                        }
1553                    } else {
1554                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1555                    }
1556
1557                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1558                } break;
1559                case UPDATED_MEDIA_STATUS: {
1560                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1561                    boolean reportStatus = msg.arg1 == 1;
1562                    boolean doGc = msg.arg2 == 1;
1563                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1564                    if (doGc) {
1565                        // Force a gc to clear up stale containers.
1566                        Runtime.getRuntime().gc();
1567                    }
1568                    if (msg.obj != null) {
1569                        @SuppressWarnings("unchecked")
1570                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1571                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1572                        // Unload containers
1573                        unloadAllContainers(args);
1574                    }
1575                    if (reportStatus) {
1576                        try {
1577                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1578                                    "Invoking StorageManagerService call back");
1579                            PackageHelper.getStorageManager().finishMediaUpdate();
1580                        } catch (RemoteException e) {
1581                            Log.e(TAG, "StorageManagerService not running?");
1582                        }
1583                    }
1584                } break;
1585                case WRITE_SETTINGS: {
1586                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1587                    synchronized (mPackages) {
1588                        removeMessages(WRITE_SETTINGS);
1589                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1590                        mSettings.writeLPr();
1591                        mDirtyUsers.clear();
1592                    }
1593                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1594                } break;
1595                case WRITE_PACKAGE_RESTRICTIONS: {
1596                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1597                    synchronized (mPackages) {
1598                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1599                        for (int userId : mDirtyUsers) {
1600                            mSettings.writePackageRestrictionsLPr(userId);
1601                        }
1602                        mDirtyUsers.clear();
1603                    }
1604                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1605                } break;
1606                case WRITE_PACKAGE_LIST: {
1607                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1608                    synchronized (mPackages) {
1609                        removeMessages(WRITE_PACKAGE_LIST);
1610                        mSettings.writePackageListLPr(msg.arg1);
1611                    }
1612                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1613                } break;
1614                case CHECK_PENDING_VERIFICATION: {
1615                    final int verificationId = msg.arg1;
1616                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1617
1618                    if ((state != null) && !state.timeoutExtended()) {
1619                        final InstallArgs args = state.getInstallArgs();
1620                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1621
1622                        Slog.i(TAG, "Verification timed out for " + originUri);
1623                        mPendingVerification.remove(verificationId);
1624
1625                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1626
1627                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1628                            Slog.i(TAG, "Continuing with installation of " + originUri);
1629                            state.setVerifierResponse(Binder.getCallingUid(),
1630                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1631                            broadcastPackageVerified(verificationId, originUri,
1632                                    PackageManager.VERIFICATION_ALLOW,
1633                                    state.getInstallArgs().getUser());
1634                            try {
1635                                ret = args.copyApk(mContainerService, true);
1636                            } catch (RemoteException e) {
1637                                Slog.e(TAG, "Could not contact the ContainerService");
1638                            }
1639                        } else {
1640                            broadcastPackageVerified(verificationId, originUri,
1641                                    PackageManager.VERIFICATION_REJECT,
1642                                    state.getInstallArgs().getUser());
1643                        }
1644
1645                        Trace.asyncTraceEnd(
1646                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1647
1648                        processPendingInstall(args, ret);
1649                        mHandler.sendEmptyMessage(MCS_UNBIND);
1650                    }
1651                    break;
1652                }
1653                case PACKAGE_VERIFIED: {
1654                    final int verificationId = msg.arg1;
1655
1656                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1657                    if (state == null) {
1658                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1659                        break;
1660                    }
1661
1662                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1663
1664                    state.setVerifierResponse(response.callerUid, response.code);
1665
1666                    if (state.isVerificationComplete()) {
1667                        mPendingVerification.remove(verificationId);
1668
1669                        final InstallArgs args = state.getInstallArgs();
1670                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1671
1672                        int ret;
1673                        if (state.isInstallAllowed()) {
1674                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1675                            broadcastPackageVerified(verificationId, originUri,
1676                                    response.code, state.getInstallArgs().getUser());
1677                            try {
1678                                ret = args.copyApk(mContainerService, true);
1679                            } catch (RemoteException e) {
1680                                Slog.e(TAG, "Could not contact the ContainerService");
1681                            }
1682                        } else {
1683                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1684                        }
1685
1686                        Trace.asyncTraceEnd(
1687                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1688
1689                        processPendingInstall(args, ret);
1690                        mHandler.sendEmptyMessage(MCS_UNBIND);
1691                    }
1692
1693                    break;
1694                }
1695                case START_INTENT_FILTER_VERIFICATIONS: {
1696                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1697                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1698                            params.replacing, params.pkg);
1699                    break;
1700                }
1701                case INTENT_FILTER_VERIFIED: {
1702                    final int verificationId = msg.arg1;
1703
1704                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1705                            verificationId);
1706                    if (state == null) {
1707                        Slog.w(TAG, "Invalid IntentFilter verification token "
1708                                + verificationId + " received");
1709                        break;
1710                    }
1711
1712                    final int userId = state.getUserId();
1713
1714                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1715                            "Processing IntentFilter verification with token:"
1716                            + verificationId + " and userId:" + userId);
1717
1718                    final IntentFilterVerificationResponse response =
1719                            (IntentFilterVerificationResponse) msg.obj;
1720
1721                    state.setVerifierResponse(response.callerUid, response.code);
1722
1723                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1724                            "IntentFilter verification with token:" + verificationId
1725                            + " and userId:" + userId
1726                            + " is settings verifier response with response code:"
1727                            + response.code);
1728
1729                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1730                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1731                                + response.getFailedDomainsString());
1732                    }
1733
1734                    if (state.isVerificationComplete()) {
1735                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1736                    } else {
1737                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1738                                "IntentFilter verification with token:" + verificationId
1739                                + " was not said to be complete");
1740                    }
1741
1742                    break;
1743                }
1744                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1745                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1746                            mInstantAppResolverConnection,
1747                            (InstantAppRequest) msg.obj,
1748                            mInstantAppInstallerActivity,
1749                            mHandler);
1750                }
1751            }
1752        }
1753    }
1754
1755    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1756            boolean killApp, String[] grantedPermissions,
1757            boolean launchedForRestore, String installerPackage,
1758            IPackageInstallObserver2 installObserver) {
1759        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1760            // Send the removed broadcasts
1761            if (res.removedInfo != null) {
1762                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1763            }
1764
1765            // Now that we successfully installed the package, grant runtime
1766            // permissions if requested before broadcasting the install. Also
1767            // for legacy apps in permission review mode we clear the permission
1768            // review flag which is used to emulate runtime permissions for
1769            // legacy apps.
1770            if (grantPermissions) {
1771                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1772            }
1773
1774            final boolean update = res.removedInfo != null
1775                    && res.removedInfo.removedPackage != null;
1776
1777            // If this is the first time we have child packages for a disabled privileged
1778            // app that had no children, we grant requested runtime permissions to the new
1779            // children if the parent on the system image had them already granted.
1780            if (res.pkg.parentPackage != null) {
1781                synchronized (mPackages) {
1782                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1783                }
1784            }
1785
1786            synchronized (mPackages) {
1787                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1788            }
1789
1790            final String packageName = res.pkg.applicationInfo.packageName;
1791
1792            // Determine the set of users who are adding this package for
1793            // the first time vs. those who are seeing an update.
1794            int[] firstUsers = EMPTY_INT_ARRAY;
1795            int[] updateUsers = EMPTY_INT_ARRAY;
1796            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1797            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1798            for (int newUser : res.newUsers) {
1799                if (ps.getInstantApp(newUser)) {
1800                    continue;
1801                }
1802                if (allNewUsers) {
1803                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1804                    continue;
1805                }
1806                boolean isNew = true;
1807                for (int origUser : res.origUsers) {
1808                    if (origUser == newUser) {
1809                        isNew = false;
1810                        break;
1811                    }
1812                }
1813                if (isNew) {
1814                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1815                } else {
1816                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1817                }
1818            }
1819
1820            // Send installed broadcasts if the package is not a static shared lib.
1821            if (res.pkg.staticSharedLibName == null) {
1822                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1823
1824                // Send added for users that see the package for the first time
1825                // sendPackageAddedForNewUsers also deals with system apps
1826                int appId = UserHandle.getAppId(res.uid);
1827                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1828                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1829
1830                // Send added for users that don't see the package for the first time
1831                Bundle extras = new Bundle(1);
1832                extras.putInt(Intent.EXTRA_UID, res.uid);
1833                if (update) {
1834                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1835                }
1836                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1837                        extras, 0 /*flags*/, null /*targetPackage*/,
1838                        null /*finishedReceiver*/, updateUsers);
1839
1840                // Send replaced for users that don't see the package for the first time
1841                if (update) {
1842                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1843                            packageName, extras, 0 /*flags*/,
1844                            null /*targetPackage*/, null /*finishedReceiver*/,
1845                            updateUsers);
1846                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1847                            null /*package*/, null /*extras*/, 0 /*flags*/,
1848                            packageName /*targetPackage*/,
1849                            null /*finishedReceiver*/, updateUsers);
1850                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1851                    // First-install and we did a restore, so we're responsible for the
1852                    // first-launch broadcast.
1853                    if (DEBUG_BACKUP) {
1854                        Slog.i(TAG, "Post-restore of " + packageName
1855                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1856                    }
1857                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1858                }
1859
1860                // Send broadcast package appeared if forward locked/external for all users
1861                // treat asec-hosted packages like removable media on upgrade
1862                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1863                    if (DEBUG_INSTALL) {
1864                        Slog.i(TAG, "upgrading pkg " + res.pkg
1865                                + " is ASEC-hosted -> AVAILABLE");
1866                    }
1867                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1868                    ArrayList<String> pkgList = new ArrayList<>(1);
1869                    pkgList.add(packageName);
1870                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1871                }
1872            }
1873
1874            // Work that needs to happen on first install within each user
1875            if (firstUsers != null && firstUsers.length > 0) {
1876                synchronized (mPackages) {
1877                    for (int userId : firstUsers) {
1878                        // If this app is a browser and it's newly-installed for some
1879                        // users, clear any default-browser state in those users. The
1880                        // app's nature doesn't depend on the user, so we can just check
1881                        // its browser nature in any user and generalize.
1882                        if (packageIsBrowser(packageName, userId)) {
1883                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1884                        }
1885
1886                        // We may also need to apply pending (restored) runtime
1887                        // permission grants within these users.
1888                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1889                    }
1890                }
1891            }
1892
1893            // Log current value of "unknown sources" setting
1894            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1895                    getUnknownSourcesSettings());
1896
1897            // Force a gc to clear up things
1898            Runtime.getRuntime().gc();
1899
1900            // Remove the replaced package's older resources safely now
1901            // We delete after a gc for applications  on sdcard.
1902            if (res.removedInfo != null && res.removedInfo.args != null) {
1903                synchronized (mInstallLock) {
1904                    res.removedInfo.args.doPostDeleteLI(true);
1905                }
1906            }
1907
1908            // Notify DexManager that the package was installed for new users.
1909            // The updated users should already be indexed and the package code paths
1910            // should not change.
1911            // Don't notify the manager for ephemeral apps as they are not expected to
1912            // survive long enough to benefit of background optimizations.
1913            for (int userId : firstUsers) {
1914                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
1915                mDexManager.notifyPackageInstalled(info, userId);
1916            }
1917        }
1918
1919        // If someone is watching installs - notify them
1920        if (installObserver != null) {
1921            try {
1922                Bundle extras = extrasForInstallResult(res);
1923                installObserver.onPackageInstalled(res.name, res.returnCode,
1924                        res.returnMsg, extras);
1925            } catch (RemoteException e) {
1926                Slog.i(TAG, "Observer no longer exists.");
1927            }
1928        }
1929    }
1930
1931    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1932            PackageParser.Package pkg) {
1933        if (pkg.parentPackage == null) {
1934            return;
1935        }
1936        if (pkg.requestedPermissions == null) {
1937            return;
1938        }
1939        final PackageSetting disabledSysParentPs = mSettings
1940                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1941        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1942                || !disabledSysParentPs.isPrivileged()
1943                || (disabledSysParentPs.childPackageNames != null
1944                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1945            return;
1946        }
1947        final int[] allUserIds = sUserManager.getUserIds();
1948        final int permCount = pkg.requestedPermissions.size();
1949        for (int i = 0; i < permCount; i++) {
1950            String permission = pkg.requestedPermissions.get(i);
1951            BasePermission bp = mSettings.mPermissions.get(permission);
1952            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1953                continue;
1954            }
1955            for (int userId : allUserIds) {
1956                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1957                        permission, userId)) {
1958                    grantRuntimePermission(pkg.packageName, permission, userId);
1959                }
1960            }
1961        }
1962    }
1963
1964    private StorageEventListener mStorageListener = new StorageEventListener() {
1965        @Override
1966        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1967            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1968                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1969                    final String volumeUuid = vol.getFsUuid();
1970
1971                    // Clean up any users or apps that were removed or recreated
1972                    // while this volume was missing
1973                    sUserManager.reconcileUsers(volumeUuid);
1974                    reconcileApps(volumeUuid);
1975
1976                    // Clean up any install sessions that expired or were
1977                    // cancelled while this volume was missing
1978                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1979
1980                    loadPrivatePackages(vol);
1981
1982                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1983                    unloadPrivatePackages(vol);
1984                }
1985            }
1986
1987            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1988                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1989                    updateExternalMediaStatus(true, false);
1990                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1991                    updateExternalMediaStatus(false, false);
1992                }
1993            }
1994        }
1995
1996        @Override
1997        public void onVolumeForgotten(String fsUuid) {
1998            if (TextUtils.isEmpty(fsUuid)) {
1999                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2000                return;
2001            }
2002
2003            // Remove any apps installed on the forgotten volume
2004            synchronized (mPackages) {
2005                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2006                for (PackageSetting ps : packages) {
2007                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2008                    deletePackageVersioned(new VersionedPackage(ps.name,
2009                            PackageManager.VERSION_CODE_HIGHEST),
2010                            new LegacyPackageDeleteObserver(null).getBinder(),
2011                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2012                    // Try very hard to release any references to this package
2013                    // so we don't risk the system server being killed due to
2014                    // open FDs
2015                    AttributeCache.instance().removePackage(ps.name);
2016                }
2017
2018                mSettings.onVolumeForgotten(fsUuid);
2019                mSettings.writeLPr();
2020            }
2021        }
2022    };
2023
2024    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2025            String[] grantedPermissions) {
2026        for (int userId : userIds) {
2027            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2028        }
2029    }
2030
2031    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2032            String[] grantedPermissions) {
2033        SettingBase sb = (SettingBase) pkg.mExtras;
2034        if (sb == null) {
2035            return;
2036        }
2037
2038        PermissionsState permissionsState = sb.getPermissionsState();
2039
2040        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2041                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2042
2043        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2044                >= Build.VERSION_CODES.M;
2045
2046        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2047
2048        for (String permission : pkg.requestedPermissions) {
2049            final BasePermission bp;
2050            synchronized (mPackages) {
2051                bp = mSettings.mPermissions.get(permission);
2052            }
2053            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2054                    && (!instantApp || bp.isInstant())
2055                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2056                    && (grantedPermissions == null
2057                           || ArrayUtils.contains(grantedPermissions, permission))) {
2058                final int flags = permissionsState.getPermissionFlags(permission, userId);
2059                if (supportsRuntimePermissions) {
2060                    // Installer cannot change immutable permissions.
2061                    if ((flags & immutableFlags) == 0) {
2062                        grantRuntimePermission(pkg.packageName, permission, userId);
2063                    }
2064                } else if (mPermissionReviewRequired) {
2065                    // In permission review mode we clear the review flag when we
2066                    // are asked to install the app with all permissions granted.
2067                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2068                        updatePermissionFlags(permission, pkg.packageName,
2069                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2070                    }
2071                }
2072            }
2073        }
2074    }
2075
2076    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2077        Bundle extras = null;
2078        switch (res.returnCode) {
2079            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2080                extras = new Bundle();
2081                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2082                        res.origPermission);
2083                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2084                        res.origPackage);
2085                break;
2086            }
2087            case PackageManager.INSTALL_SUCCEEDED: {
2088                extras = new Bundle();
2089                extras.putBoolean(Intent.EXTRA_REPLACING,
2090                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2091                break;
2092            }
2093        }
2094        return extras;
2095    }
2096
2097    void scheduleWriteSettingsLocked() {
2098        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2099            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2100        }
2101    }
2102
2103    void scheduleWritePackageListLocked(int userId) {
2104        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2105            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2106            msg.arg1 = userId;
2107            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2108        }
2109    }
2110
2111    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2112        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2113        scheduleWritePackageRestrictionsLocked(userId);
2114    }
2115
2116    void scheduleWritePackageRestrictionsLocked(int userId) {
2117        final int[] userIds = (userId == UserHandle.USER_ALL)
2118                ? sUserManager.getUserIds() : new int[]{userId};
2119        for (int nextUserId : userIds) {
2120            if (!sUserManager.exists(nextUserId)) return;
2121            mDirtyUsers.add(nextUserId);
2122            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2123                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2124            }
2125        }
2126    }
2127
2128    public static PackageManagerService main(Context context, Installer installer,
2129            boolean factoryTest, boolean onlyCore) {
2130        // Self-check for initial settings.
2131        PackageManagerServiceCompilerMapping.checkProperties();
2132
2133        PackageManagerService m = new PackageManagerService(context, installer,
2134                factoryTest, onlyCore);
2135        m.enableSystemUserPackages();
2136        ServiceManager.addService("package", m);
2137        return m;
2138    }
2139
2140    private void enableSystemUserPackages() {
2141        if (!UserManager.isSplitSystemUser()) {
2142            return;
2143        }
2144        // For system user, enable apps based on the following conditions:
2145        // - app is whitelisted or belong to one of these groups:
2146        //   -- system app which has no launcher icons
2147        //   -- system app which has INTERACT_ACROSS_USERS permission
2148        //   -- system IME app
2149        // - app is not in the blacklist
2150        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2151        Set<String> enableApps = new ArraySet<>();
2152        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2153                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2154                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2155        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2156        enableApps.addAll(wlApps);
2157        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2158                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2159        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2160        enableApps.removeAll(blApps);
2161        Log.i(TAG, "Applications installed for system user: " + enableApps);
2162        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2163                UserHandle.SYSTEM);
2164        final int allAppsSize = allAps.size();
2165        synchronized (mPackages) {
2166            for (int i = 0; i < allAppsSize; i++) {
2167                String pName = allAps.get(i);
2168                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2169                // Should not happen, but we shouldn't be failing if it does
2170                if (pkgSetting == null) {
2171                    continue;
2172                }
2173                boolean install = enableApps.contains(pName);
2174                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2175                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2176                            + " for system user");
2177                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2178                }
2179            }
2180            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2181        }
2182    }
2183
2184    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2185        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2186                Context.DISPLAY_SERVICE);
2187        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2188    }
2189
2190    /**
2191     * Requests that files preopted on a secondary system partition be copied to the data partition
2192     * if possible.  Note that the actual copying of the files is accomplished by init for security
2193     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2194     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2195     */
2196    private static void requestCopyPreoptedFiles() {
2197        final int WAIT_TIME_MS = 100;
2198        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2199        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2200            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2201            // We will wait for up to 100 seconds.
2202            final long timeStart = SystemClock.uptimeMillis();
2203            final long timeEnd = timeStart + 100 * 1000;
2204            long timeNow = timeStart;
2205            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2206                try {
2207                    Thread.sleep(WAIT_TIME_MS);
2208                } catch (InterruptedException e) {
2209                    // Do nothing
2210                }
2211                timeNow = SystemClock.uptimeMillis();
2212                if (timeNow > timeEnd) {
2213                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2214                    Slog.wtf(TAG, "cppreopt did not finish!");
2215                    break;
2216                }
2217            }
2218
2219            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2220        }
2221    }
2222
2223    public PackageManagerService(Context context, Installer installer,
2224            boolean factoryTest, boolean onlyCore) {
2225        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2226        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2227        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2228                SystemClock.uptimeMillis());
2229
2230        if (mSdkVersion <= 0) {
2231            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2232        }
2233
2234        mContext = context;
2235
2236        mPermissionReviewRequired = context.getResources().getBoolean(
2237                R.bool.config_permissionReviewRequired);
2238
2239        mFactoryTest = factoryTest;
2240        mOnlyCore = onlyCore;
2241        mMetrics = new DisplayMetrics();
2242        mSettings = new Settings(mPackages);
2243        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2244                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2245        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2246                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2247        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2248                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2249        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2250                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2251        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2252                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2253        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2254                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2255
2256        String separateProcesses = SystemProperties.get("debug.separate_processes");
2257        if (separateProcesses != null && separateProcesses.length() > 0) {
2258            if ("*".equals(separateProcesses)) {
2259                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2260                mSeparateProcesses = null;
2261                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2262            } else {
2263                mDefParseFlags = 0;
2264                mSeparateProcesses = separateProcesses.split(",");
2265                Slog.w(TAG, "Running with debug.separate_processes: "
2266                        + separateProcesses);
2267            }
2268        } else {
2269            mDefParseFlags = 0;
2270            mSeparateProcesses = null;
2271        }
2272
2273        mInstaller = installer;
2274        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2275                "*dexopt*");
2276        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2277        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2278
2279        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2280                FgThread.get().getLooper());
2281
2282        getDefaultDisplayMetrics(context, mMetrics);
2283
2284        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2285        SystemConfig systemConfig = SystemConfig.getInstance();
2286        mGlobalGids = systemConfig.getGlobalGids();
2287        mSystemPermissions = systemConfig.getSystemPermissions();
2288        mAvailableFeatures = systemConfig.getAvailableFeatures();
2289        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2290
2291        mProtectedPackages = new ProtectedPackages(mContext);
2292
2293        synchronized (mInstallLock) {
2294        // writer
2295        synchronized (mPackages) {
2296            mHandlerThread = new ServiceThread(TAG,
2297                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2298            mHandlerThread.start();
2299            mHandler = new PackageHandler(mHandlerThread.getLooper());
2300            mProcessLoggingHandler = new ProcessLoggingHandler();
2301            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2302
2303            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2304            mInstantAppRegistry = new InstantAppRegistry(this);
2305
2306            File dataDir = Environment.getDataDirectory();
2307            mAppInstallDir = new File(dataDir, "app");
2308            mAppLib32InstallDir = new File(dataDir, "app-lib");
2309            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2310            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2311            sUserManager = new UserManagerService(context, this,
2312                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2313
2314            // Propagate permission configuration in to package manager.
2315            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2316                    = systemConfig.getPermissions();
2317            for (int i=0; i<permConfig.size(); i++) {
2318                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2319                BasePermission bp = mSettings.mPermissions.get(perm.name);
2320                if (bp == null) {
2321                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2322                    mSettings.mPermissions.put(perm.name, bp);
2323                }
2324                if (perm.gids != null) {
2325                    bp.setGids(perm.gids, perm.perUser);
2326                }
2327            }
2328
2329            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2330            final int builtInLibCount = libConfig.size();
2331            for (int i = 0; i < builtInLibCount; i++) {
2332                String name = libConfig.keyAt(i);
2333                String path = libConfig.valueAt(i);
2334                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2335                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2336            }
2337
2338            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2339
2340            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2341            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2342            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2343
2344            // Clean up orphaned packages for which the code path doesn't exist
2345            // and they are an update to a system app - caused by bug/32321269
2346            final int packageSettingCount = mSettings.mPackages.size();
2347            for (int i = packageSettingCount - 1; i >= 0; i--) {
2348                PackageSetting ps = mSettings.mPackages.valueAt(i);
2349                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2350                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2351                    mSettings.mPackages.removeAt(i);
2352                    mSettings.enableSystemPackageLPw(ps.name);
2353                }
2354            }
2355
2356            if (mFirstBoot) {
2357                requestCopyPreoptedFiles();
2358            }
2359
2360            String customResolverActivity = Resources.getSystem().getString(
2361                    R.string.config_customResolverActivity);
2362            if (TextUtils.isEmpty(customResolverActivity)) {
2363                customResolverActivity = null;
2364            } else {
2365                mCustomResolverComponentName = ComponentName.unflattenFromString(
2366                        customResolverActivity);
2367            }
2368
2369            long startTime = SystemClock.uptimeMillis();
2370
2371            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2372                    startTime);
2373
2374            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2375            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2376
2377            if (bootClassPath == null) {
2378                Slog.w(TAG, "No BOOTCLASSPATH found!");
2379            }
2380
2381            if (systemServerClassPath == null) {
2382                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2383            }
2384
2385            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2386
2387            final VersionInfo ver = mSettings.getInternalVersion();
2388            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2389            if (mIsUpgrade) {
2390                logCriticalInfo(Log.INFO,
2391                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2392            }
2393
2394            // when upgrading from pre-M, promote system app permissions from install to runtime
2395            mPromoteSystemApps =
2396                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2397
2398            // When upgrading from pre-N, we need to handle package extraction like first boot,
2399            // as there is no profiling data available.
2400            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2401
2402            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2403
2404            // save off the names of pre-existing system packages prior to scanning; we don't
2405            // want to automatically grant runtime permissions for new system apps
2406            if (mPromoteSystemApps) {
2407                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2408                while (pkgSettingIter.hasNext()) {
2409                    PackageSetting ps = pkgSettingIter.next();
2410                    if (isSystemApp(ps)) {
2411                        mExistingSystemPackages.add(ps.name);
2412                    }
2413                }
2414            }
2415
2416            mCacheDir = preparePackageParserCache(mIsUpgrade);
2417
2418            // Set flag to monitor and not change apk file paths when
2419            // scanning install directories.
2420            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2421
2422            if (mIsUpgrade || mFirstBoot) {
2423                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2424            }
2425
2426            // Collect vendor overlay packages. (Do this before scanning any apps.)
2427            // For security and version matching reason, only consider
2428            // overlay packages if they reside in the right directory.
2429            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2430                    | PackageParser.PARSE_IS_SYSTEM
2431                    | PackageParser.PARSE_IS_SYSTEM_DIR
2432                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2433
2434            // Find base frameworks (resource packages without code).
2435            scanDirTracedLI(frameworkDir, mDefParseFlags
2436                    | PackageParser.PARSE_IS_SYSTEM
2437                    | PackageParser.PARSE_IS_SYSTEM_DIR
2438                    | PackageParser.PARSE_IS_PRIVILEGED,
2439                    scanFlags | SCAN_NO_DEX, 0);
2440
2441            // Collected privileged system packages.
2442            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2443            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2444                    | PackageParser.PARSE_IS_SYSTEM
2445                    | PackageParser.PARSE_IS_SYSTEM_DIR
2446                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2447
2448            // Collect ordinary system packages.
2449            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2450            scanDirTracedLI(systemAppDir, mDefParseFlags
2451                    | PackageParser.PARSE_IS_SYSTEM
2452                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2453
2454            // Collect all vendor packages.
2455            File vendorAppDir = new File("/vendor/app");
2456            try {
2457                vendorAppDir = vendorAppDir.getCanonicalFile();
2458            } catch (IOException e) {
2459                // failed to look up canonical path, continue with original one
2460            }
2461            scanDirTracedLI(vendorAppDir, mDefParseFlags
2462                    | PackageParser.PARSE_IS_SYSTEM
2463                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2464
2465            // Collect all OEM packages.
2466            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2467            scanDirTracedLI(oemAppDir, mDefParseFlags
2468                    | PackageParser.PARSE_IS_SYSTEM
2469                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2470
2471            // Prune any system packages that no longer exist.
2472            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2473            if (!mOnlyCore) {
2474                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2475                while (psit.hasNext()) {
2476                    PackageSetting ps = psit.next();
2477
2478                    /*
2479                     * If this is not a system app, it can't be a
2480                     * disable system app.
2481                     */
2482                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2483                        continue;
2484                    }
2485
2486                    /*
2487                     * If the package is scanned, it's not erased.
2488                     */
2489                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2490                    if (scannedPkg != null) {
2491                        /*
2492                         * If the system app is both scanned and in the
2493                         * disabled packages list, then it must have been
2494                         * added via OTA. Remove it from the currently
2495                         * scanned package so the previously user-installed
2496                         * application can be scanned.
2497                         */
2498                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2499                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2500                                    + ps.name + "; removing system app.  Last known codePath="
2501                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2502                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2503                                    + scannedPkg.mVersionCode);
2504                            removePackageLI(scannedPkg, true);
2505                            mExpectingBetter.put(ps.name, ps.codePath);
2506                        }
2507
2508                        continue;
2509                    }
2510
2511                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2512                        psit.remove();
2513                        logCriticalInfo(Log.WARN, "System package " + ps.name
2514                                + " no longer exists; it's data will be wiped");
2515                        // Actual deletion of code and data will be handled by later
2516                        // reconciliation step
2517                    } else {
2518                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2519                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2520                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2521                        }
2522                    }
2523                }
2524            }
2525
2526            //look for any incomplete package installations
2527            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2528            for (int i = 0; i < deletePkgsList.size(); i++) {
2529                // Actual deletion of code and data will be handled by later
2530                // reconciliation step
2531                final String packageName = deletePkgsList.get(i).name;
2532                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2533                synchronized (mPackages) {
2534                    mSettings.removePackageLPw(packageName);
2535                }
2536            }
2537
2538            //delete tmp files
2539            deleteTempPackageFiles();
2540
2541            // Remove any shared userIDs that have no associated packages
2542            mSettings.pruneSharedUsersLPw();
2543
2544            if (!mOnlyCore) {
2545                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2546                        SystemClock.uptimeMillis());
2547                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2548
2549                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2550                        | PackageParser.PARSE_FORWARD_LOCK,
2551                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2552
2553                /**
2554                 * Remove disable package settings for any updated system
2555                 * apps that were removed via an OTA. If they're not a
2556                 * previously-updated app, remove them completely.
2557                 * Otherwise, just revoke their system-level permissions.
2558                 */
2559                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2560                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2561                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2562
2563                    String msg;
2564                    if (deletedPkg == null) {
2565                        msg = "Updated system package " + deletedAppName
2566                                + " no longer exists; it's data will be wiped";
2567                        // Actual deletion of code and data will be handled by later
2568                        // reconciliation step
2569                    } else {
2570                        msg = "Updated system app + " + deletedAppName
2571                                + " no longer present; removing system privileges for "
2572                                + deletedAppName;
2573
2574                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2575
2576                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2577                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2578                    }
2579                    logCriticalInfo(Log.WARN, msg);
2580                }
2581
2582                /**
2583                 * Make sure all system apps that we expected to appear on
2584                 * the userdata partition actually showed up. If they never
2585                 * appeared, crawl back and revive the system version.
2586                 */
2587                for (int i = 0; i < mExpectingBetter.size(); i++) {
2588                    final String packageName = mExpectingBetter.keyAt(i);
2589                    if (!mPackages.containsKey(packageName)) {
2590                        final File scanFile = mExpectingBetter.valueAt(i);
2591
2592                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2593                                + " but never showed up; reverting to system");
2594
2595                        int reparseFlags = mDefParseFlags;
2596                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2597                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2598                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2599                                    | PackageParser.PARSE_IS_PRIVILEGED;
2600                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2601                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2602                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2603                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2604                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2605                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2606                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2607                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2608                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2609                        } else {
2610                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2611                            continue;
2612                        }
2613
2614                        mSettings.enableSystemPackageLPw(packageName);
2615
2616                        try {
2617                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2618                        } catch (PackageManagerException e) {
2619                            Slog.e(TAG, "Failed to parse original system package: "
2620                                    + e.getMessage());
2621                        }
2622                    }
2623                }
2624            }
2625            mExpectingBetter.clear();
2626
2627            // Resolve the storage manager.
2628            mStorageManagerPackage = getStorageManagerPackageName();
2629
2630            // Resolve protected action filters. Only the setup wizard is allowed to
2631            // have a high priority filter for these actions.
2632            mSetupWizardPackage = getSetupWizardPackageName();
2633            if (mProtectedFilters.size() > 0) {
2634                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2635                    Slog.i(TAG, "No setup wizard;"
2636                        + " All protected intents capped to priority 0");
2637                }
2638                for (ActivityIntentInfo filter : mProtectedFilters) {
2639                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2640                        if (DEBUG_FILTERS) {
2641                            Slog.i(TAG, "Found setup wizard;"
2642                                + " allow priority " + filter.getPriority() + ";"
2643                                + " package: " + filter.activity.info.packageName
2644                                + " activity: " + filter.activity.className
2645                                + " priority: " + filter.getPriority());
2646                        }
2647                        // skip setup wizard; allow it to keep the high priority filter
2648                        continue;
2649                    }
2650                    Slog.w(TAG, "Protected action; cap priority to 0;"
2651                            + " package: " + filter.activity.info.packageName
2652                            + " activity: " + filter.activity.className
2653                            + " origPrio: " + filter.getPriority());
2654                    filter.setPriority(0);
2655                }
2656            }
2657            mDeferProtectedFilters = false;
2658            mProtectedFilters.clear();
2659
2660            // Now that we know all of the shared libraries, update all clients to have
2661            // the correct library paths.
2662            updateAllSharedLibrariesLPw(null);
2663
2664            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2665                // NOTE: We ignore potential failures here during a system scan (like
2666                // the rest of the commands above) because there's precious little we
2667                // can do about it. A settings error is reported, though.
2668                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2669            }
2670
2671            // Now that we know all the packages we are keeping,
2672            // read and update their last usage times.
2673            mPackageUsage.read(mPackages);
2674            mCompilerStats.read();
2675
2676            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2677                    SystemClock.uptimeMillis());
2678            Slog.i(TAG, "Time to scan packages: "
2679                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2680                    + " seconds");
2681
2682            // If the platform SDK has changed since the last time we booted,
2683            // we need to re-grant app permission to catch any new ones that
2684            // appear.  This is really a hack, and means that apps can in some
2685            // cases get permissions that the user didn't initially explicitly
2686            // allow...  it would be nice to have some better way to handle
2687            // this situation.
2688            int updateFlags = UPDATE_PERMISSIONS_ALL;
2689            if (ver.sdkVersion != mSdkVersion) {
2690                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2691                        + mSdkVersion + "; regranting permissions for internal storage");
2692                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2693            }
2694            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2695            ver.sdkVersion = mSdkVersion;
2696
2697            // If this is the first boot or an update from pre-M, and it is a normal
2698            // boot, then we need to initialize the default preferred apps across
2699            // all defined users.
2700            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2701                for (UserInfo user : sUserManager.getUsers(true)) {
2702                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2703                    applyFactoryDefaultBrowserLPw(user.id);
2704                    primeDomainVerificationsLPw(user.id);
2705                }
2706            }
2707
2708            // Prepare storage for system user really early during boot,
2709            // since core system apps like SettingsProvider and SystemUI
2710            // can't wait for user to start
2711            final int storageFlags;
2712            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2713                storageFlags = StorageManager.FLAG_STORAGE_DE;
2714            } else {
2715                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2716            }
2717            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2718                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2719                    true /* onlyCoreApps */);
2720            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2721                if (deferPackages == null || deferPackages.isEmpty()) {
2722                    return;
2723                }
2724                int count = 0;
2725                for (String pkgName : deferPackages) {
2726                    PackageParser.Package pkg = null;
2727                    synchronized (mPackages) {
2728                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2729                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2730                            pkg = ps.pkg;
2731                        }
2732                    }
2733                    if (pkg != null) {
2734                        synchronized (mInstallLock) {
2735                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2736                                    true /* maybeMigrateAppData */);
2737                        }
2738                        count++;
2739                    }
2740                }
2741                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2742            }, "prepareAppData");
2743
2744            // If this is first boot after an OTA, and a normal boot, then
2745            // we need to clear code cache directories.
2746            // Note that we do *not* clear the application profiles. These remain valid
2747            // across OTAs and are used to drive profile verification (post OTA) and
2748            // profile compilation (without waiting to collect a fresh set of profiles).
2749            if (mIsUpgrade && !onlyCore) {
2750                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2751                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2752                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2753                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2754                        // No apps are running this early, so no need to freeze
2755                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2756                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2757                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2758                    }
2759                }
2760                ver.fingerprint = Build.FINGERPRINT;
2761            }
2762
2763            checkDefaultBrowser();
2764
2765            // clear only after permissions and other defaults have been updated
2766            mExistingSystemPackages.clear();
2767            mPromoteSystemApps = false;
2768
2769            // All the changes are done during package scanning.
2770            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2771
2772            // can downgrade to reader
2773            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2774            mSettings.writeLPr();
2775            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2776
2777            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2778                    SystemClock.uptimeMillis());
2779
2780            if (!mOnlyCore) {
2781                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2782                mRequiredInstallerPackage = getRequiredInstallerLPr();
2783                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2784                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2785                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2786                        mIntentFilterVerifierComponent);
2787                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2788                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2789                        SharedLibraryInfo.VERSION_UNDEFINED);
2790                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2791                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2792                        SharedLibraryInfo.VERSION_UNDEFINED);
2793            } else {
2794                mRequiredVerifierPackage = null;
2795                mRequiredInstallerPackage = null;
2796                mRequiredUninstallerPackage = null;
2797                mIntentFilterVerifierComponent = null;
2798                mIntentFilterVerifier = null;
2799                mServicesSystemSharedLibraryPackageName = null;
2800                mSharedSystemSharedLibraryPackageName = null;
2801            }
2802
2803            mInstallerService = new PackageInstallerService(context, this);
2804            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2805            if (ephemeralResolverComponent != null) {
2806                if (DEBUG_EPHEMERAL) {
2807                    Slog.d(TAG, "Set ephemeral resolver: " + ephemeralResolverComponent);
2808                }
2809                mInstantAppResolverConnection =
2810                        new EphemeralResolverConnection(mContext, ephemeralResolverComponent);
2811            } else {
2812                mInstantAppResolverConnection = null;
2813            }
2814            updateInstantAppInstallerLocked();
2815            mInstantAppResolverSettingsComponent = getEphemeralResolverSettingsLPr();
2816
2817            // Read and update the usage of dex files.
2818            // Do this at the end of PM init so that all the packages have their
2819            // data directory reconciled.
2820            // At this point we know the code paths of the packages, so we can validate
2821            // the disk file and build the internal cache.
2822            // The usage file is expected to be small so loading and verifying it
2823            // should take a fairly small time compare to the other activities (e.g. package
2824            // scanning).
2825            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2826            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2827            for (int userId : currentUserIds) {
2828                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2829            }
2830            mDexManager.load(userPackages);
2831        } // synchronized (mPackages)
2832        } // synchronized (mInstallLock)
2833
2834        // Now after opening every single application zip, make sure they
2835        // are all flushed.  Not really needed, but keeps things nice and
2836        // tidy.
2837        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2838        Runtime.getRuntime().gc();
2839        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2840
2841        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2842        FallbackCategoryProvider.loadFallbacks();
2843        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2844
2845        // The initial scanning above does many calls into installd while
2846        // holding the mPackages lock, but we're mostly interested in yelling
2847        // once we have a booted system.
2848        mInstaller.setWarnIfHeld(mPackages);
2849
2850        // Expose private service for system components to use.
2851        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2852        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2853    }
2854
2855    private void updateInstantAppInstallerLocked() {
2856        final ComponentName oldInstantAppInstallerComponent = mInstantAppInstallerComponent;
2857        final ActivityInfo newInstantAppInstaller = getEphemeralInstallerLPr();
2858        ComponentName newInstantAppInstallerComponent = newInstantAppInstaller == null
2859                ? null : newInstantAppInstaller.getComponentName();
2860
2861        if (newInstantAppInstallerComponent != null
2862                && !newInstantAppInstallerComponent.equals(oldInstantAppInstallerComponent)) {
2863            if (DEBUG_EPHEMERAL) {
2864                Slog.d(TAG, "Set ephemeral installer: " + newInstantAppInstallerComponent);
2865            }
2866            setUpInstantAppInstallerActivityLP(newInstantAppInstaller);
2867        } else if (DEBUG_EPHEMERAL && newInstantAppInstallerComponent == null) {
2868            Slog.d(TAG, "Unset ephemeral installer; none available");
2869        }
2870        mInstantAppInstallerComponent = newInstantAppInstallerComponent;
2871    }
2872
2873    private static File preparePackageParserCache(boolean isUpgrade) {
2874        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2875            return null;
2876        }
2877
2878        // Disable package parsing on eng builds to allow for faster incremental development.
2879        if ("eng".equals(Build.TYPE)) {
2880            return null;
2881        }
2882
2883        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2884            Slog.i(TAG, "Disabling package parser cache due to system property.");
2885            return null;
2886        }
2887
2888        // The base directory for the package parser cache lives under /data/system/.
2889        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2890                "package_cache");
2891        if (cacheBaseDir == null) {
2892            return null;
2893        }
2894
2895        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2896        // This also serves to "GC" unused entries when the package cache version changes (which
2897        // can only happen during upgrades).
2898        if (isUpgrade) {
2899            FileUtils.deleteContents(cacheBaseDir);
2900        }
2901
2902
2903        // Return the versioned package cache directory. This is something like
2904        // "/data/system/package_cache/1"
2905        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2906
2907        // The following is a workaround to aid development on non-numbered userdebug
2908        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2909        // the system partition is newer.
2910        //
2911        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2912        // that starts with "eng." to signify that this is an engineering build and not
2913        // destined for release.
2914        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2915            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2916
2917            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2918            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2919            // in general and should not be used for production changes. In this specific case,
2920            // we know that they will work.
2921            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2922            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
2923                FileUtils.deleteContents(cacheBaseDir);
2924                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2925            }
2926        }
2927
2928        return cacheDir;
2929    }
2930
2931    @Override
2932    public boolean isFirstBoot() {
2933        return mFirstBoot;
2934    }
2935
2936    @Override
2937    public boolean isOnlyCoreApps() {
2938        return mOnlyCore;
2939    }
2940
2941    @Override
2942    public boolean isUpgrade() {
2943        return mIsUpgrade;
2944    }
2945
2946    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2947        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2948
2949        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2950                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2951                UserHandle.USER_SYSTEM);
2952        if (matches.size() == 1) {
2953            return matches.get(0).getComponentInfo().packageName;
2954        } else if (matches.size() == 0) {
2955            Log.e(TAG, "There should probably be a verifier, but, none were found");
2956            return null;
2957        }
2958        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2959    }
2960
2961    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
2962        synchronized (mPackages) {
2963            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
2964            if (libraryEntry == null) {
2965                throw new IllegalStateException("Missing required shared library:" + name);
2966            }
2967            return libraryEntry.apk;
2968        }
2969    }
2970
2971    private @NonNull String getRequiredInstallerLPr() {
2972        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2973        intent.addCategory(Intent.CATEGORY_DEFAULT);
2974        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2975
2976        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2977                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2978                UserHandle.USER_SYSTEM);
2979        if (matches.size() == 1) {
2980            ResolveInfo resolveInfo = matches.get(0);
2981            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2982                throw new RuntimeException("The installer must be a privileged app");
2983            }
2984            return matches.get(0).getComponentInfo().packageName;
2985        } else {
2986            throw new RuntimeException("There must be exactly one installer; found " + matches);
2987        }
2988    }
2989
2990    private @NonNull String getRequiredUninstallerLPr() {
2991        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2992        intent.addCategory(Intent.CATEGORY_DEFAULT);
2993        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2994
2995        final ResolveInfo resolveInfo = resolveIntent(intent, null,
2996                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2997                UserHandle.USER_SYSTEM);
2998        if (resolveInfo == null ||
2999                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3000            throw new RuntimeException("There must be exactly one uninstaller; found "
3001                    + resolveInfo);
3002        }
3003        return resolveInfo.getComponentInfo().packageName;
3004    }
3005
3006    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3007        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3008
3009        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3010                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3011                UserHandle.USER_SYSTEM);
3012        ResolveInfo best = null;
3013        final int N = matches.size();
3014        for (int i = 0; i < N; i++) {
3015            final ResolveInfo cur = matches.get(i);
3016            final String packageName = cur.getComponentInfo().packageName;
3017            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3018                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3019                continue;
3020            }
3021
3022            if (best == null || cur.priority > best.priority) {
3023                best = cur;
3024            }
3025        }
3026
3027        if (best != null) {
3028            return best.getComponentInfo().getComponentName();
3029        } else {
3030            throw new RuntimeException("There must be at least one intent filter verifier");
3031        }
3032    }
3033
3034    private @Nullable ComponentName getEphemeralResolverLPr() {
3035        final String[] packageArray =
3036                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3037        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3038            if (DEBUG_EPHEMERAL) {
3039                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3040            }
3041            return null;
3042        }
3043
3044        final int callingUid = Binder.getCallingUid();
3045        final int resolveFlags =
3046                MATCH_DIRECT_BOOT_AWARE
3047                | MATCH_DIRECT_BOOT_UNAWARE
3048                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3049        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
3050        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3051                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3052
3053        final int N = resolvers.size();
3054        if (N == 0) {
3055            if (DEBUG_EPHEMERAL) {
3056                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3057            }
3058            return null;
3059        }
3060
3061        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3062        for (int i = 0; i < N; i++) {
3063            final ResolveInfo info = resolvers.get(i);
3064
3065            if (info.serviceInfo == null) {
3066                continue;
3067            }
3068
3069            final String packageName = info.serviceInfo.packageName;
3070            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3071                if (DEBUG_EPHEMERAL) {
3072                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3073                            + " pkg: " + packageName + ", info:" + info);
3074                }
3075                continue;
3076            }
3077
3078            if (DEBUG_EPHEMERAL) {
3079                Slog.v(TAG, "Ephemeral resolver found;"
3080                        + " pkg: " + packageName + ", info:" + info);
3081            }
3082            return new ComponentName(packageName, info.serviceInfo.name);
3083        }
3084        if (DEBUG_EPHEMERAL) {
3085            Slog.v(TAG, "Ephemeral resolver NOT found");
3086        }
3087        return null;
3088    }
3089
3090    private @Nullable ActivityInfo getEphemeralInstallerLPr() {
3091        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3092        intent.addCategory(Intent.CATEGORY_DEFAULT);
3093        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3094
3095        final int resolveFlags =
3096                MATCH_DIRECT_BOOT_AWARE
3097                | MATCH_DIRECT_BOOT_UNAWARE
3098                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3099        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3100                resolveFlags, UserHandle.USER_SYSTEM);
3101        Iterator<ResolveInfo> iter = matches.iterator();
3102        while (iter.hasNext()) {
3103            final ResolveInfo rInfo = iter.next();
3104            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3105            if (ps != null) {
3106                final PermissionsState permissionsState = ps.getPermissionsState();
3107                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3108                    continue;
3109                }
3110            }
3111            iter.remove();
3112        }
3113        if (matches.size() == 0) {
3114            return null;
3115        } else if (matches.size() == 1) {
3116            return (ActivityInfo) matches.get(0).getComponentInfo();
3117        } else {
3118            throw new RuntimeException(
3119                    "There must be at most one ephemeral installer; found " + matches);
3120        }
3121    }
3122
3123    private @Nullable ComponentName getEphemeralResolverSettingsLPr() {
3124        final Intent intent = new Intent(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3125        intent.addCategory(Intent.CATEGORY_DEFAULT);
3126        final int resolveFlags =
3127                MATCH_DIRECT_BOOT_AWARE
3128                | MATCH_DIRECT_BOOT_UNAWARE
3129                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3130        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
3131                resolveFlags, UserHandle.USER_SYSTEM);
3132        Iterator<ResolveInfo> iter = matches.iterator();
3133        while (iter.hasNext()) {
3134            final ResolveInfo rInfo = iter.next();
3135            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3136            if (ps != null) {
3137                final PermissionsState permissionsState = ps.getPermissionsState();
3138                if (permissionsState.hasPermission(Manifest.permission.ACCESS_INSTANT_APPS, 0)) {
3139                    continue;
3140                }
3141            }
3142            iter.remove();
3143        }
3144        if (matches.size() == 0) {
3145            return null;
3146        } else if (matches.size() == 1) {
3147            return matches.get(0).getComponentInfo().getComponentName();
3148        } else {
3149            throw new RuntimeException(
3150                    "There must be at most one ephemeral resolver settings; found " + matches);
3151        }
3152    }
3153
3154    private void primeDomainVerificationsLPw(int userId) {
3155        if (DEBUG_DOMAIN_VERIFICATION) {
3156            Slog.d(TAG, "Priming domain verifications in user " + userId);
3157        }
3158
3159        SystemConfig systemConfig = SystemConfig.getInstance();
3160        ArraySet<String> packages = systemConfig.getLinkedApps();
3161
3162        for (String packageName : packages) {
3163            PackageParser.Package pkg = mPackages.get(packageName);
3164            if (pkg != null) {
3165                if (!pkg.isSystemApp()) {
3166                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3167                    continue;
3168                }
3169
3170                ArraySet<String> domains = null;
3171                for (PackageParser.Activity a : pkg.activities) {
3172                    for (ActivityIntentInfo filter : a.intents) {
3173                        if (hasValidDomains(filter)) {
3174                            if (domains == null) {
3175                                domains = new ArraySet<String>();
3176                            }
3177                            domains.addAll(filter.getHostsList());
3178                        }
3179                    }
3180                }
3181
3182                if (domains != null && domains.size() > 0) {
3183                    if (DEBUG_DOMAIN_VERIFICATION) {
3184                        Slog.v(TAG, "      + " + packageName);
3185                    }
3186                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3187                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3188                    // and then 'always' in the per-user state actually used for intent resolution.
3189                    final IntentFilterVerificationInfo ivi;
3190                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3191                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3192                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3193                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3194                } else {
3195                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3196                            + "' does not handle web links");
3197                }
3198            } else {
3199                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3200            }
3201        }
3202
3203        scheduleWritePackageRestrictionsLocked(userId);
3204        scheduleWriteSettingsLocked();
3205    }
3206
3207    private void applyFactoryDefaultBrowserLPw(int userId) {
3208        // The default browser app's package name is stored in a string resource,
3209        // with a product-specific overlay used for vendor customization.
3210        String browserPkg = mContext.getResources().getString(
3211                com.android.internal.R.string.default_browser);
3212        if (!TextUtils.isEmpty(browserPkg)) {
3213            // non-empty string => required to be a known package
3214            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3215            if (ps == null) {
3216                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3217                browserPkg = null;
3218            } else {
3219                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3220            }
3221        }
3222
3223        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3224        // default.  If there's more than one, just leave everything alone.
3225        if (browserPkg == null) {
3226            calculateDefaultBrowserLPw(userId);
3227        }
3228    }
3229
3230    private void calculateDefaultBrowserLPw(int userId) {
3231        List<String> allBrowsers = resolveAllBrowserApps(userId);
3232        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3233        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3234    }
3235
3236    private List<String> resolveAllBrowserApps(int userId) {
3237        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3238        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3239                PackageManager.MATCH_ALL, userId);
3240
3241        final int count = list.size();
3242        List<String> result = new ArrayList<String>(count);
3243        for (int i=0; i<count; i++) {
3244            ResolveInfo info = list.get(i);
3245            if (info.activityInfo == null
3246                    || !info.handleAllWebDataURI
3247                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3248                    || result.contains(info.activityInfo.packageName)) {
3249                continue;
3250            }
3251            result.add(info.activityInfo.packageName);
3252        }
3253
3254        return result;
3255    }
3256
3257    private boolean packageIsBrowser(String packageName, int userId) {
3258        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3259                PackageManager.MATCH_ALL, userId);
3260        final int N = list.size();
3261        for (int i = 0; i < N; i++) {
3262            ResolveInfo info = list.get(i);
3263            if (packageName.equals(info.activityInfo.packageName)) {
3264                return true;
3265            }
3266        }
3267        return false;
3268    }
3269
3270    private void checkDefaultBrowser() {
3271        final int myUserId = UserHandle.myUserId();
3272        final String packageName = getDefaultBrowserPackageName(myUserId);
3273        if (packageName != null) {
3274            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3275            if (info == null) {
3276                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3277                synchronized (mPackages) {
3278                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3279                }
3280            }
3281        }
3282    }
3283
3284    @Override
3285    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3286            throws RemoteException {
3287        try {
3288            return super.onTransact(code, data, reply, flags);
3289        } catch (RuntimeException e) {
3290            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3291                Slog.wtf(TAG, "Package Manager Crash", e);
3292            }
3293            throw e;
3294        }
3295    }
3296
3297    static int[] appendInts(int[] cur, int[] add) {
3298        if (add == null) return cur;
3299        if (cur == null) return add;
3300        final int N = add.length;
3301        for (int i=0; i<N; i++) {
3302            cur = appendInt(cur, add[i]);
3303        }
3304        return cur;
3305    }
3306
3307    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3308        if (!sUserManager.exists(userId)) return null;
3309        if (ps == null) {
3310            return null;
3311        }
3312        final PackageParser.Package p = ps.pkg;
3313        if (p == null) {
3314            return null;
3315        }
3316        // Filter out ephemeral app metadata:
3317        //   * The system/shell/root can see metadata for any app
3318        //   * An installed app can see metadata for 1) other installed apps
3319        //     and 2) ephemeral apps that have explicitly interacted with it
3320        //   * Ephemeral apps can only see their own data and exposed installed apps
3321        //   * Holding a signature permission allows seeing instant apps
3322        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3323        if (callingAppId != Process.SYSTEM_UID
3324                && callingAppId != Process.SHELL_UID
3325                && callingAppId != Process.ROOT_UID
3326                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3327                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3328            final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid());
3329            if (instantAppPackageName != null) {
3330                // ephemeral apps can only get information on themselves or
3331                // installed apps that are exposed.
3332                if (!instantAppPackageName.equals(p.packageName)
3333                        && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) {
3334                    return null;
3335                }
3336            } else {
3337                if (ps.getInstantApp(userId)) {
3338                    // only get access to the ephemeral app if we've been granted access
3339                    if (!mInstantAppRegistry.isInstantAccessGranted(
3340                            userId, callingAppId, ps.appId)) {
3341                        return null;
3342                    }
3343                }
3344            }
3345        }
3346
3347        final PermissionsState permissionsState = ps.getPermissionsState();
3348
3349        // Compute GIDs only if requested
3350        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3351                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3352        // Compute granted permissions only if package has requested permissions
3353        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3354                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3355        final PackageUserState state = ps.readUserState(userId);
3356
3357        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3358                && ps.isSystem()) {
3359            flags |= MATCH_ANY_USER;
3360        }
3361
3362        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3363                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3364
3365        if (packageInfo == null) {
3366            return null;
3367        }
3368
3369        rebaseEnabledOverlays(packageInfo.applicationInfo, userId);
3370
3371        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3372                resolveExternalPackageNameLPr(p);
3373
3374        return packageInfo;
3375    }
3376
3377    @Override
3378    public void checkPackageStartable(String packageName, int userId) {
3379        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3380
3381        synchronized (mPackages) {
3382            final PackageSetting ps = mSettings.mPackages.get(packageName);
3383            if (ps == null) {
3384                throw new SecurityException("Package " + packageName + " was not found!");
3385            }
3386
3387            if (!ps.getInstalled(userId)) {
3388                throw new SecurityException(
3389                        "Package " + packageName + " was not installed for user " + userId + "!");
3390            }
3391
3392            if (mSafeMode && !ps.isSystem()) {
3393                throw new SecurityException("Package " + packageName + " not a system app!");
3394            }
3395
3396            if (mFrozenPackages.contains(packageName)) {
3397                throw new SecurityException("Package " + packageName + " is currently frozen!");
3398            }
3399
3400            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3401                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3402                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3403            }
3404        }
3405    }
3406
3407    @Override
3408    public boolean isPackageAvailable(String packageName, int userId) {
3409        if (!sUserManager.exists(userId)) return false;
3410        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3411                false /* requireFullPermission */, false /* checkShell */, "is package available");
3412        synchronized (mPackages) {
3413            PackageParser.Package p = mPackages.get(packageName);
3414            if (p != null) {
3415                final PackageSetting ps = (PackageSetting) p.mExtras;
3416                if (ps != null) {
3417                    final PackageUserState state = ps.readUserState(userId);
3418                    if (state != null) {
3419                        return PackageParser.isAvailable(state);
3420                    }
3421                }
3422            }
3423        }
3424        return false;
3425    }
3426
3427    @Override
3428    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3429        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3430                flags, userId);
3431    }
3432
3433    @Override
3434    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3435            int flags, int userId) {
3436        return getPackageInfoInternal(versionedPackage.getPackageName(),
3437                // TODO: We will change version code to long, so in the new API it is long
3438                (int) versionedPackage.getVersionCode(), flags, userId);
3439    }
3440
3441    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3442            int flags, int userId) {
3443        if (!sUserManager.exists(userId)) return null;
3444        flags = updateFlagsForPackage(flags, userId, packageName);
3445        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3446                false /* requireFullPermission */, false /* checkShell */, "get package info");
3447
3448        // reader
3449        synchronized (mPackages) {
3450            // Normalize package name to handle renamed packages and static libs
3451            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3452
3453            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3454            if (matchFactoryOnly) {
3455                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3456                if (ps != null) {
3457                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3458                        return null;
3459                    }
3460                    return generatePackageInfo(ps, flags, userId);
3461                }
3462            }
3463
3464            PackageParser.Package p = mPackages.get(packageName);
3465            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3466                return null;
3467            }
3468            if (DEBUG_PACKAGE_INFO)
3469                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3470            if (p != null) {
3471                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3472                        Binder.getCallingUid(), userId)) {
3473                    return null;
3474                }
3475                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3476            }
3477            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3478                final PackageSetting ps = mSettings.mPackages.get(packageName);
3479                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3480                    return null;
3481                }
3482                return generatePackageInfo(ps, flags, userId);
3483            }
3484        }
3485        return null;
3486    }
3487
3488
3489    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) {
3490        // System/shell/root get to see all static libs
3491        final int appId = UserHandle.getAppId(uid);
3492        if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3493                || appId == Process.ROOT_UID) {
3494            return false;
3495        }
3496
3497        // No package means no static lib as it is always on internal storage
3498        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3499            return false;
3500        }
3501
3502        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3503                ps.pkg.staticSharedLibVersion);
3504        if (libEntry == null) {
3505            return false;
3506        }
3507
3508        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3509        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3510        if (uidPackageNames == null) {
3511            return true;
3512        }
3513
3514        for (String uidPackageName : uidPackageNames) {
3515            if (ps.name.equals(uidPackageName)) {
3516                return false;
3517            }
3518            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3519            if (uidPs != null) {
3520                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3521                        libEntry.info.getName());
3522                if (index < 0) {
3523                    continue;
3524                }
3525                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3526                    return false;
3527                }
3528            }
3529        }
3530        return true;
3531    }
3532
3533    @Override
3534    public String[] currentToCanonicalPackageNames(String[] names) {
3535        String[] out = new String[names.length];
3536        // reader
3537        synchronized (mPackages) {
3538            for (int i=names.length-1; i>=0; i--) {
3539                PackageSetting ps = mSettings.mPackages.get(names[i]);
3540                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3541            }
3542        }
3543        return out;
3544    }
3545
3546    @Override
3547    public String[] canonicalToCurrentPackageNames(String[] names) {
3548        String[] out = new String[names.length];
3549        // reader
3550        synchronized (mPackages) {
3551            for (int i=names.length-1; i>=0; i--) {
3552                String cur = mSettings.getRenamedPackageLPr(names[i]);
3553                out[i] = cur != null ? cur : names[i];
3554            }
3555        }
3556        return out;
3557    }
3558
3559    @Override
3560    public int getPackageUid(String packageName, int flags, int userId) {
3561        if (!sUserManager.exists(userId)) return -1;
3562        flags = updateFlagsForPackage(flags, userId, packageName);
3563        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3564                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3565
3566        // reader
3567        synchronized (mPackages) {
3568            final PackageParser.Package p = mPackages.get(packageName);
3569            if (p != null && p.isMatch(flags)) {
3570                return UserHandle.getUid(userId, p.applicationInfo.uid);
3571            }
3572            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3573                final PackageSetting ps = mSettings.mPackages.get(packageName);
3574                if (ps != null && ps.isMatch(flags)) {
3575                    return UserHandle.getUid(userId, ps.appId);
3576                }
3577            }
3578        }
3579
3580        return -1;
3581    }
3582
3583    @Override
3584    public int[] getPackageGids(String packageName, int flags, int userId) {
3585        if (!sUserManager.exists(userId)) return null;
3586        flags = updateFlagsForPackage(flags, userId, packageName);
3587        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3588                false /* requireFullPermission */, false /* checkShell */,
3589                "getPackageGids");
3590
3591        // reader
3592        synchronized (mPackages) {
3593            final PackageParser.Package p = mPackages.get(packageName);
3594            if (p != null && p.isMatch(flags)) {
3595                PackageSetting ps = (PackageSetting) p.mExtras;
3596                // TODO: Shouldn't this be checking for package installed state for userId and
3597                // return null?
3598                return ps.getPermissionsState().computeGids(userId);
3599            }
3600            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3601                final PackageSetting ps = mSettings.mPackages.get(packageName);
3602                if (ps != null && ps.isMatch(flags)) {
3603                    return ps.getPermissionsState().computeGids(userId);
3604                }
3605            }
3606        }
3607
3608        return null;
3609    }
3610
3611    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3612        if (bp.perm != null) {
3613            return PackageParser.generatePermissionInfo(bp.perm, flags);
3614        }
3615        PermissionInfo pi = new PermissionInfo();
3616        pi.name = bp.name;
3617        pi.packageName = bp.sourcePackage;
3618        pi.nonLocalizedLabel = bp.name;
3619        pi.protectionLevel = bp.protectionLevel;
3620        return pi;
3621    }
3622
3623    @Override
3624    public PermissionInfo getPermissionInfo(String name, int flags) {
3625        // reader
3626        synchronized (mPackages) {
3627            final BasePermission p = mSettings.mPermissions.get(name);
3628            if (p != null) {
3629                return generatePermissionInfo(p, flags);
3630            }
3631            return null;
3632        }
3633    }
3634
3635    @Override
3636    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3637            int flags) {
3638        // reader
3639        synchronized (mPackages) {
3640            if (group != null && !mPermissionGroups.containsKey(group)) {
3641                // This is thrown as NameNotFoundException
3642                return null;
3643            }
3644
3645            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3646            for (BasePermission p : mSettings.mPermissions.values()) {
3647                if (group == null) {
3648                    if (p.perm == null || p.perm.info.group == null) {
3649                        out.add(generatePermissionInfo(p, flags));
3650                    }
3651                } else {
3652                    if (p.perm != null && group.equals(p.perm.info.group)) {
3653                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3654                    }
3655                }
3656            }
3657            return new ParceledListSlice<>(out);
3658        }
3659    }
3660
3661    @Override
3662    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3663        // reader
3664        synchronized (mPackages) {
3665            return PackageParser.generatePermissionGroupInfo(
3666                    mPermissionGroups.get(name), flags);
3667        }
3668    }
3669
3670    @Override
3671    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3672        // reader
3673        synchronized (mPackages) {
3674            final int N = mPermissionGroups.size();
3675            ArrayList<PermissionGroupInfo> out
3676                    = new ArrayList<PermissionGroupInfo>(N);
3677            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3678                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3679            }
3680            return new ParceledListSlice<>(out);
3681        }
3682    }
3683
3684    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3685            int uid, int userId) {
3686        if (!sUserManager.exists(userId)) return null;
3687        PackageSetting ps = mSettings.mPackages.get(packageName);
3688        if (ps != null) {
3689            if (filterSharedLibPackageLPr(ps, uid, userId)) {
3690                return null;
3691            }
3692            if (ps.pkg == null) {
3693                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3694                if (pInfo != null) {
3695                    return pInfo.applicationInfo;
3696                }
3697                return null;
3698            }
3699            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3700                    ps.readUserState(userId), userId);
3701            if (ai != null) {
3702                rebaseEnabledOverlays(ai, userId);
3703                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3704            }
3705            return ai;
3706        }
3707        return null;
3708    }
3709
3710    @Override
3711    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3712        if (!sUserManager.exists(userId)) return null;
3713        flags = updateFlagsForApplication(flags, userId, packageName);
3714        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3715                false /* requireFullPermission */, false /* checkShell */, "get application info");
3716
3717        // writer
3718        synchronized (mPackages) {
3719            // Normalize package name to handle renamed packages and static libs
3720            packageName = resolveInternalPackageNameLPr(packageName,
3721                    PackageManager.VERSION_CODE_HIGHEST);
3722
3723            PackageParser.Package p = mPackages.get(packageName);
3724            if (DEBUG_PACKAGE_INFO) Log.v(
3725                    TAG, "getApplicationInfo " + packageName
3726                    + ": " + p);
3727            if (p != null) {
3728                PackageSetting ps = mSettings.mPackages.get(packageName);
3729                if (ps == null) return null;
3730                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3731                    return null;
3732                }
3733                // Note: isEnabledLP() does not apply here - always return info
3734                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3735                        p, flags, ps.readUserState(userId), userId);
3736                if (ai != null) {
3737                    rebaseEnabledOverlays(ai, userId);
3738                    ai.packageName = resolveExternalPackageNameLPr(p);
3739                }
3740                return ai;
3741            }
3742            if ("android".equals(packageName)||"system".equals(packageName)) {
3743                return mAndroidApplication;
3744            }
3745            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3746                // Already generates the external package name
3747                return generateApplicationInfoFromSettingsLPw(packageName,
3748                        Binder.getCallingUid(), flags, userId);
3749            }
3750        }
3751        return null;
3752    }
3753
3754    private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) {
3755        List<String> paths = new ArrayList<>();
3756        ArrayMap<String, ArrayList<String>> userSpecificOverlays =
3757            mEnabledOverlayPaths.get(userId);
3758        if (userSpecificOverlays != null) {
3759            if (!"android".equals(ai.packageName)) {
3760                ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android");
3761                if (frameworkOverlays != null) {
3762                    paths.addAll(frameworkOverlays);
3763                }
3764            }
3765
3766            ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName);
3767            if (appOverlays != null) {
3768                paths.addAll(appOverlays);
3769            }
3770        }
3771        ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null;
3772    }
3773
3774    private String normalizePackageNameLPr(String packageName) {
3775        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3776        return normalizedPackageName != null ? normalizedPackageName : packageName;
3777    }
3778
3779    @Override
3780    public void deletePreloadsFileCache() {
3781        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
3782            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
3783        }
3784        File dir = Environment.getDataPreloadsFileCacheDirectory();
3785        Slog.i(TAG, "Deleting preloaded file cache " + dir);
3786        FileUtils.deleteContents(dir);
3787    }
3788
3789    @Override
3790    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3791            final IPackageDataObserver observer) {
3792        mContext.enforceCallingOrSelfPermission(
3793                android.Manifest.permission.CLEAR_APP_CACHE, null);
3794        mHandler.post(() -> {
3795            boolean success = false;
3796            try {
3797                freeStorage(volumeUuid, freeStorageSize, 0);
3798                success = true;
3799            } catch (IOException e) {
3800                Slog.w(TAG, e);
3801            }
3802            if (observer != null) {
3803                try {
3804                    observer.onRemoveCompleted(null, success);
3805                } catch (RemoteException e) {
3806                    Slog.w(TAG, e);
3807                }
3808            }
3809        });
3810    }
3811
3812    @Override
3813    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3814            final IntentSender pi) {
3815        mContext.enforceCallingOrSelfPermission(
3816                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
3817        mHandler.post(() -> {
3818            boolean success = false;
3819            try {
3820                freeStorage(volumeUuid, freeStorageSize, 0);
3821                success = true;
3822            } catch (IOException e) {
3823                Slog.w(TAG, e);
3824            }
3825            if (pi != null) {
3826                try {
3827                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
3828                } catch (SendIntentException e) {
3829                    Slog.w(TAG, e);
3830                }
3831            }
3832        });
3833    }
3834
3835    /**
3836     * Blocking call to clear various types of cached data across the system
3837     * until the requested bytes are available.
3838     */
3839    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
3840        final StorageManager storage = mContext.getSystemService(StorageManager.class);
3841        final File file = storage.findPathForUuid(volumeUuid);
3842        if (file.getUsableSpace() >= bytes) return;
3843
3844        if (ENABLE_FREE_CACHE_V2) {
3845            final boolean aggressive = (storageFlags
3846                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
3847            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
3848                    volumeUuid);
3849
3850            // 1. Pre-flight to determine if we have any chance to succeed
3851            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
3852            if (internalVolume && (aggressive || SystemProperties
3853                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
3854                deletePreloadsFileCache();
3855                if (file.getUsableSpace() >= bytes) return;
3856            }
3857
3858            // 3. Consider parsed APK data (aggressive only)
3859            if (internalVolume && aggressive) {
3860                FileUtils.deleteContents(mCacheDir);
3861                if (file.getUsableSpace() >= bytes) return;
3862            }
3863
3864            // 4. Consider cached app data (above quotas)
3865            try {
3866                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2);
3867            } catch (InstallerException ignored) {
3868            }
3869            if (file.getUsableSpace() >= bytes) return;
3870
3871            // 5. Consider shared libraries with refcount=0 and age>2h
3872            // 6. Consider dexopt output (aggressive only)
3873            // 7. Consider ephemeral apps not used in last week
3874
3875            // 8. Consider cached app data (below quotas)
3876            try {
3877                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2
3878                        | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
3879            } catch (InstallerException ignored) {
3880            }
3881            if (file.getUsableSpace() >= bytes) return;
3882
3883            // 9. Consider DropBox entries
3884            // 10. Consider ephemeral cookies
3885
3886        } else {
3887            try {
3888                mInstaller.freeCache(volumeUuid, bytes, 0);
3889            } catch (InstallerException ignored) {
3890            }
3891            if (file.getUsableSpace() >= bytes) return;
3892        }
3893
3894        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
3895    }
3896
3897    /**
3898     * Update given flags based on encryption status of current user.
3899     */
3900    private int updateFlags(int flags, int userId) {
3901        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3902                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3903            // Caller expressed an explicit opinion about what encryption
3904            // aware/unaware components they want to see, so fall through and
3905            // give them what they want
3906        } else {
3907            // Caller expressed no opinion, so match based on user state
3908            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3909                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3910            } else {
3911                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3912            }
3913        }
3914        return flags;
3915    }
3916
3917    private UserManagerInternal getUserManagerInternal() {
3918        if (mUserManagerInternal == null) {
3919            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3920        }
3921        return mUserManagerInternal;
3922    }
3923
3924    private DeviceIdleController.LocalService getDeviceIdleController() {
3925        if (mDeviceIdleController == null) {
3926            mDeviceIdleController =
3927                    LocalServices.getService(DeviceIdleController.LocalService.class);
3928        }
3929        return mDeviceIdleController;
3930    }
3931
3932    /**
3933     * Update given flags when being used to request {@link PackageInfo}.
3934     */
3935    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3936        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3937        boolean triaged = true;
3938        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3939                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3940            // Caller is asking for component details, so they'd better be
3941            // asking for specific encryption matching behavior, or be triaged
3942            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3943                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3944                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3945                triaged = false;
3946            }
3947        }
3948        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3949                | PackageManager.MATCH_SYSTEM_ONLY
3950                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3951            triaged = false;
3952        }
3953        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3954            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3955                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3956                    + Debug.getCallers(5));
3957        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3958                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3959            // If the caller wants all packages and has a restricted profile associated with it,
3960            // then match all users. This is to make sure that launchers that need to access work
3961            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3962            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3963            flags |= PackageManager.MATCH_ANY_USER;
3964        }
3965        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3966            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3967                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3968        }
3969        return updateFlags(flags, userId);
3970    }
3971
3972    /**
3973     * Update given flags when being used to request {@link ApplicationInfo}.
3974     */
3975    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3976        return updateFlagsForPackage(flags, userId, cookie);
3977    }
3978
3979    /**
3980     * Update given flags when being used to request {@link ComponentInfo}.
3981     */
3982    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3983        if (cookie instanceof Intent) {
3984            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3985                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3986            }
3987        }
3988
3989        boolean triaged = true;
3990        // Caller is asking for component details, so they'd better be
3991        // asking for specific encryption matching behavior, or be triaged
3992        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3993                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3994                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3995            triaged = false;
3996        }
3997        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3998            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3999                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4000        }
4001
4002        return updateFlags(flags, userId);
4003    }
4004
4005    /**
4006     * Update given intent when being used to request {@link ResolveInfo}.
4007     */
4008    private Intent updateIntentForResolve(Intent intent) {
4009        if (intent.getSelector() != null) {
4010            intent = intent.getSelector();
4011        }
4012        if (DEBUG_PREFERRED) {
4013            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4014        }
4015        return intent;
4016    }
4017
4018    /**
4019     * Update given flags when being used to request {@link ResolveInfo}.
4020     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4021     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4022     * flag set. However, this flag is only honoured in three circumstances:
4023     * <ul>
4024     * <li>when called from a system process</li>
4025     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4026     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4027     * action and a {@code android.intent.category.BROWSABLE} category</li>
4028     * </ul>
4029     */
4030    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4031            boolean includeInstantApps) {
4032        // Safe mode means we shouldn't match any third-party components
4033        if (mSafeMode) {
4034            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4035        }
4036        if (getInstantAppPackageName(callingUid) != null) {
4037            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4038            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4039            flags |= PackageManager.MATCH_INSTANT;
4040        } else {
4041            // Otherwise, prevent leaking ephemeral components
4042            final boolean isSpecialProcess =
4043                    callingUid == Process.SYSTEM_UID
4044                    || callingUid == Process.SHELL_UID
4045                    || callingUid == 0;
4046            final boolean allowMatchInstant =
4047                    (includeInstantApps
4048                            && Intent.ACTION_VIEW.equals(intent.getAction())
4049                            && intent.hasCategory(Intent.CATEGORY_BROWSABLE)
4050                            && hasWebURI(intent))
4051                    || isSpecialProcess
4052                    || mContext.checkCallingOrSelfPermission(
4053                            android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED;
4054            flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4055            if (!allowMatchInstant) {
4056                flags &= ~PackageManager.MATCH_INSTANT;
4057            }
4058        }
4059        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4060    }
4061
4062    @Override
4063    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4064        if (!sUserManager.exists(userId)) return null;
4065        flags = updateFlagsForComponent(flags, userId, component);
4066        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4067                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4068        synchronized (mPackages) {
4069            PackageParser.Activity a = mActivities.mActivities.get(component);
4070
4071            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4072            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4073                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4074                if (ps == null) return null;
4075                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
4076                        userId);
4077            }
4078            if (mResolveComponentName.equals(component)) {
4079                return PackageParser.generateActivityInfo(mResolveActivity, flags,
4080                        new PackageUserState(), userId);
4081            }
4082        }
4083        return null;
4084    }
4085
4086    @Override
4087    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4088            String resolvedType) {
4089        synchronized (mPackages) {
4090            if (component.equals(mResolveComponentName)) {
4091                // The resolver supports EVERYTHING!
4092                return true;
4093            }
4094            PackageParser.Activity a = mActivities.mActivities.get(component);
4095            if (a == null) {
4096                return false;
4097            }
4098            for (int i=0; i<a.intents.size(); i++) {
4099                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4100                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4101                    return true;
4102                }
4103            }
4104            return false;
4105        }
4106    }
4107
4108    @Override
4109    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4110        if (!sUserManager.exists(userId)) return null;
4111        flags = updateFlagsForComponent(flags, userId, component);
4112        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4113                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4114        synchronized (mPackages) {
4115            PackageParser.Activity a = mReceivers.mActivities.get(component);
4116            if (DEBUG_PACKAGE_INFO) Log.v(
4117                TAG, "getReceiverInfo " + component + ": " + a);
4118            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4119                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4120                if (ps == null) return null;
4121                ActivityInfo ri = PackageParser.generateActivityInfo(a, flags,
4122                        ps.readUserState(userId), userId);
4123                if (ri != null) {
4124                    rebaseEnabledOverlays(ri.applicationInfo, userId);
4125                }
4126                return ri;
4127            }
4128        }
4129        return null;
4130    }
4131
4132    @Override
4133    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4134        if (!sUserManager.exists(userId)) return null;
4135        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4136
4137        flags = updateFlagsForPackage(flags, userId, null);
4138
4139        final boolean canSeeStaticLibraries =
4140                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4141                        == PERMISSION_GRANTED
4142                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4143                        == PERMISSION_GRANTED
4144                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4145                        == PERMISSION_GRANTED
4146                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4147                        == PERMISSION_GRANTED;
4148
4149        synchronized (mPackages) {
4150            List<SharedLibraryInfo> result = null;
4151
4152            final int libCount = mSharedLibraries.size();
4153            for (int i = 0; i < libCount; i++) {
4154                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4155                if (versionedLib == null) {
4156                    continue;
4157                }
4158
4159                final int versionCount = versionedLib.size();
4160                for (int j = 0; j < versionCount; j++) {
4161                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4162                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4163                        break;
4164                    }
4165                    final long identity = Binder.clearCallingIdentity();
4166                    try {
4167                        // TODO: We will change version code to long, so in the new API it is long
4168                        PackageInfo packageInfo = getPackageInfoVersioned(
4169                                libInfo.getDeclaringPackage(), flags, userId);
4170                        if (packageInfo == null) {
4171                            continue;
4172                        }
4173                    } finally {
4174                        Binder.restoreCallingIdentity(identity);
4175                    }
4176
4177                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4178                            libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(),
4179                            getPackagesUsingSharedLibraryLPr(libInfo, flags, userId));
4180
4181                    if (result == null) {
4182                        result = new ArrayList<>();
4183                    }
4184                    result.add(resLibInfo);
4185                }
4186            }
4187
4188            return result != null ? new ParceledListSlice<>(result) : null;
4189        }
4190    }
4191
4192    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4193            SharedLibraryInfo libInfo, int flags, int userId) {
4194        List<VersionedPackage> versionedPackages = null;
4195        final int packageCount = mSettings.mPackages.size();
4196        for (int i = 0; i < packageCount; i++) {
4197            PackageSetting ps = mSettings.mPackages.valueAt(i);
4198
4199            if (ps == null) {
4200                continue;
4201            }
4202
4203            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4204                continue;
4205            }
4206
4207            final String libName = libInfo.getName();
4208            if (libInfo.isStatic()) {
4209                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4210                if (libIdx < 0) {
4211                    continue;
4212                }
4213                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4214                    continue;
4215                }
4216                if (versionedPackages == null) {
4217                    versionedPackages = new ArrayList<>();
4218                }
4219                // If the dependent is a static shared lib, use the public package name
4220                String dependentPackageName = ps.name;
4221                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4222                    dependentPackageName = ps.pkg.manifestPackageName;
4223                }
4224                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4225            } else if (ps.pkg != null) {
4226                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4227                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4228                    if (versionedPackages == null) {
4229                        versionedPackages = new ArrayList<>();
4230                    }
4231                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4232                }
4233            }
4234        }
4235
4236        return versionedPackages;
4237    }
4238
4239    @Override
4240    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4241        if (!sUserManager.exists(userId)) return null;
4242        flags = updateFlagsForComponent(flags, userId, component);
4243        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4244                false /* requireFullPermission */, false /* checkShell */, "get service info");
4245        synchronized (mPackages) {
4246            PackageParser.Service s = mServices.mServices.get(component);
4247            if (DEBUG_PACKAGE_INFO) Log.v(
4248                TAG, "getServiceInfo " + component + ": " + s);
4249            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4250                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4251                if (ps == null) return null;
4252                ServiceInfo si = PackageParser.generateServiceInfo(s, flags,
4253                        ps.readUserState(userId), userId);
4254                if (si != null) {
4255                    rebaseEnabledOverlays(si.applicationInfo, userId);
4256                }
4257                return si;
4258            }
4259        }
4260        return null;
4261    }
4262
4263    @Override
4264    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4265        if (!sUserManager.exists(userId)) return null;
4266        flags = updateFlagsForComponent(flags, userId, component);
4267        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4268                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4269        synchronized (mPackages) {
4270            PackageParser.Provider p = mProviders.mProviders.get(component);
4271            if (DEBUG_PACKAGE_INFO) Log.v(
4272                TAG, "getProviderInfo " + component + ": " + p);
4273            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4274                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4275                if (ps == null) return null;
4276                ProviderInfo pi = PackageParser.generateProviderInfo(p, flags,
4277                        ps.readUserState(userId), userId);
4278                if (pi != null) {
4279                    rebaseEnabledOverlays(pi.applicationInfo, userId);
4280                }
4281                return pi;
4282            }
4283        }
4284        return null;
4285    }
4286
4287    @Override
4288    public String[] getSystemSharedLibraryNames() {
4289        synchronized (mPackages) {
4290            Set<String> libs = null;
4291            final int libCount = mSharedLibraries.size();
4292            for (int i = 0; i < libCount; i++) {
4293                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4294                if (versionedLib == null) {
4295                    continue;
4296                }
4297                final int versionCount = versionedLib.size();
4298                for (int j = 0; j < versionCount; j++) {
4299                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4300                    if (!libEntry.info.isStatic()) {
4301                        if (libs == null) {
4302                            libs = new ArraySet<>();
4303                        }
4304                        libs.add(libEntry.info.getName());
4305                        break;
4306                    }
4307                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4308                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4309                            UserHandle.getUserId(Binder.getCallingUid()))) {
4310                        if (libs == null) {
4311                            libs = new ArraySet<>();
4312                        }
4313                        libs.add(libEntry.info.getName());
4314                        break;
4315                    }
4316                }
4317            }
4318
4319            if (libs != null) {
4320                String[] libsArray = new String[libs.size()];
4321                libs.toArray(libsArray);
4322                return libsArray;
4323            }
4324
4325            return null;
4326        }
4327    }
4328
4329    @Override
4330    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4331        synchronized (mPackages) {
4332            return mServicesSystemSharedLibraryPackageName;
4333        }
4334    }
4335
4336    @Override
4337    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4338        synchronized (mPackages) {
4339            return mSharedSystemSharedLibraryPackageName;
4340        }
4341    }
4342
4343    private void updateSequenceNumberLP(String packageName, int[] userList) {
4344        for (int i = userList.length - 1; i >= 0; --i) {
4345            final int userId = userList[i];
4346            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4347            if (changedPackages == null) {
4348                changedPackages = new SparseArray<>();
4349                mChangedPackages.put(userId, changedPackages);
4350            }
4351            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4352            if (sequenceNumbers == null) {
4353                sequenceNumbers = new HashMap<>();
4354                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4355            }
4356            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4357            if (sequenceNumber != null) {
4358                changedPackages.remove(sequenceNumber);
4359            }
4360            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4361            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4362        }
4363        mChangedPackagesSequenceNumber++;
4364    }
4365
4366    @Override
4367    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4368        synchronized (mPackages) {
4369            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4370                return null;
4371            }
4372            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4373            if (changedPackages == null) {
4374                return null;
4375            }
4376            final List<String> packageNames =
4377                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4378            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4379                final String packageName = changedPackages.get(i);
4380                if (packageName != null) {
4381                    packageNames.add(packageName);
4382                }
4383            }
4384            return packageNames.isEmpty()
4385                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4386        }
4387    }
4388
4389    @Override
4390    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4391        ArrayList<FeatureInfo> res;
4392        synchronized (mAvailableFeatures) {
4393            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4394            res.addAll(mAvailableFeatures.values());
4395        }
4396        final FeatureInfo fi = new FeatureInfo();
4397        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4398                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4399        res.add(fi);
4400
4401        return new ParceledListSlice<>(res);
4402    }
4403
4404    @Override
4405    public boolean hasSystemFeature(String name, int version) {
4406        synchronized (mAvailableFeatures) {
4407            final FeatureInfo feat = mAvailableFeatures.get(name);
4408            if (feat == null) {
4409                return false;
4410            } else {
4411                return feat.version >= version;
4412            }
4413        }
4414    }
4415
4416    @Override
4417    public int checkPermission(String permName, String pkgName, int userId) {
4418        if (!sUserManager.exists(userId)) {
4419            return PackageManager.PERMISSION_DENIED;
4420        }
4421
4422        synchronized (mPackages) {
4423            final PackageParser.Package p = mPackages.get(pkgName);
4424            if (p != null && p.mExtras != null) {
4425                final PackageSetting ps = (PackageSetting) p.mExtras;
4426                final PermissionsState permissionsState = ps.getPermissionsState();
4427                if (permissionsState.hasPermission(permName, userId)) {
4428                    return PackageManager.PERMISSION_GRANTED;
4429                }
4430                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4431                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4432                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4433                    return PackageManager.PERMISSION_GRANTED;
4434                }
4435            }
4436        }
4437
4438        return PackageManager.PERMISSION_DENIED;
4439    }
4440
4441    @Override
4442    public int checkUidPermission(String permName, int uid) {
4443        final int userId = UserHandle.getUserId(uid);
4444
4445        if (!sUserManager.exists(userId)) {
4446            return PackageManager.PERMISSION_DENIED;
4447        }
4448
4449        synchronized (mPackages) {
4450            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4451            if (obj != null) {
4452                final SettingBase ps = (SettingBase) obj;
4453                final PermissionsState permissionsState = ps.getPermissionsState();
4454                if (permissionsState.hasPermission(permName, userId)) {
4455                    return PackageManager.PERMISSION_GRANTED;
4456                }
4457                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4458                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4459                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4460                    return PackageManager.PERMISSION_GRANTED;
4461                }
4462            } else {
4463                ArraySet<String> perms = mSystemPermissions.get(uid);
4464                if (perms != null) {
4465                    if (perms.contains(permName)) {
4466                        return PackageManager.PERMISSION_GRANTED;
4467                    }
4468                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4469                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4470                        return PackageManager.PERMISSION_GRANTED;
4471                    }
4472                }
4473            }
4474        }
4475
4476        return PackageManager.PERMISSION_DENIED;
4477    }
4478
4479    @Override
4480    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4481        if (UserHandle.getCallingUserId() != userId) {
4482            mContext.enforceCallingPermission(
4483                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4484                    "isPermissionRevokedByPolicy for user " + userId);
4485        }
4486
4487        if (checkPermission(permission, packageName, userId)
4488                == PackageManager.PERMISSION_GRANTED) {
4489            return false;
4490        }
4491
4492        final long identity = Binder.clearCallingIdentity();
4493        try {
4494            final int flags = getPermissionFlags(permission, packageName, userId);
4495            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4496        } finally {
4497            Binder.restoreCallingIdentity(identity);
4498        }
4499    }
4500
4501    @Override
4502    public String getPermissionControllerPackageName() {
4503        synchronized (mPackages) {
4504            return mRequiredInstallerPackage;
4505        }
4506    }
4507
4508    /**
4509     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4510     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4511     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4512     * @param message the message to log on security exception
4513     */
4514    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4515            boolean checkShell, String message) {
4516        if (userId < 0) {
4517            throw new IllegalArgumentException("Invalid userId " + userId);
4518        }
4519        if (checkShell) {
4520            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4521        }
4522        if (userId == UserHandle.getUserId(callingUid)) return;
4523        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4524            if (requireFullPermission) {
4525                mContext.enforceCallingOrSelfPermission(
4526                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4527            } else {
4528                try {
4529                    mContext.enforceCallingOrSelfPermission(
4530                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4531                } catch (SecurityException se) {
4532                    mContext.enforceCallingOrSelfPermission(
4533                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4534                }
4535            }
4536        }
4537    }
4538
4539    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4540        if (callingUid == Process.SHELL_UID) {
4541            if (userHandle >= 0
4542                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4543                throw new SecurityException("Shell does not have permission to access user "
4544                        + userHandle);
4545            } else if (userHandle < 0) {
4546                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4547                        + Debug.getCallers(3));
4548            }
4549        }
4550    }
4551
4552    private BasePermission findPermissionTreeLP(String permName) {
4553        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4554            if (permName.startsWith(bp.name) &&
4555                    permName.length() > bp.name.length() &&
4556                    permName.charAt(bp.name.length()) == '.') {
4557                return bp;
4558            }
4559        }
4560        return null;
4561    }
4562
4563    private BasePermission checkPermissionTreeLP(String permName) {
4564        if (permName != null) {
4565            BasePermission bp = findPermissionTreeLP(permName);
4566            if (bp != null) {
4567                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4568                    return bp;
4569                }
4570                throw new SecurityException("Calling uid "
4571                        + Binder.getCallingUid()
4572                        + " is not allowed to add to permission tree "
4573                        + bp.name + " owned by uid " + bp.uid);
4574            }
4575        }
4576        throw new SecurityException("No permission tree found for " + permName);
4577    }
4578
4579    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4580        if (s1 == null) {
4581            return s2 == null;
4582        }
4583        if (s2 == null) {
4584            return false;
4585        }
4586        if (s1.getClass() != s2.getClass()) {
4587            return false;
4588        }
4589        return s1.equals(s2);
4590    }
4591
4592    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4593        if (pi1.icon != pi2.icon) return false;
4594        if (pi1.logo != pi2.logo) return false;
4595        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4596        if (!compareStrings(pi1.name, pi2.name)) return false;
4597        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4598        // We'll take care of setting this one.
4599        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4600        // These are not currently stored in settings.
4601        //if (!compareStrings(pi1.group, pi2.group)) return false;
4602        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4603        //if (pi1.labelRes != pi2.labelRes) return false;
4604        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4605        return true;
4606    }
4607
4608    int permissionInfoFootprint(PermissionInfo info) {
4609        int size = info.name.length();
4610        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4611        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4612        return size;
4613    }
4614
4615    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4616        int size = 0;
4617        for (BasePermission perm : mSettings.mPermissions.values()) {
4618            if (perm.uid == tree.uid) {
4619                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4620            }
4621        }
4622        return size;
4623    }
4624
4625    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4626        // We calculate the max size of permissions defined by this uid and throw
4627        // if that plus the size of 'info' would exceed our stated maximum.
4628        if (tree.uid != Process.SYSTEM_UID) {
4629            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4630            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4631                throw new SecurityException("Permission tree size cap exceeded");
4632            }
4633        }
4634    }
4635
4636    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4637        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4638            throw new SecurityException("Label must be specified in permission");
4639        }
4640        BasePermission tree = checkPermissionTreeLP(info.name);
4641        BasePermission bp = mSettings.mPermissions.get(info.name);
4642        boolean added = bp == null;
4643        boolean changed = true;
4644        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4645        if (added) {
4646            enforcePermissionCapLocked(info, tree);
4647            bp = new BasePermission(info.name, tree.sourcePackage,
4648                    BasePermission.TYPE_DYNAMIC);
4649        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4650            throw new SecurityException(
4651                    "Not allowed to modify non-dynamic permission "
4652                    + info.name);
4653        } else {
4654            if (bp.protectionLevel == fixedLevel
4655                    && bp.perm.owner.equals(tree.perm.owner)
4656                    && bp.uid == tree.uid
4657                    && comparePermissionInfos(bp.perm.info, info)) {
4658                changed = false;
4659            }
4660        }
4661        bp.protectionLevel = fixedLevel;
4662        info = new PermissionInfo(info);
4663        info.protectionLevel = fixedLevel;
4664        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4665        bp.perm.info.packageName = tree.perm.info.packageName;
4666        bp.uid = tree.uid;
4667        if (added) {
4668            mSettings.mPermissions.put(info.name, bp);
4669        }
4670        if (changed) {
4671            if (!async) {
4672                mSettings.writeLPr();
4673            } else {
4674                scheduleWriteSettingsLocked();
4675            }
4676        }
4677        return added;
4678    }
4679
4680    @Override
4681    public boolean addPermission(PermissionInfo info) {
4682        synchronized (mPackages) {
4683            return addPermissionLocked(info, false);
4684        }
4685    }
4686
4687    @Override
4688    public boolean addPermissionAsync(PermissionInfo info) {
4689        synchronized (mPackages) {
4690            return addPermissionLocked(info, true);
4691        }
4692    }
4693
4694    @Override
4695    public void removePermission(String name) {
4696        synchronized (mPackages) {
4697            checkPermissionTreeLP(name);
4698            BasePermission bp = mSettings.mPermissions.get(name);
4699            if (bp != null) {
4700                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4701                    throw new SecurityException(
4702                            "Not allowed to modify non-dynamic permission "
4703                            + name);
4704                }
4705                mSettings.mPermissions.remove(name);
4706                mSettings.writeLPr();
4707            }
4708        }
4709    }
4710
4711    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4712            BasePermission bp) {
4713        int index = pkg.requestedPermissions.indexOf(bp.name);
4714        if (index == -1) {
4715            throw new SecurityException("Package " + pkg.packageName
4716                    + " has not requested permission " + bp.name);
4717        }
4718        if (!bp.isRuntime() && !bp.isDevelopment()) {
4719            throw new SecurityException("Permission " + bp.name
4720                    + " is not a changeable permission type");
4721        }
4722    }
4723
4724    @Override
4725    public void grantRuntimePermission(String packageName, String name, final int userId) {
4726        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4727    }
4728
4729    private void grantRuntimePermission(String packageName, String name, final int userId,
4730            boolean overridePolicy) {
4731        if (!sUserManager.exists(userId)) {
4732            Log.e(TAG, "No such user:" + userId);
4733            return;
4734        }
4735
4736        mContext.enforceCallingOrSelfPermission(
4737                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4738                "grantRuntimePermission");
4739
4740        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4741                true /* requireFullPermission */, true /* checkShell */,
4742                "grantRuntimePermission");
4743
4744        final int uid;
4745        final SettingBase sb;
4746
4747        synchronized (mPackages) {
4748            final PackageParser.Package pkg = mPackages.get(packageName);
4749            if (pkg == null) {
4750                throw new IllegalArgumentException("Unknown package: " + packageName);
4751            }
4752
4753            final BasePermission bp = mSettings.mPermissions.get(name);
4754            if (bp == null) {
4755                throw new IllegalArgumentException("Unknown permission: " + name);
4756            }
4757
4758            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4759
4760            // If a permission review is required for legacy apps we represent
4761            // their permissions as always granted runtime ones since we need
4762            // to keep the review required permission flag per user while an
4763            // install permission's state is shared across all users.
4764            if (mPermissionReviewRequired
4765                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4766                    && bp.isRuntime()) {
4767                return;
4768            }
4769
4770            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4771            sb = (SettingBase) pkg.mExtras;
4772            if (sb == null) {
4773                throw new IllegalArgumentException("Unknown package: " + packageName);
4774            }
4775
4776            final PermissionsState permissionsState = sb.getPermissionsState();
4777
4778            final int flags = permissionsState.getPermissionFlags(name, userId);
4779            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4780                throw new SecurityException("Cannot grant system fixed permission "
4781                        + name + " for package " + packageName);
4782            }
4783            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4784                throw new SecurityException("Cannot grant policy fixed permission "
4785                        + name + " for package " + packageName);
4786            }
4787
4788            if (bp.isDevelopment()) {
4789                // Development permissions must be handled specially, since they are not
4790                // normal runtime permissions.  For now they apply to all users.
4791                if (permissionsState.grantInstallPermission(bp) !=
4792                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4793                    scheduleWriteSettingsLocked();
4794                }
4795                return;
4796            }
4797
4798            final PackageSetting ps = mSettings.mPackages.get(packageName);
4799            if (ps.getInstantApp(userId) && !bp.isInstant()) {
4800                throw new SecurityException("Cannot grant non-ephemeral permission"
4801                        + name + " for package " + packageName);
4802            }
4803
4804            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4805                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4806                return;
4807            }
4808
4809            final int result = permissionsState.grantRuntimePermission(bp, userId);
4810            switch (result) {
4811                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4812                    return;
4813                }
4814
4815                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4816                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4817                    mHandler.post(new Runnable() {
4818                        @Override
4819                        public void run() {
4820                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4821                        }
4822                    });
4823                }
4824                break;
4825            }
4826
4827            if (bp.isRuntime()) {
4828                logPermissionGranted(mContext, name, packageName);
4829            }
4830
4831            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4832
4833            // Not critical if that is lost - app has to request again.
4834            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4835        }
4836
4837        // Only need to do this if user is initialized. Otherwise it's a new user
4838        // and there are no processes running as the user yet and there's no need
4839        // to make an expensive call to remount processes for the changed permissions.
4840        if (READ_EXTERNAL_STORAGE.equals(name)
4841                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4842            final long token = Binder.clearCallingIdentity();
4843            try {
4844                if (sUserManager.isInitialized(userId)) {
4845                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4846                            StorageManagerInternal.class);
4847                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4848                }
4849            } finally {
4850                Binder.restoreCallingIdentity(token);
4851            }
4852        }
4853    }
4854
4855    @Override
4856    public void revokeRuntimePermission(String packageName, String name, int userId) {
4857        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4858    }
4859
4860    private void revokeRuntimePermission(String packageName, String name, int userId,
4861            boolean overridePolicy) {
4862        if (!sUserManager.exists(userId)) {
4863            Log.e(TAG, "No such user:" + userId);
4864            return;
4865        }
4866
4867        mContext.enforceCallingOrSelfPermission(
4868                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4869                "revokeRuntimePermission");
4870
4871        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4872                true /* requireFullPermission */, true /* checkShell */,
4873                "revokeRuntimePermission");
4874
4875        final int appId;
4876
4877        synchronized (mPackages) {
4878            final PackageParser.Package pkg = mPackages.get(packageName);
4879            if (pkg == null) {
4880                throw new IllegalArgumentException("Unknown package: " + packageName);
4881            }
4882
4883            final BasePermission bp = mSettings.mPermissions.get(name);
4884            if (bp == null) {
4885                throw new IllegalArgumentException("Unknown permission: " + name);
4886            }
4887
4888            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4889
4890            // If a permission review is required for legacy apps we represent
4891            // their permissions as always granted runtime ones since we need
4892            // to keep the review required permission flag per user while an
4893            // install permission's state is shared across all users.
4894            if (mPermissionReviewRequired
4895                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4896                    && bp.isRuntime()) {
4897                return;
4898            }
4899
4900            SettingBase sb = (SettingBase) pkg.mExtras;
4901            if (sb == null) {
4902                throw new IllegalArgumentException("Unknown package: " + packageName);
4903            }
4904
4905            final PermissionsState permissionsState = sb.getPermissionsState();
4906
4907            final int flags = permissionsState.getPermissionFlags(name, userId);
4908            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4909                throw new SecurityException("Cannot revoke system fixed permission "
4910                        + name + " for package " + packageName);
4911            }
4912            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4913                throw new SecurityException("Cannot revoke policy fixed permission "
4914                        + name + " for package " + packageName);
4915            }
4916
4917            if (bp.isDevelopment()) {
4918                // Development permissions must be handled specially, since they are not
4919                // normal runtime permissions.  For now they apply to all users.
4920                if (permissionsState.revokeInstallPermission(bp) !=
4921                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4922                    scheduleWriteSettingsLocked();
4923                }
4924                return;
4925            }
4926
4927            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4928                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4929                return;
4930            }
4931
4932            if (bp.isRuntime()) {
4933                logPermissionRevoked(mContext, name, packageName);
4934            }
4935
4936            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4937
4938            // Critical, after this call app should never have the permission.
4939            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4940
4941            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4942        }
4943
4944        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4945    }
4946
4947    /**
4948     * Get the first event id for the permission.
4949     *
4950     * <p>There are four events for each permission: <ul>
4951     *     <li>Request permission: first id + 0</li>
4952     *     <li>Grant permission: first id + 1</li>
4953     *     <li>Request for permission denied: first id + 2</li>
4954     *     <li>Revoke permission: first id + 3</li>
4955     * </ul></p>
4956     *
4957     * @param name name of the permission
4958     *
4959     * @return The first event id for the permission
4960     */
4961    private static int getBaseEventId(@NonNull String name) {
4962        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
4963
4964        if (eventIdIndex == -1) {
4965            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
4966                    || "user".equals(Build.TYPE)) {
4967                Log.i(TAG, "Unknown permission " + name);
4968
4969                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
4970            } else {
4971                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
4972                //
4973                // Also update
4974                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
4975                // - metrics_constants.proto
4976                throw new IllegalStateException("Unknown permission " + name);
4977            }
4978        }
4979
4980        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
4981    }
4982
4983    /**
4984     * Log that a permission was revoked.
4985     *
4986     * @param context Context of the caller
4987     * @param name name of the permission
4988     * @param packageName package permission if for
4989     */
4990    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
4991            @NonNull String packageName) {
4992        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
4993    }
4994
4995    /**
4996     * Log that a permission request was granted.
4997     *
4998     * @param context Context of the caller
4999     * @param name name of the permission
5000     * @param packageName package permission if for
5001     */
5002    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5003            @NonNull String packageName) {
5004        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5005    }
5006
5007    @Override
5008    public void resetRuntimePermissions() {
5009        mContext.enforceCallingOrSelfPermission(
5010                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5011                "revokeRuntimePermission");
5012
5013        int callingUid = Binder.getCallingUid();
5014        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5015            mContext.enforceCallingOrSelfPermission(
5016                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5017                    "resetRuntimePermissions");
5018        }
5019
5020        synchronized (mPackages) {
5021            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5022            for (int userId : UserManagerService.getInstance().getUserIds()) {
5023                final int packageCount = mPackages.size();
5024                for (int i = 0; i < packageCount; i++) {
5025                    PackageParser.Package pkg = mPackages.valueAt(i);
5026                    if (!(pkg.mExtras instanceof PackageSetting)) {
5027                        continue;
5028                    }
5029                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5030                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5031                }
5032            }
5033        }
5034    }
5035
5036    @Override
5037    public int getPermissionFlags(String name, String packageName, int userId) {
5038        if (!sUserManager.exists(userId)) {
5039            return 0;
5040        }
5041
5042        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5043
5044        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5045                true /* requireFullPermission */, false /* checkShell */,
5046                "getPermissionFlags");
5047
5048        synchronized (mPackages) {
5049            final PackageParser.Package pkg = mPackages.get(packageName);
5050            if (pkg == null) {
5051                return 0;
5052            }
5053
5054            final BasePermission bp = mSettings.mPermissions.get(name);
5055            if (bp == null) {
5056                return 0;
5057            }
5058
5059            SettingBase sb = (SettingBase) pkg.mExtras;
5060            if (sb == null) {
5061                return 0;
5062            }
5063
5064            PermissionsState permissionsState = sb.getPermissionsState();
5065            return permissionsState.getPermissionFlags(name, userId);
5066        }
5067    }
5068
5069    @Override
5070    public void updatePermissionFlags(String name, String packageName, int flagMask,
5071            int flagValues, int userId) {
5072        if (!sUserManager.exists(userId)) {
5073            return;
5074        }
5075
5076        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5077
5078        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5079                true /* requireFullPermission */, true /* checkShell */,
5080                "updatePermissionFlags");
5081
5082        // Only the system can change these flags and nothing else.
5083        if (getCallingUid() != Process.SYSTEM_UID) {
5084            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5085            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5086            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5087            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5088            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5089        }
5090
5091        synchronized (mPackages) {
5092            final PackageParser.Package pkg = mPackages.get(packageName);
5093            if (pkg == null) {
5094                throw new IllegalArgumentException("Unknown package: " + packageName);
5095            }
5096
5097            final BasePermission bp = mSettings.mPermissions.get(name);
5098            if (bp == null) {
5099                throw new IllegalArgumentException("Unknown permission: " + name);
5100            }
5101
5102            SettingBase sb = (SettingBase) pkg.mExtras;
5103            if (sb == null) {
5104                throw new IllegalArgumentException("Unknown package: " + packageName);
5105            }
5106
5107            PermissionsState permissionsState = sb.getPermissionsState();
5108
5109            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5110
5111            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5112                // Install and runtime permissions are stored in different places,
5113                // so figure out what permission changed and persist the change.
5114                if (permissionsState.getInstallPermissionState(name) != null) {
5115                    scheduleWriteSettingsLocked();
5116                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5117                        || hadState) {
5118                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5119                }
5120            }
5121        }
5122    }
5123
5124    /**
5125     * Update the permission flags for all packages and runtime permissions of a user in order
5126     * to allow device or profile owner to remove POLICY_FIXED.
5127     */
5128    @Override
5129    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5130        if (!sUserManager.exists(userId)) {
5131            return;
5132        }
5133
5134        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5135
5136        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5137                true /* requireFullPermission */, true /* checkShell */,
5138                "updatePermissionFlagsForAllApps");
5139
5140        // Only the system can change system fixed flags.
5141        if (getCallingUid() != Process.SYSTEM_UID) {
5142            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5143            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5144        }
5145
5146        synchronized (mPackages) {
5147            boolean changed = false;
5148            final int packageCount = mPackages.size();
5149            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5150                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5151                SettingBase sb = (SettingBase) pkg.mExtras;
5152                if (sb == null) {
5153                    continue;
5154                }
5155                PermissionsState permissionsState = sb.getPermissionsState();
5156                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5157                        userId, flagMask, flagValues);
5158            }
5159            if (changed) {
5160                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5161            }
5162        }
5163    }
5164
5165    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5166        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5167                != PackageManager.PERMISSION_GRANTED
5168            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5169                != PackageManager.PERMISSION_GRANTED) {
5170            throw new SecurityException(message + " requires "
5171                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5172                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5173        }
5174    }
5175
5176    @Override
5177    public boolean shouldShowRequestPermissionRationale(String permissionName,
5178            String packageName, int userId) {
5179        if (UserHandle.getCallingUserId() != userId) {
5180            mContext.enforceCallingPermission(
5181                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5182                    "canShowRequestPermissionRationale for user " + userId);
5183        }
5184
5185        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5186        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5187            return false;
5188        }
5189
5190        if (checkPermission(permissionName, packageName, userId)
5191                == PackageManager.PERMISSION_GRANTED) {
5192            return false;
5193        }
5194
5195        final int flags;
5196
5197        final long identity = Binder.clearCallingIdentity();
5198        try {
5199            flags = getPermissionFlags(permissionName,
5200                    packageName, userId);
5201        } finally {
5202            Binder.restoreCallingIdentity(identity);
5203        }
5204
5205        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5206                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5207                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5208
5209        if ((flags & fixedFlags) != 0) {
5210            return false;
5211        }
5212
5213        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5214    }
5215
5216    @Override
5217    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5218        mContext.enforceCallingOrSelfPermission(
5219                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5220                "addOnPermissionsChangeListener");
5221
5222        synchronized (mPackages) {
5223            mOnPermissionChangeListeners.addListenerLocked(listener);
5224        }
5225    }
5226
5227    @Override
5228    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5229        synchronized (mPackages) {
5230            mOnPermissionChangeListeners.removeListenerLocked(listener);
5231        }
5232    }
5233
5234    @Override
5235    public boolean isProtectedBroadcast(String actionName) {
5236        synchronized (mPackages) {
5237            if (mProtectedBroadcasts.contains(actionName)) {
5238                return true;
5239            } else if (actionName != null) {
5240                // TODO: remove these terrible hacks
5241                if (actionName.startsWith("android.net.netmon.lingerExpired")
5242                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5243                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5244                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5245                    return true;
5246                }
5247            }
5248        }
5249        return false;
5250    }
5251
5252    @Override
5253    public int checkSignatures(String pkg1, String pkg2) {
5254        synchronized (mPackages) {
5255            final PackageParser.Package p1 = mPackages.get(pkg1);
5256            final PackageParser.Package p2 = mPackages.get(pkg2);
5257            if (p1 == null || p1.mExtras == null
5258                    || p2 == null || p2.mExtras == null) {
5259                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5260            }
5261            return compareSignatures(p1.mSignatures, p2.mSignatures);
5262        }
5263    }
5264
5265    @Override
5266    public int checkUidSignatures(int uid1, int uid2) {
5267        // Map to base uids.
5268        uid1 = UserHandle.getAppId(uid1);
5269        uid2 = UserHandle.getAppId(uid2);
5270        // reader
5271        synchronized (mPackages) {
5272            Signature[] s1;
5273            Signature[] s2;
5274            Object obj = mSettings.getUserIdLPr(uid1);
5275            if (obj != null) {
5276                if (obj instanceof SharedUserSetting) {
5277                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5278                } else if (obj instanceof PackageSetting) {
5279                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5280                } else {
5281                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5282                }
5283            } else {
5284                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5285            }
5286            obj = mSettings.getUserIdLPr(uid2);
5287            if (obj != null) {
5288                if (obj instanceof SharedUserSetting) {
5289                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5290                } else if (obj instanceof PackageSetting) {
5291                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5292                } else {
5293                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5294                }
5295            } else {
5296                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5297            }
5298            return compareSignatures(s1, s2);
5299        }
5300    }
5301
5302    /**
5303     * This method should typically only be used when granting or revoking
5304     * permissions, since the app may immediately restart after this call.
5305     * <p>
5306     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5307     * guard your work against the app being relaunched.
5308     */
5309    private void killUid(int appId, int userId, String reason) {
5310        final long identity = Binder.clearCallingIdentity();
5311        try {
5312            IActivityManager am = ActivityManager.getService();
5313            if (am != null) {
5314                try {
5315                    am.killUid(appId, userId, reason);
5316                } catch (RemoteException e) {
5317                    /* ignore - same process */
5318                }
5319            }
5320        } finally {
5321            Binder.restoreCallingIdentity(identity);
5322        }
5323    }
5324
5325    /**
5326     * Compares two sets of signatures. Returns:
5327     * <br />
5328     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5329     * <br />
5330     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5331     * <br />
5332     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5333     * <br />
5334     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5335     * <br />
5336     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5337     */
5338    static int compareSignatures(Signature[] s1, Signature[] s2) {
5339        if (s1 == null) {
5340            return s2 == null
5341                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5342                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5343        }
5344
5345        if (s2 == null) {
5346            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5347        }
5348
5349        if (s1.length != s2.length) {
5350            return PackageManager.SIGNATURE_NO_MATCH;
5351        }
5352
5353        // Since both signature sets are of size 1, we can compare without HashSets.
5354        if (s1.length == 1) {
5355            return s1[0].equals(s2[0]) ?
5356                    PackageManager.SIGNATURE_MATCH :
5357                    PackageManager.SIGNATURE_NO_MATCH;
5358        }
5359
5360        ArraySet<Signature> set1 = new ArraySet<Signature>();
5361        for (Signature sig : s1) {
5362            set1.add(sig);
5363        }
5364        ArraySet<Signature> set2 = new ArraySet<Signature>();
5365        for (Signature sig : s2) {
5366            set2.add(sig);
5367        }
5368        // Make sure s2 contains all signatures in s1.
5369        if (set1.equals(set2)) {
5370            return PackageManager.SIGNATURE_MATCH;
5371        }
5372        return PackageManager.SIGNATURE_NO_MATCH;
5373    }
5374
5375    /**
5376     * If the database version for this type of package (internal storage or
5377     * external storage) is less than the version where package signatures
5378     * were updated, return true.
5379     */
5380    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5381        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5382        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5383    }
5384
5385    /**
5386     * Used for backward compatibility to make sure any packages with
5387     * certificate chains get upgraded to the new style. {@code existingSigs}
5388     * will be in the old format (since they were stored on disk from before the
5389     * system upgrade) and {@code scannedSigs} will be in the newer format.
5390     */
5391    private int compareSignaturesCompat(PackageSignatures existingSigs,
5392            PackageParser.Package scannedPkg) {
5393        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5394            return PackageManager.SIGNATURE_NO_MATCH;
5395        }
5396
5397        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5398        for (Signature sig : existingSigs.mSignatures) {
5399            existingSet.add(sig);
5400        }
5401        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5402        for (Signature sig : scannedPkg.mSignatures) {
5403            try {
5404                Signature[] chainSignatures = sig.getChainSignatures();
5405                for (Signature chainSig : chainSignatures) {
5406                    scannedCompatSet.add(chainSig);
5407                }
5408            } catch (CertificateEncodingException e) {
5409                scannedCompatSet.add(sig);
5410            }
5411        }
5412        /*
5413         * Make sure the expanded scanned set contains all signatures in the
5414         * existing one.
5415         */
5416        if (scannedCompatSet.equals(existingSet)) {
5417            // Migrate the old signatures to the new scheme.
5418            existingSigs.assignSignatures(scannedPkg.mSignatures);
5419            // The new KeySets will be re-added later in the scanning process.
5420            synchronized (mPackages) {
5421                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5422            }
5423            return PackageManager.SIGNATURE_MATCH;
5424        }
5425        return PackageManager.SIGNATURE_NO_MATCH;
5426    }
5427
5428    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5429        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5430        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5431    }
5432
5433    private int compareSignaturesRecover(PackageSignatures existingSigs,
5434            PackageParser.Package scannedPkg) {
5435        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5436            return PackageManager.SIGNATURE_NO_MATCH;
5437        }
5438
5439        String msg = null;
5440        try {
5441            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5442                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5443                        + scannedPkg.packageName);
5444                return PackageManager.SIGNATURE_MATCH;
5445            }
5446        } catch (CertificateException e) {
5447            msg = e.getMessage();
5448        }
5449
5450        logCriticalInfo(Log.INFO,
5451                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5452        return PackageManager.SIGNATURE_NO_MATCH;
5453    }
5454
5455    @Override
5456    public List<String> getAllPackages() {
5457        synchronized (mPackages) {
5458            return new ArrayList<String>(mPackages.keySet());
5459        }
5460    }
5461
5462    @Override
5463    public String[] getPackagesForUid(int uid) {
5464        final int userId = UserHandle.getUserId(uid);
5465        uid = UserHandle.getAppId(uid);
5466        // reader
5467        synchronized (mPackages) {
5468            Object obj = mSettings.getUserIdLPr(uid);
5469            if (obj instanceof SharedUserSetting) {
5470                final SharedUserSetting sus = (SharedUserSetting) obj;
5471                final int N = sus.packages.size();
5472                String[] res = new String[N];
5473                final Iterator<PackageSetting> it = sus.packages.iterator();
5474                int i = 0;
5475                while (it.hasNext()) {
5476                    PackageSetting ps = it.next();
5477                    if (ps.getInstalled(userId)) {
5478                        res[i++] = ps.name;
5479                    } else {
5480                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5481                    }
5482                }
5483                return res;
5484            } else if (obj instanceof PackageSetting) {
5485                final PackageSetting ps = (PackageSetting) obj;
5486                if (ps.getInstalled(userId)) {
5487                    return new String[]{ps.name};
5488                }
5489            }
5490        }
5491        return null;
5492    }
5493
5494    @Override
5495    public String getNameForUid(int uid) {
5496        // reader
5497        synchronized (mPackages) {
5498            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5499            if (obj instanceof SharedUserSetting) {
5500                final SharedUserSetting sus = (SharedUserSetting) obj;
5501                return sus.name + ":" + sus.userId;
5502            } else if (obj instanceof PackageSetting) {
5503                final PackageSetting ps = (PackageSetting) obj;
5504                return ps.name;
5505            }
5506        }
5507        return null;
5508    }
5509
5510    @Override
5511    public int getUidForSharedUser(String sharedUserName) {
5512        if(sharedUserName == null) {
5513            return -1;
5514        }
5515        // reader
5516        synchronized (mPackages) {
5517            SharedUserSetting suid;
5518            try {
5519                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5520                if (suid != null) {
5521                    return suid.userId;
5522                }
5523            } catch (PackageManagerException ignore) {
5524                // can't happen, but, still need to catch it
5525            }
5526            return -1;
5527        }
5528    }
5529
5530    @Override
5531    public int getFlagsForUid(int uid) {
5532        synchronized (mPackages) {
5533            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5534            if (obj instanceof SharedUserSetting) {
5535                final SharedUserSetting sus = (SharedUserSetting) obj;
5536                return sus.pkgFlags;
5537            } else if (obj instanceof PackageSetting) {
5538                final PackageSetting ps = (PackageSetting) obj;
5539                return ps.pkgFlags;
5540            }
5541        }
5542        return 0;
5543    }
5544
5545    @Override
5546    public int getPrivateFlagsForUid(int uid) {
5547        synchronized (mPackages) {
5548            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5549            if (obj instanceof SharedUserSetting) {
5550                final SharedUserSetting sus = (SharedUserSetting) obj;
5551                return sus.pkgPrivateFlags;
5552            } else if (obj instanceof PackageSetting) {
5553                final PackageSetting ps = (PackageSetting) obj;
5554                return ps.pkgPrivateFlags;
5555            }
5556        }
5557        return 0;
5558    }
5559
5560    @Override
5561    public boolean isUidPrivileged(int uid) {
5562        uid = UserHandle.getAppId(uid);
5563        // reader
5564        synchronized (mPackages) {
5565            Object obj = mSettings.getUserIdLPr(uid);
5566            if (obj instanceof SharedUserSetting) {
5567                final SharedUserSetting sus = (SharedUserSetting) obj;
5568                final Iterator<PackageSetting> it = sus.packages.iterator();
5569                while (it.hasNext()) {
5570                    if (it.next().isPrivileged()) {
5571                        return true;
5572                    }
5573                }
5574            } else if (obj instanceof PackageSetting) {
5575                final PackageSetting ps = (PackageSetting) obj;
5576                return ps.isPrivileged();
5577            }
5578        }
5579        return false;
5580    }
5581
5582    @Override
5583    public String[] getAppOpPermissionPackages(String permissionName) {
5584        synchronized (mPackages) {
5585            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5586            if (pkgs == null) {
5587                return null;
5588            }
5589            return pkgs.toArray(new String[pkgs.size()]);
5590        }
5591    }
5592
5593    @Override
5594    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5595            int flags, int userId) {
5596        return resolveIntentInternal(
5597                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
5598    }
5599
5600    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5601            int flags, int userId, boolean includeInstantApps) {
5602        try {
5603            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5604
5605            if (!sUserManager.exists(userId)) return null;
5606            final int callingUid = Binder.getCallingUid();
5607            flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
5608            enforceCrossUserPermission(callingUid, userId,
5609                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5610
5611            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5612            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5613                    flags, userId, includeInstantApps);
5614            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5615
5616            final ResolveInfo bestChoice =
5617                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5618            return bestChoice;
5619        } finally {
5620            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5621        }
5622    }
5623
5624    @Override
5625    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5626        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5627            throw new SecurityException(
5628                    "findPersistentPreferredActivity can only be run by the system");
5629        }
5630        if (!sUserManager.exists(userId)) {
5631            return null;
5632        }
5633        final int callingUid = Binder.getCallingUid();
5634        intent = updateIntentForResolve(intent);
5635        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5636        final int flags = updateFlagsForResolve(
5637                0, userId, intent, callingUid, false /*includeInstantApps*/);
5638        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5639                userId);
5640        synchronized (mPackages) {
5641            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5642                    userId);
5643        }
5644    }
5645
5646    @Override
5647    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5648            IntentFilter filter, int match, ComponentName activity) {
5649        final int userId = UserHandle.getCallingUserId();
5650        if (DEBUG_PREFERRED) {
5651            Log.v(TAG, "setLastChosenActivity intent=" + intent
5652                + " resolvedType=" + resolvedType
5653                + " flags=" + flags
5654                + " filter=" + filter
5655                + " match=" + match
5656                + " activity=" + activity);
5657            filter.dump(new PrintStreamPrinter(System.out), "    ");
5658        }
5659        intent.setComponent(null);
5660        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5661                userId);
5662        // Find any earlier preferred or last chosen entries and nuke them
5663        findPreferredActivity(intent, resolvedType,
5664                flags, query, 0, false, true, false, userId);
5665        // Add the new activity as the last chosen for this filter
5666        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5667                "Setting last chosen");
5668    }
5669
5670    @Override
5671    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5672        final int userId = UserHandle.getCallingUserId();
5673        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5674        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5675                userId);
5676        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5677                false, false, false, userId);
5678    }
5679
5680    /**
5681     * Returns whether or not instant apps have been disabled remotely.
5682     * <p><em>IMPORTANT</em> This should not be called with the package manager lock
5683     * held. Otherwise we run the risk of deadlock.
5684     */
5685    private boolean isEphemeralDisabled() {
5686        // ephemeral apps have been disabled across the board
5687        if (DISABLE_EPHEMERAL_APPS) {
5688            return true;
5689        }
5690        // system isn't up yet; can't read settings, so, assume no ephemeral apps
5691        if (!mSystemReady) {
5692            return true;
5693        }
5694        // we can't get a content resolver until the system is ready; these checks must happen last
5695        final ContentResolver resolver = mContext.getContentResolver();
5696        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
5697            return true;
5698        }
5699        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
5700    }
5701
5702    private boolean isEphemeralAllowed(
5703            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5704            boolean skipPackageCheck) {
5705        final int callingUser = UserHandle.getCallingUserId();
5706        if (callingUser != UserHandle.USER_SYSTEM) {
5707            return false;
5708        }
5709        if (mInstantAppResolverConnection == null) {
5710            return false;
5711        }
5712        if (mInstantAppInstallerComponent == null) {
5713            return false;
5714        }
5715        if (intent.getComponent() != null) {
5716            return false;
5717        }
5718        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5719            return false;
5720        }
5721        if (!skipPackageCheck && intent.getPackage() != null) {
5722            return false;
5723        }
5724        final boolean isWebUri = hasWebURI(intent);
5725        if (!isWebUri || intent.getData().getHost() == null) {
5726            return false;
5727        }
5728        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5729        // Or if there's already an ephemeral app installed that handles the action
5730        synchronized (mPackages) {
5731            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5732            for (int n = 0; n < count; n++) {
5733                ResolveInfo info = resolvedActivities.get(n);
5734                String packageName = info.activityInfo.packageName;
5735                PackageSetting ps = mSettings.mPackages.get(packageName);
5736                if (ps != null) {
5737                    // Try to get the status from User settings first
5738                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5739                    int status = (int) (packedStatus >> 32);
5740                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5741                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5742                        if (DEBUG_EPHEMERAL) {
5743                            Slog.v(TAG, "DENY ephemeral apps;"
5744                                + " pkg: " + packageName + ", status: " + status);
5745                        }
5746                        return false;
5747                    }
5748                    if (ps.getInstantApp(userId)) {
5749                        if (DEBUG_EPHEMERAL) {
5750                            Slog.v(TAG, "DENY instant app installed;"
5751                                    + " pkg: " + packageName);
5752                        }
5753                        return false;
5754                    }
5755                }
5756            }
5757        }
5758        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5759        return true;
5760    }
5761
5762    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5763            Intent origIntent, String resolvedType, String callingPackage,
5764            int userId) {
5765        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5766                new InstantAppRequest(responseObj, origIntent, resolvedType,
5767                        callingPackage, userId));
5768        mHandler.sendMessage(msg);
5769    }
5770
5771    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5772            int flags, List<ResolveInfo> query, int userId) {
5773        if (query != null) {
5774            final int N = query.size();
5775            if (N == 1) {
5776                return query.get(0);
5777            } else if (N > 1) {
5778                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5779                // If there is more than one activity with the same priority,
5780                // then let the user decide between them.
5781                ResolveInfo r0 = query.get(0);
5782                ResolveInfo r1 = query.get(1);
5783                if (DEBUG_INTENT_MATCHING || debug) {
5784                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5785                            + r1.activityInfo.name + "=" + r1.priority);
5786                }
5787                // If the first activity has a higher priority, or a different
5788                // default, then it is always desirable to pick it.
5789                if (r0.priority != r1.priority
5790                        || r0.preferredOrder != r1.preferredOrder
5791                        || r0.isDefault != r1.isDefault) {
5792                    return query.get(0);
5793                }
5794                // If we have saved a preference for a preferred activity for
5795                // this Intent, use that.
5796                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5797                        flags, query, r0.priority, true, false, debug, userId);
5798                if (ri != null) {
5799                    return ri;
5800                }
5801                // If we have an ephemeral app, use it
5802                for (int i = 0; i < N; i++) {
5803                    ri = query.get(i);
5804                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5805                        return ri;
5806                    }
5807                }
5808                ri = new ResolveInfo(mResolveInfo);
5809                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5810                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5811                // If all of the options come from the same package, show the application's
5812                // label and icon instead of the generic resolver's.
5813                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5814                // and then throw away the ResolveInfo itself, meaning that the caller loses
5815                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5816                // a fallback for this case; we only set the target package's resources on
5817                // the ResolveInfo, not the ActivityInfo.
5818                final String intentPackage = intent.getPackage();
5819                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5820                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5821                    ri.resolvePackageName = intentPackage;
5822                    if (userNeedsBadging(userId)) {
5823                        ri.noResourceId = true;
5824                    } else {
5825                        ri.icon = appi.icon;
5826                    }
5827                    ri.iconResourceId = appi.icon;
5828                    ri.labelRes = appi.labelRes;
5829                }
5830                ri.activityInfo.applicationInfo = new ApplicationInfo(
5831                        ri.activityInfo.applicationInfo);
5832                if (userId != 0) {
5833                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5834                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5835                }
5836                // Make sure that the resolver is displayable in car mode
5837                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5838                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5839                return ri;
5840            }
5841        }
5842        return null;
5843    }
5844
5845    /**
5846     * Return true if the given list is not empty and all of its contents have
5847     * an activityInfo with the given package name.
5848     */
5849    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5850        if (ArrayUtils.isEmpty(list)) {
5851            return false;
5852        }
5853        for (int i = 0, N = list.size(); i < N; i++) {
5854            final ResolveInfo ri = list.get(i);
5855            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5856            if (ai == null || !packageName.equals(ai.packageName)) {
5857                return false;
5858            }
5859        }
5860        return true;
5861    }
5862
5863    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5864            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5865        final int N = query.size();
5866        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5867                .get(userId);
5868        // Get the list of persistent preferred activities that handle the intent
5869        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5870        List<PersistentPreferredActivity> pprefs = ppir != null
5871                ? ppir.queryIntent(intent, resolvedType,
5872                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5873                        userId)
5874                : null;
5875        if (pprefs != null && pprefs.size() > 0) {
5876            final int M = pprefs.size();
5877            for (int i=0; i<M; i++) {
5878                final PersistentPreferredActivity ppa = pprefs.get(i);
5879                if (DEBUG_PREFERRED || debug) {
5880                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5881                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5882                            + "\n  component=" + ppa.mComponent);
5883                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5884                }
5885                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5886                        flags | MATCH_DISABLED_COMPONENTS, userId);
5887                if (DEBUG_PREFERRED || debug) {
5888                    Slog.v(TAG, "Found persistent preferred activity:");
5889                    if (ai != null) {
5890                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5891                    } else {
5892                        Slog.v(TAG, "  null");
5893                    }
5894                }
5895                if (ai == null) {
5896                    // This previously registered persistent preferred activity
5897                    // component is no longer known. Ignore it and do NOT remove it.
5898                    continue;
5899                }
5900                for (int j=0; j<N; j++) {
5901                    final ResolveInfo ri = query.get(j);
5902                    if (!ri.activityInfo.applicationInfo.packageName
5903                            .equals(ai.applicationInfo.packageName)) {
5904                        continue;
5905                    }
5906                    if (!ri.activityInfo.name.equals(ai.name)) {
5907                        continue;
5908                    }
5909                    //  Found a persistent preference that can handle the intent.
5910                    if (DEBUG_PREFERRED || debug) {
5911                        Slog.v(TAG, "Returning persistent preferred activity: " +
5912                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5913                    }
5914                    return ri;
5915                }
5916            }
5917        }
5918        return null;
5919    }
5920
5921    // TODO: handle preferred activities missing while user has amnesia
5922    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5923            List<ResolveInfo> query, int priority, boolean always,
5924            boolean removeMatches, boolean debug, int userId) {
5925        if (!sUserManager.exists(userId)) return null;
5926        final int callingUid = Binder.getCallingUid();
5927        flags = updateFlagsForResolve(
5928                flags, userId, intent, callingUid, false /*includeInstantApps*/);
5929        intent = updateIntentForResolve(intent);
5930        // writer
5931        synchronized (mPackages) {
5932            // Try to find a matching persistent preferred activity.
5933            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5934                    debug, userId);
5935
5936            // If a persistent preferred activity matched, use it.
5937            if (pri != null) {
5938                return pri;
5939            }
5940
5941            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5942            // Get the list of preferred activities that handle the intent
5943            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5944            List<PreferredActivity> prefs = pir != null
5945                    ? pir.queryIntent(intent, resolvedType,
5946                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5947                            userId)
5948                    : null;
5949            if (prefs != null && prefs.size() > 0) {
5950                boolean changed = false;
5951                try {
5952                    // First figure out how good the original match set is.
5953                    // We will only allow preferred activities that came
5954                    // from the same match quality.
5955                    int match = 0;
5956
5957                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5958
5959                    final int N = query.size();
5960                    for (int j=0; j<N; j++) {
5961                        final ResolveInfo ri = query.get(j);
5962                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5963                                + ": 0x" + Integer.toHexString(match));
5964                        if (ri.match > match) {
5965                            match = ri.match;
5966                        }
5967                    }
5968
5969                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5970                            + Integer.toHexString(match));
5971
5972                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5973                    final int M = prefs.size();
5974                    for (int i=0; i<M; i++) {
5975                        final PreferredActivity pa = prefs.get(i);
5976                        if (DEBUG_PREFERRED || debug) {
5977                            Slog.v(TAG, "Checking PreferredActivity ds="
5978                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5979                                    + "\n  component=" + pa.mPref.mComponent);
5980                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5981                        }
5982                        if (pa.mPref.mMatch != match) {
5983                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5984                                    + Integer.toHexString(pa.mPref.mMatch));
5985                            continue;
5986                        }
5987                        // If it's not an "always" type preferred activity and that's what we're
5988                        // looking for, skip it.
5989                        if (always && !pa.mPref.mAlways) {
5990                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5991                            continue;
5992                        }
5993                        final ActivityInfo ai = getActivityInfo(
5994                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5995                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5996                                userId);
5997                        if (DEBUG_PREFERRED || debug) {
5998                            Slog.v(TAG, "Found preferred activity:");
5999                            if (ai != null) {
6000                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6001                            } else {
6002                                Slog.v(TAG, "  null");
6003                            }
6004                        }
6005                        if (ai == null) {
6006                            // This previously registered preferred activity
6007                            // component is no longer known.  Most likely an update
6008                            // to the app was installed and in the new version this
6009                            // component no longer exists.  Clean it up by removing
6010                            // it from the preferred activities list, and skip it.
6011                            Slog.w(TAG, "Removing dangling preferred activity: "
6012                                    + pa.mPref.mComponent);
6013                            pir.removeFilter(pa);
6014                            changed = true;
6015                            continue;
6016                        }
6017                        for (int j=0; j<N; j++) {
6018                            final ResolveInfo ri = query.get(j);
6019                            if (!ri.activityInfo.applicationInfo.packageName
6020                                    .equals(ai.applicationInfo.packageName)) {
6021                                continue;
6022                            }
6023                            if (!ri.activityInfo.name.equals(ai.name)) {
6024                                continue;
6025                            }
6026
6027                            if (removeMatches) {
6028                                pir.removeFilter(pa);
6029                                changed = true;
6030                                if (DEBUG_PREFERRED) {
6031                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6032                                }
6033                                break;
6034                            }
6035
6036                            // Okay we found a previously set preferred or last chosen app.
6037                            // If the result set is different from when this
6038                            // was created, we need to clear it and re-ask the
6039                            // user their preference, if we're looking for an "always" type entry.
6040                            if (always && !pa.mPref.sameSet(query)) {
6041                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6042                                        + intent + " type " + resolvedType);
6043                                if (DEBUG_PREFERRED) {
6044                                    Slog.v(TAG, "Removing preferred activity since set changed "
6045                                            + pa.mPref.mComponent);
6046                                }
6047                                pir.removeFilter(pa);
6048                                // Re-add the filter as a "last chosen" entry (!always)
6049                                PreferredActivity lastChosen = new PreferredActivity(
6050                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6051                                pir.addFilter(lastChosen);
6052                                changed = true;
6053                                return null;
6054                            }
6055
6056                            // Yay! Either the set matched or we're looking for the last chosen
6057                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6058                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6059                            return ri;
6060                        }
6061                    }
6062                } finally {
6063                    if (changed) {
6064                        if (DEBUG_PREFERRED) {
6065                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6066                        }
6067                        scheduleWritePackageRestrictionsLocked(userId);
6068                    }
6069                }
6070            }
6071        }
6072        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6073        return null;
6074    }
6075
6076    /*
6077     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6078     */
6079    @Override
6080    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6081            int targetUserId) {
6082        mContext.enforceCallingOrSelfPermission(
6083                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6084        List<CrossProfileIntentFilter> matches =
6085                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6086        if (matches != null) {
6087            int size = matches.size();
6088            for (int i = 0; i < size; i++) {
6089                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6090            }
6091        }
6092        if (hasWebURI(intent)) {
6093            // cross-profile app linking works only towards the parent.
6094            final int callingUid = Binder.getCallingUid();
6095            final UserInfo parent = getProfileParent(sourceUserId);
6096            synchronized(mPackages) {
6097                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6098                        false /*includeInstantApps*/);
6099                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6100                        intent, resolvedType, flags, sourceUserId, parent.id);
6101                return xpDomainInfo != null;
6102            }
6103        }
6104        return false;
6105    }
6106
6107    private UserInfo getProfileParent(int userId) {
6108        final long identity = Binder.clearCallingIdentity();
6109        try {
6110            return sUserManager.getProfileParent(userId);
6111        } finally {
6112            Binder.restoreCallingIdentity(identity);
6113        }
6114    }
6115
6116    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6117            String resolvedType, int userId) {
6118        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6119        if (resolver != null) {
6120            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6121        }
6122        return null;
6123    }
6124
6125    @Override
6126    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6127            String resolvedType, int flags, int userId) {
6128        try {
6129            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6130
6131            return new ParceledListSlice<>(
6132                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6133        } finally {
6134            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6135        }
6136    }
6137
6138    /**
6139     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6140     * instant, returns {@code null}.
6141     */
6142    private String getInstantAppPackageName(int callingUid) {
6143        // If the caller is an isolated app use the owner's uid for the lookup.
6144        if (Process.isIsolated(callingUid)) {
6145            callingUid = mIsolatedOwners.get(callingUid);
6146        }
6147        final int appId = UserHandle.getAppId(callingUid);
6148        synchronized (mPackages) {
6149            final Object obj = mSettings.getUserIdLPr(appId);
6150            if (obj instanceof PackageSetting) {
6151                final PackageSetting ps = (PackageSetting) obj;
6152                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6153                return isInstantApp ? ps.pkg.packageName : null;
6154            }
6155        }
6156        return null;
6157    }
6158
6159    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6160            String resolvedType, int flags, int userId) {
6161        return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false);
6162    }
6163
6164    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6165            String resolvedType, int flags, int userId, boolean includeInstantApps) {
6166        if (!sUserManager.exists(userId)) return Collections.emptyList();
6167        final int callingUid = Binder.getCallingUid();
6168        final String instantAppPkgName = getInstantAppPackageName(callingUid);
6169        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
6170        enforceCrossUserPermission(callingUid, userId,
6171                false /* requireFullPermission */, false /* checkShell */,
6172                "query intent activities");
6173        ComponentName comp = intent.getComponent();
6174        if (comp == null) {
6175            if (intent.getSelector() != null) {
6176                intent = intent.getSelector();
6177                comp = intent.getComponent();
6178            }
6179        }
6180
6181        if (comp != null) {
6182            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6183            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6184            if (ai != null) {
6185                // When specifying an explicit component, we prevent the activity from being
6186                // used when either 1) the calling package is normal and the activity is within
6187                // an ephemeral application or 2) the calling package is ephemeral and the
6188                // activity is not visible to ephemeral applications.
6189                final boolean matchInstantApp =
6190                        (flags & PackageManager.MATCH_INSTANT) != 0;
6191                final boolean matchVisibleToInstantAppOnly =
6192                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6193                final boolean isCallerInstantApp =
6194                        instantAppPkgName != null;
6195                final boolean isTargetSameInstantApp =
6196                        comp.getPackageName().equals(instantAppPkgName);
6197                final boolean isTargetInstantApp =
6198                        (ai.applicationInfo.privateFlags
6199                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6200                final boolean isTargetHiddenFromInstantApp =
6201                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
6202                final boolean blockResolution =
6203                        !isTargetSameInstantApp
6204                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6205                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6206                                        && isTargetHiddenFromInstantApp));
6207                if (!blockResolution) {
6208                    final ResolveInfo ri = new ResolveInfo();
6209                    ri.activityInfo = ai;
6210                    list.add(ri);
6211                }
6212            }
6213            return applyPostResolutionFilter(list, instantAppPkgName);
6214        }
6215
6216        // reader
6217        boolean sortResult = false;
6218        boolean addEphemeral = false;
6219        List<ResolveInfo> result;
6220        final String pkgName = intent.getPackage();
6221        final boolean ephemeralDisabled = isEphemeralDisabled();
6222        synchronized (mPackages) {
6223            if (pkgName == null) {
6224                List<CrossProfileIntentFilter> matchingFilters =
6225                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6226                // Check for results that need to skip the current profile.
6227                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6228                        resolvedType, flags, userId);
6229                if (xpResolveInfo != null) {
6230                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6231                    xpResult.add(xpResolveInfo);
6232                    return applyPostResolutionFilter(
6233                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6234                }
6235
6236                // Check for results in the current profile.
6237                result = filterIfNotSystemUser(mActivities.queryIntent(
6238                        intent, resolvedType, flags, userId), userId);
6239                addEphemeral = !ephemeralDisabled
6240                        && isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
6241                // Check for cross profile results.
6242                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6243                xpResolveInfo = queryCrossProfileIntents(
6244                        matchingFilters, intent, resolvedType, flags, userId,
6245                        hasNonNegativePriorityResult);
6246                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6247                    boolean isVisibleToUser = filterIfNotSystemUser(
6248                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6249                    if (isVisibleToUser) {
6250                        result.add(xpResolveInfo);
6251                        sortResult = true;
6252                    }
6253                }
6254                if (hasWebURI(intent)) {
6255                    CrossProfileDomainInfo xpDomainInfo = null;
6256                    final UserInfo parent = getProfileParent(userId);
6257                    if (parent != null) {
6258                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6259                                flags, userId, parent.id);
6260                    }
6261                    if (xpDomainInfo != null) {
6262                        if (xpResolveInfo != null) {
6263                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6264                            // in the result.
6265                            result.remove(xpResolveInfo);
6266                        }
6267                        if (result.size() == 0 && !addEphemeral) {
6268                            // No result in current profile, but found candidate in parent user.
6269                            // And we are not going to add emphemeral app, so we can return the
6270                            // result straight away.
6271                            result.add(xpDomainInfo.resolveInfo);
6272                            return applyPostResolutionFilter(result, instantAppPkgName);
6273                        }
6274                    } else if (result.size() <= 1 && !addEphemeral) {
6275                        // No result in parent user and <= 1 result in current profile, and we
6276                        // are not going to add emphemeral app, so we can return the result without
6277                        // further processing.
6278                        return applyPostResolutionFilter(result, instantAppPkgName);
6279                    }
6280                    // We have more than one candidate (combining results from current and parent
6281                    // profile), so we need filtering and sorting.
6282                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6283                            intent, flags, result, xpDomainInfo, userId);
6284                    sortResult = true;
6285                }
6286            } else {
6287                final PackageParser.Package pkg = mPackages.get(pkgName);
6288                if (pkg != null) {
6289                    return applyPostResolutionFilter(filterIfNotSystemUser(
6290                            mActivities.queryIntentForPackage(
6291                                    intent, resolvedType, flags, pkg.activities, userId),
6292                            userId), instantAppPkgName);
6293                } else {
6294                    // the caller wants to resolve for a particular package; however, there
6295                    // were no installed results, so, try to find an ephemeral result
6296                    addEphemeral = !ephemeralDisabled
6297                            && isEphemeralAllowed(
6298                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6299                    result = new ArrayList<ResolveInfo>();
6300                }
6301            }
6302        }
6303        if (addEphemeral) {
6304            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6305            final InstantAppRequest requestObject = new InstantAppRequest(
6306                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
6307                    null /*callingPackage*/, userId);
6308            final AuxiliaryResolveInfo auxiliaryResponse =
6309                    InstantAppResolver.doInstantAppResolutionPhaseOne(
6310                            mContext, mInstantAppResolverConnection, requestObject);
6311            if (auxiliaryResponse != null) {
6312                if (DEBUG_EPHEMERAL) {
6313                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6314                }
6315                final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6316                ephemeralInstaller.activityInfo = new ActivityInfo(mInstantAppInstallerActivity);
6317                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6318                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6319                // make sure this resolver is the default
6320                ephemeralInstaller.isDefault = true;
6321                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6322                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6323                // add a non-generic filter
6324                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6325                ephemeralInstaller.filter.addDataPath(
6326                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6327                ephemeralInstaller.instantAppAvailable = true;
6328                result.add(ephemeralInstaller);
6329            }
6330            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6331        }
6332        if (sortResult) {
6333            Collections.sort(result, mResolvePrioritySorter);
6334        }
6335        return applyPostResolutionFilter(result, instantAppPkgName);
6336    }
6337
6338    private static class CrossProfileDomainInfo {
6339        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6340        ResolveInfo resolveInfo;
6341        /* Best domain verification status of the activities found in the other profile */
6342        int bestDomainVerificationStatus;
6343    }
6344
6345    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6346            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6347        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6348                sourceUserId)) {
6349            return null;
6350        }
6351        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6352                resolvedType, flags, parentUserId);
6353
6354        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6355            return null;
6356        }
6357        CrossProfileDomainInfo result = null;
6358        int size = resultTargetUser.size();
6359        for (int i = 0; i < size; i++) {
6360            ResolveInfo riTargetUser = resultTargetUser.get(i);
6361            // Intent filter verification is only for filters that specify a host. So don't return
6362            // those that handle all web uris.
6363            if (riTargetUser.handleAllWebDataURI) {
6364                continue;
6365            }
6366            String packageName = riTargetUser.activityInfo.packageName;
6367            PackageSetting ps = mSettings.mPackages.get(packageName);
6368            if (ps == null) {
6369                continue;
6370            }
6371            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6372            int status = (int)(verificationState >> 32);
6373            if (result == null) {
6374                result = new CrossProfileDomainInfo();
6375                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6376                        sourceUserId, parentUserId);
6377                result.bestDomainVerificationStatus = status;
6378            } else {
6379                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6380                        result.bestDomainVerificationStatus);
6381            }
6382        }
6383        // Don't consider matches with status NEVER across profiles.
6384        if (result != null && result.bestDomainVerificationStatus
6385                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6386            return null;
6387        }
6388        return result;
6389    }
6390
6391    /**
6392     * Verification statuses are ordered from the worse to the best, except for
6393     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6394     */
6395    private int bestDomainVerificationStatus(int status1, int status2) {
6396        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6397            return status2;
6398        }
6399        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6400            return status1;
6401        }
6402        return (int) MathUtils.max(status1, status2);
6403    }
6404
6405    private boolean isUserEnabled(int userId) {
6406        long callingId = Binder.clearCallingIdentity();
6407        try {
6408            UserInfo userInfo = sUserManager.getUserInfo(userId);
6409            return userInfo != null && userInfo.isEnabled();
6410        } finally {
6411            Binder.restoreCallingIdentity(callingId);
6412        }
6413    }
6414
6415    /**
6416     * Filter out activities with systemUserOnly flag set, when current user is not System.
6417     *
6418     * @return filtered list
6419     */
6420    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6421        if (userId == UserHandle.USER_SYSTEM) {
6422            return resolveInfos;
6423        }
6424        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6425            ResolveInfo info = resolveInfos.get(i);
6426            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6427                resolveInfos.remove(i);
6428            }
6429        }
6430        return resolveInfos;
6431    }
6432
6433    /**
6434     * Filters out ephemeral activities.
6435     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6436     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6437     *
6438     * @param resolveInfos The pre-filtered list of resolved activities
6439     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6440     *          is performed.
6441     * @return A filtered list of resolved activities.
6442     */
6443    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6444            String ephemeralPkgName) {
6445        // TODO: When adding on-demand split support for non-instant apps, remove this check
6446        // and always apply post filtering
6447        if (ephemeralPkgName == null) {
6448            return resolveInfos;
6449        }
6450        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6451            final ResolveInfo info = resolveInfos.get(i);
6452            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6453            // allow activities that are defined in the provided package
6454            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6455                if (info.activityInfo.splitName != null
6456                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6457                                info.activityInfo.splitName)) {
6458                    // requested activity is defined in a split that hasn't been installed yet.
6459                    // add the installer to the resolve list
6460                    if (DEBUG_EPHEMERAL) {
6461                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6462                    }
6463                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6464                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6465                            info.activityInfo.packageName, info.activityInfo.splitName,
6466                            info.activityInfo.applicationInfo.versionCode);
6467                    // make sure this resolver is the default
6468                    installerInfo.isDefault = true;
6469                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6470                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6471                    // add a non-generic filter
6472                    installerInfo.filter = new IntentFilter();
6473                    // load resources from the correct package
6474                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6475                    resolveInfos.set(i, installerInfo);
6476                }
6477                continue;
6478            }
6479            // allow activities that have been explicitly exposed to ephemeral apps
6480            if (!isEphemeralApp
6481                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
6482                continue;
6483            }
6484            resolveInfos.remove(i);
6485        }
6486        return resolveInfos;
6487    }
6488
6489    /**
6490     * @param resolveInfos list of resolve infos in descending priority order
6491     * @return if the list contains a resolve info with non-negative priority
6492     */
6493    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6494        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6495    }
6496
6497    private static boolean hasWebURI(Intent intent) {
6498        if (intent.getData() == null) {
6499            return false;
6500        }
6501        final String scheme = intent.getScheme();
6502        if (TextUtils.isEmpty(scheme)) {
6503            return false;
6504        }
6505        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6506    }
6507
6508    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6509            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6510            int userId) {
6511        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6512
6513        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6514            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6515                    candidates.size());
6516        }
6517
6518        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6519        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6520        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6521        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6522        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6523        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6524
6525        synchronized (mPackages) {
6526            final int count = candidates.size();
6527            // First, try to use linked apps. Partition the candidates into four lists:
6528            // one for the final results, one for the "do not use ever", one for "undefined status"
6529            // and finally one for "browser app type".
6530            for (int n=0; n<count; n++) {
6531                ResolveInfo info = candidates.get(n);
6532                String packageName = info.activityInfo.packageName;
6533                PackageSetting ps = mSettings.mPackages.get(packageName);
6534                if (ps != null) {
6535                    // Add to the special match all list (Browser use case)
6536                    if (info.handleAllWebDataURI) {
6537                        matchAllList.add(info);
6538                        continue;
6539                    }
6540                    // Try to get the status from User settings first
6541                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6542                    int status = (int)(packedStatus >> 32);
6543                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6544                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6545                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6546                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6547                                    + " : linkgen=" + linkGeneration);
6548                        }
6549                        // Use link-enabled generation as preferredOrder, i.e.
6550                        // prefer newly-enabled over earlier-enabled.
6551                        info.preferredOrder = linkGeneration;
6552                        alwaysList.add(info);
6553                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6554                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6555                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6556                        }
6557                        neverList.add(info);
6558                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6559                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6560                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6561                        }
6562                        alwaysAskList.add(info);
6563                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6564                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6565                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6566                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6567                        }
6568                        undefinedList.add(info);
6569                    }
6570                }
6571            }
6572
6573            // We'll want to include browser possibilities in a few cases
6574            boolean includeBrowser = false;
6575
6576            // First try to add the "always" resolution(s) for the current user, if any
6577            if (alwaysList.size() > 0) {
6578                result.addAll(alwaysList);
6579            } else {
6580                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6581                result.addAll(undefinedList);
6582                // Maybe add one for the other profile.
6583                if (xpDomainInfo != null && (
6584                        xpDomainInfo.bestDomainVerificationStatus
6585                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6586                    result.add(xpDomainInfo.resolveInfo);
6587                }
6588                includeBrowser = true;
6589            }
6590
6591            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6592            // If there were 'always' entries their preferred order has been set, so we also
6593            // back that off to make the alternatives equivalent
6594            if (alwaysAskList.size() > 0) {
6595                for (ResolveInfo i : result) {
6596                    i.preferredOrder = 0;
6597                }
6598                result.addAll(alwaysAskList);
6599                includeBrowser = true;
6600            }
6601
6602            if (includeBrowser) {
6603                // Also add browsers (all of them or only the default one)
6604                if (DEBUG_DOMAIN_VERIFICATION) {
6605                    Slog.v(TAG, "   ...including browsers in candidate set");
6606                }
6607                if ((matchFlags & MATCH_ALL) != 0) {
6608                    result.addAll(matchAllList);
6609                } else {
6610                    // Browser/generic handling case.  If there's a default browser, go straight
6611                    // to that (but only if there is no other higher-priority match).
6612                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6613                    int maxMatchPrio = 0;
6614                    ResolveInfo defaultBrowserMatch = null;
6615                    final int numCandidates = matchAllList.size();
6616                    for (int n = 0; n < numCandidates; n++) {
6617                        ResolveInfo info = matchAllList.get(n);
6618                        // track the highest overall match priority...
6619                        if (info.priority > maxMatchPrio) {
6620                            maxMatchPrio = info.priority;
6621                        }
6622                        // ...and the highest-priority default browser match
6623                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6624                            if (defaultBrowserMatch == null
6625                                    || (defaultBrowserMatch.priority < info.priority)) {
6626                                if (debug) {
6627                                    Slog.v(TAG, "Considering default browser match " + info);
6628                                }
6629                                defaultBrowserMatch = info;
6630                            }
6631                        }
6632                    }
6633                    if (defaultBrowserMatch != null
6634                            && defaultBrowserMatch.priority >= maxMatchPrio
6635                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6636                    {
6637                        if (debug) {
6638                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6639                        }
6640                        result.add(defaultBrowserMatch);
6641                    } else {
6642                        result.addAll(matchAllList);
6643                    }
6644                }
6645
6646                // If there is nothing selected, add all candidates and remove the ones that the user
6647                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6648                if (result.size() == 0) {
6649                    result.addAll(candidates);
6650                    result.removeAll(neverList);
6651                }
6652            }
6653        }
6654        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6655            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6656                    result.size());
6657            for (ResolveInfo info : result) {
6658                Slog.v(TAG, "  + " + info.activityInfo);
6659            }
6660        }
6661        return result;
6662    }
6663
6664    // Returns a packed value as a long:
6665    //
6666    // high 'int'-sized word: link status: undefined/ask/never/always.
6667    // low 'int'-sized word: relative priority among 'always' results.
6668    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6669        long result = ps.getDomainVerificationStatusForUser(userId);
6670        // if none available, get the master status
6671        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6672            if (ps.getIntentFilterVerificationInfo() != null) {
6673                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6674            }
6675        }
6676        return result;
6677    }
6678
6679    private ResolveInfo querySkipCurrentProfileIntents(
6680            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6681            int flags, int sourceUserId) {
6682        if (matchingFilters != null) {
6683            int size = matchingFilters.size();
6684            for (int i = 0; i < size; i ++) {
6685                CrossProfileIntentFilter filter = matchingFilters.get(i);
6686                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6687                    // Checking if there are activities in the target user that can handle the
6688                    // intent.
6689                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6690                            resolvedType, flags, sourceUserId);
6691                    if (resolveInfo != null) {
6692                        return resolveInfo;
6693                    }
6694                }
6695            }
6696        }
6697        return null;
6698    }
6699
6700    // Return matching ResolveInfo in target user if any.
6701    private ResolveInfo queryCrossProfileIntents(
6702            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6703            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6704        if (matchingFilters != null) {
6705            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6706            // match the same intent. For performance reasons, it is better not to
6707            // run queryIntent twice for the same userId
6708            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6709            int size = matchingFilters.size();
6710            for (int i = 0; i < size; i++) {
6711                CrossProfileIntentFilter filter = matchingFilters.get(i);
6712                int targetUserId = filter.getTargetUserId();
6713                boolean skipCurrentProfile =
6714                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6715                boolean skipCurrentProfileIfNoMatchFound =
6716                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6717                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6718                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6719                    // Checking if there are activities in the target user that can handle the
6720                    // intent.
6721                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6722                            resolvedType, flags, sourceUserId);
6723                    if (resolveInfo != null) return resolveInfo;
6724                    alreadyTriedUserIds.put(targetUserId, true);
6725                }
6726            }
6727        }
6728        return null;
6729    }
6730
6731    /**
6732     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6733     * will forward the intent to the filter's target user.
6734     * Otherwise, returns null.
6735     */
6736    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6737            String resolvedType, int flags, int sourceUserId) {
6738        int targetUserId = filter.getTargetUserId();
6739        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6740                resolvedType, flags, targetUserId);
6741        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6742            // If all the matches in the target profile are suspended, return null.
6743            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6744                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6745                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6746                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6747                            targetUserId);
6748                }
6749            }
6750        }
6751        return null;
6752    }
6753
6754    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6755            int sourceUserId, int targetUserId) {
6756        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6757        long ident = Binder.clearCallingIdentity();
6758        boolean targetIsProfile;
6759        try {
6760            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6761        } finally {
6762            Binder.restoreCallingIdentity(ident);
6763        }
6764        String className;
6765        if (targetIsProfile) {
6766            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6767        } else {
6768            className = FORWARD_INTENT_TO_PARENT;
6769        }
6770        ComponentName forwardingActivityComponentName = new ComponentName(
6771                mAndroidApplication.packageName, className);
6772        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6773                sourceUserId);
6774        if (!targetIsProfile) {
6775            forwardingActivityInfo.showUserIcon = targetUserId;
6776            forwardingResolveInfo.noResourceId = true;
6777        }
6778        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6779        forwardingResolveInfo.priority = 0;
6780        forwardingResolveInfo.preferredOrder = 0;
6781        forwardingResolveInfo.match = 0;
6782        forwardingResolveInfo.isDefault = true;
6783        forwardingResolveInfo.filter = filter;
6784        forwardingResolveInfo.targetUserId = targetUserId;
6785        return forwardingResolveInfo;
6786    }
6787
6788    @Override
6789    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6790            Intent[] specifics, String[] specificTypes, Intent intent,
6791            String resolvedType, int flags, int userId) {
6792        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6793                specificTypes, intent, resolvedType, flags, userId));
6794    }
6795
6796    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6797            Intent[] specifics, String[] specificTypes, Intent intent,
6798            String resolvedType, int flags, int userId) {
6799        if (!sUserManager.exists(userId)) return Collections.emptyList();
6800        final int callingUid = Binder.getCallingUid();
6801        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
6802                false /*includeInstantApps*/);
6803        enforceCrossUserPermission(callingUid, userId,
6804                false /*requireFullPermission*/, false /*checkShell*/,
6805                "query intent activity options");
6806        final String resultsAction = intent.getAction();
6807
6808        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6809                | PackageManager.GET_RESOLVED_FILTER, userId);
6810
6811        if (DEBUG_INTENT_MATCHING) {
6812            Log.v(TAG, "Query " + intent + ": " + results);
6813        }
6814
6815        int specificsPos = 0;
6816        int N;
6817
6818        // todo: note that the algorithm used here is O(N^2).  This
6819        // isn't a problem in our current environment, but if we start running
6820        // into situations where we have more than 5 or 10 matches then this
6821        // should probably be changed to something smarter...
6822
6823        // First we go through and resolve each of the specific items
6824        // that were supplied, taking care of removing any corresponding
6825        // duplicate items in the generic resolve list.
6826        if (specifics != null) {
6827            for (int i=0; i<specifics.length; i++) {
6828                final Intent sintent = specifics[i];
6829                if (sintent == null) {
6830                    continue;
6831                }
6832
6833                if (DEBUG_INTENT_MATCHING) {
6834                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6835                }
6836
6837                String action = sintent.getAction();
6838                if (resultsAction != null && resultsAction.equals(action)) {
6839                    // If this action was explicitly requested, then don't
6840                    // remove things that have it.
6841                    action = null;
6842                }
6843
6844                ResolveInfo ri = null;
6845                ActivityInfo ai = null;
6846
6847                ComponentName comp = sintent.getComponent();
6848                if (comp == null) {
6849                    ri = resolveIntent(
6850                        sintent,
6851                        specificTypes != null ? specificTypes[i] : null,
6852                            flags, userId);
6853                    if (ri == null) {
6854                        continue;
6855                    }
6856                    if (ri == mResolveInfo) {
6857                        // ACK!  Must do something better with this.
6858                    }
6859                    ai = ri.activityInfo;
6860                    comp = new ComponentName(ai.applicationInfo.packageName,
6861                            ai.name);
6862                } else {
6863                    ai = getActivityInfo(comp, flags, userId);
6864                    if (ai == null) {
6865                        continue;
6866                    }
6867                }
6868
6869                // Look for any generic query activities that are duplicates
6870                // of this specific one, and remove them from the results.
6871                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6872                N = results.size();
6873                int j;
6874                for (j=specificsPos; j<N; j++) {
6875                    ResolveInfo sri = results.get(j);
6876                    if ((sri.activityInfo.name.equals(comp.getClassName())
6877                            && sri.activityInfo.applicationInfo.packageName.equals(
6878                                    comp.getPackageName()))
6879                        || (action != null && sri.filter.matchAction(action))) {
6880                        results.remove(j);
6881                        if (DEBUG_INTENT_MATCHING) Log.v(
6882                            TAG, "Removing duplicate item from " + j
6883                            + " due to specific " + specificsPos);
6884                        if (ri == null) {
6885                            ri = sri;
6886                        }
6887                        j--;
6888                        N--;
6889                    }
6890                }
6891
6892                // Add this specific item to its proper place.
6893                if (ri == null) {
6894                    ri = new ResolveInfo();
6895                    ri.activityInfo = ai;
6896                }
6897                results.add(specificsPos, ri);
6898                ri.specificIndex = i;
6899                specificsPos++;
6900            }
6901        }
6902
6903        // Now we go through the remaining generic results and remove any
6904        // duplicate actions that are found here.
6905        N = results.size();
6906        for (int i=specificsPos; i<N-1; i++) {
6907            final ResolveInfo rii = results.get(i);
6908            if (rii.filter == null) {
6909                continue;
6910            }
6911
6912            // Iterate over all of the actions of this result's intent
6913            // filter...  typically this should be just one.
6914            final Iterator<String> it = rii.filter.actionsIterator();
6915            if (it == null) {
6916                continue;
6917            }
6918            while (it.hasNext()) {
6919                final String action = it.next();
6920                if (resultsAction != null && resultsAction.equals(action)) {
6921                    // If this action was explicitly requested, then don't
6922                    // remove things that have it.
6923                    continue;
6924                }
6925                for (int j=i+1; j<N; j++) {
6926                    final ResolveInfo rij = results.get(j);
6927                    if (rij.filter != null && rij.filter.hasAction(action)) {
6928                        results.remove(j);
6929                        if (DEBUG_INTENT_MATCHING) Log.v(
6930                            TAG, "Removing duplicate item from " + j
6931                            + " due to action " + action + " at " + i);
6932                        j--;
6933                        N--;
6934                    }
6935                }
6936            }
6937
6938            // If the caller didn't request filter information, drop it now
6939            // so we don't have to marshall/unmarshall it.
6940            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6941                rii.filter = null;
6942            }
6943        }
6944
6945        // Filter out the caller activity if so requested.
6946        if (caller != null) {
6947            N = results.size();
6948            for (int i=0; i<N; i++) {
6949                ActivityInfo ainfo = results.get(i).activityInfo;
6950                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6951                        && caller.getClassName().equals(ainfo.name)) {
6952                    results.remove(i);
6953                    break;
6954                }
6955            }
6956        }
6957
6958        // If the caller didn't request filter information,
6959        // drop them now so we don't have to
6960        // marshall/unmarshall it.
6961        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6962            N = results.size();
6963            for (int i=0; i<N; i++) {
6964                results.get(i).filter = null;
6965            }
6966        }
6967
6968        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6969        return results;
6970    }
6971
6972    @Override
6973    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6974            String resolvedType, int flags, int userId) {
6975        return new ParceledListSlice<>(
6976                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6977    }
6978
6979    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6980            String resolvedType, int flags, int userId) {
6981        if (!sUserManager.exists(userId)) return Collections.emptyList();
6982        final int callingUid = Binder.getCallingUid();
6983        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
6984                false /*includeInstantApps*/);
6985        ComponentName comp = intent.getComponent();
6986        if (comp == null) {
6987            if (intent.getSelector() != null) {
6988                intent = intent.getSelector();
6989                comp = intent.getComponent();
6990            }
6991        }
6992        if (comp != null) {
6993            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6994            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6995            if (ai != null) {
6996                ResolveInfo ri = new ResolveInfo();
6997                ri.activityInfo = ai;
6998                list.add(ri);
6999            }
7000            return list;
7001        }
7002
7003        // reader
7004        synchronized (mPackages) {
7005            String pkgName = intent.getPackage();
7006            if (pkgName == null) {
7007                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
7008            }
7009            final PackageParser.Package pkg = mPackages.get(pkgName);
7010            if (pkg != null) {
7011                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
7012                        userId);
7013            }
7014            return Collections.emptyList();
7015        }
7016    }
7017
7018    @Override
7019    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7020        final int callingUid = Binder.getCallingUid();
7021        return resolveServiceInternal(
7022                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7023    }
7024
7025    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7026            int userId, int callingUid, boolean includeInstantApps) {
7027        if (!sUserManager.exists(userId)) return null;
7028        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7029        List<ResolveInfo> query = queryIntentServicesInternal(
7030                intent, resolvedType, flags, userId, callingUid, includeInstantApps);
7031        if (query != null) {
7032            if (query.size() >= 1) {
7033                // If there is more than one service with the same priority,
7034                // just arbitrarily pick the first one.
7035                return query.get(0);
7036            }
7037        }
7038        return null;
7039    }
7040
7041    @Override
7042    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7043            String resolvedType, int flags, int userId) {
7044        final int callingUid = Binder.getCallingUid();
7045        return new ParceledListSlice<>(queryIntentServicesInternal(
7046                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7047    }
7048
7049    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7050            String resolvedType, int flags, int userId, int callingUid,
7051            boolean includeInstantApps) {
7052        if (!sUserManager.exists(userId)) return Collections.emptyList();
7053        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7054        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7055        ComponentName comp = intent.getComponent();
7056        if (comp == null) {
7057            if (intent.getSelector() != null) {
7058                intent = intent.getSelector();
7059                comp = intent.getComponent();
7060            }
7061        }
7062        if (comp != null) {
7063            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7064            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7065            if (si != null) {
7066                // When specifying an explicit component, we prevent the service from being
7067                // used when either 1) the service is in an instant application and the
7068                // caller is not the same instant application or 2) the calling package is
7069                // ephemeral and the activity is not visible to ephemeral applications.
7070                final boolean matchVisibleToInstantAppOnly =
7071                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7072                final boolean isCallerInstantApp =
7073                        instantAppPkgName != null;
7074                final boolean isTargetSameInstantApp =
7075                        comp.getPackageName().equals(instantAppPkgName);
7076                final boolean isTargetHiddenFromInstantApp =
7077                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
7078                final boolean blockResolution =
7079                        !isTargetSameInstantApp
7080                        && ((matchVisibleToInstantAppOnly && isCallerInstantApp
7081                                        && isTargetHiddenFromInstantApp));
7082                if (!blockResolution) {
7083                    final ResolveInfo ri = new ResolveInfo();
7084                    ri.serviceInfo = si;
7085                    list.add(ri);
7086                }
7087            }
7088            return list;
7089        }
7090
7091        // reader
7092        synchronized (mPackages) {
7093            String pkgName = intent.getPackage();
7094            if (pkgName == null) {
7095                return applyPostServiceResolutionFilter(
7096                        mServices.queryIntent(intent, resolvedType, flags, userId),
7097                        instantAppPkgName);
7098            }
7099            final PackageParser.Package pkg = mPackages.get(pkgName);
7100            if (pkg != null) {
7101                return applyPostServiceResolutionFilter(
7102                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7103                                userId),
7104                        instantAppPkgName);
7105            }
7106            return Collections.emptyList();
7107        }
7108    }
7109
7110    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7111            String instantAppPkgName) {
7112        // TODO: When adding on-demand split support for non-instant apps, remove this check
7113        // and always apply post filtering
7114        if (instantAppPkgName == null) {
7115            return resolveInfos;
7116        }
7117        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7118            final ResolveInfo info = resolveInfos.get(i);
7119            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7120            // allow services that are defined in the provided package
7121            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7122                if (info.serviceInfo.splitName != null
7123                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7124                                info.serviceInfo.splitName)) {
7125                    // requested service is defined in a split that hasn't been installed yet.
7126                    // add the installer to the resolve list
7127                    if (DEBUG_EPHEMERAL) {
7128                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7129                    }
7130                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7131                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7132                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7133                            info.serviceInfo.applicationInfo.versionCode);
7134                    // make sure this resolver is the default
7135                    installerInfo.isDefault = true;
7136                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7137                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7138                    // add a non-generic filter
7139                    installerInfo.filter = new IntentFilter();
7140                    // load resources from the correct package
7141                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7142                    resolveInfos.set(i, installerInfo);
7143                }
7144                continue;
7145            }
7146            // allow services that have been explicitly exposed to ephemeral apps
7147            if (!isEphemeralApp
7148                    && ((info.serviceInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
7149                continue;
7150            }
7151            resolveInfos.remove(i);
7152        }
7153        return resolveInfos;
7154    }
7155
7156    @Override
7157    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7158            String resolvedType, int flags, int userId) {
7159        return new ParceledListSlice<>(
7160                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7161    }
7162
7163    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7164            Intent intent, String resolvedType, int flags, int userId) {
7165        if (!sUserManager.exists(userId)) return Collections.emptyList();
7166        final int callingUid = Binder.getCallingUid();
7167        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7168                false /*includeInstantApps*/);
7169        ComponentName comp = intent.getComponent();
7170        if (comp == null) {
7171            if (intent.getSelector() != null) {
7172                intent = intent.getSelector();
7173                comp = intent.getComponent();
7174            }
7175        }
7176        if (comp != null) {
7177            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7178            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7179            if (pi != null) {
7180                final ResolveInfo ri = new ResolveInfo();
7181                ri.providerInfo = pi;
7182                list.add(ri);
7183            }
7184            return list;
7185        }
7186
7187        // reader
7188        synchronized (mPackages) {
7189            String pkgName = intent.getPackage();
7190            if (pkgName == null) {
7191                return mProviders.queryIntent(intent, resolvedType, flags, userId);
7192            }
7193            final PackageParser.Package pkg = mPackages.get(pkgName);
7194            if (pkg != null) {
7195                return mProviders.queryIntentForPackage(
7196                        intent, resolvedType, flags, pkg.providers, userId);
7197            }
7198            return Collections.emptyList();
7199        }
7200    }
7201
7202    @Override
7203    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7204        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7205        flags = updateFlagsForPackage(flags, userId, null);
7206        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7207        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7208                true /* requireFullPermission */, false /* checkShell */,
7209                "get installed packages");
7210
7211        // writer
7212        synchronized (mPackages) {
7213            ArrayList<PackageInfo> list;
7214            if (listUninstalled) {
7215                list = new ArrayList<>(mSettings.mPackages.size());
7216                for (PackageSetting ps : mSettings.mPackages.values()) {
7217                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7218                        continue;
7219                    }
7220                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7221                    if (pi != null) {
7222                        list.add(pi);
7223                    }
7224                }
7225            } else {
7226                list = new ArrayList<>(mPackages.size());
7227                for (PackageParser.Package p : mPackages.values()) {
7228                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
7229                            Binder.getCallingUid(), userId)) {
7230                        continue;
7231                    }
7232                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7233                            p.mExtras, flags, userId);
7234                    if (pi != null) {
7235                        list.add(pi);
7236                    }
7237                }
7238            }
7239
7240            return new ParceledListSlice<>(list);
7241        }
7242    }
7243
7244    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7245            String[] permissions, boolean[] tmp, int flags, int userId) {
7246        int numMatch = 0;
7247        final PermissionsState permissionsState = ps.getPermissionsState();
7248        for (int i=0; i<permissions.length; i++) {
7249            final String permission = permissions[i];
7250            if (permissionsState.hasPermission(permission, userId)) {
7251                tmp[i] = true;
7252                numMatch++;
7253            } else {
7254                tmp[i] = false;
7255            }
7256        }
7257        if (numMatch == 0) {
7258            return;
7259        }
7260        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7261
7262        // The above might return null in cases of uninstalled apps or install-state
7263        // skew across users/profiles.
7264        if (pi != null) {
7265            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7266                if (numMatch == permissions.length) {
7267                    pi.requestedPermissions = permissions;
7268                } else {
7269                    pi.requestedPermissions = new String[numMatch];
7270                    numMatch = 0;
7271                    for (int i=0; i<permissions.length; i++) {
7272                        if (tmp[i]) {
7273                            pi.requestedPermissions[numMatch] = permissions[i];
7274                            numMatch++;
7275                        }
7276                    }
7277                }
7278            }
7279            list.add(pi);
7280        }
7281    }
7282
7283    @Override
7284    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7285            String[] permissions, int flags, int userId) {
7286        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7287        flags = updateFlagsForPackage(flags, userId, permissions);
7288        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7289                true /* requireFullPermission */, false /* checkShell */,
7290                "get packages holding permissions");
7291        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7292
7293        // writer
7294        synchronized (mPackages) {
7295            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7296            boolean[] tmpBools = new boolean[permissions.length];
7297            if (listUninstalled) {
7298                for (PackageSetting ps : mSettings.mPackages.values()) {
7299                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7300                            userId);
7301                }
7302            } else {
7303                for (PackageParser.Package pkg : mPackages.values()) {
7304                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7305                    if (ps != null) {
7306                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7307                                userId);
7308                    }
7309                }
7310            }
7311
7312            return new ParceledListSlice<PackageInfo>(list);
7313        }
7314    }
7315
7316    @Override
7317    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7318        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7319        flags = updateFlagsForApplication(flags, userId, null);
7320        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7321
7322        // writer
7323        synchronized (mPackages) {
7324            ArrayList<ApplicationInfo> list;
7325            if (listUninstalled) {
7326                list = new ArrayList<>(mSettings.mPackages.size());
7327                for (PackageSetting ps : mSettings.mPackages.values()) {
7328                    ApplicationInfo ai;
7329                    int effectiveFlags = flags;
7330                    if (ps.isSystem()) {
7331                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7332                    }
7333                    if (ps.pkg != null) {
7334                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7335                            continue;
7336                        }
7337                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7338                                ps.readUserState(userId), userId);
7339                        if (ai != null) {
7340                            rebaseEnabledOverlays(ai, userId);
7341                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7342                        }
7343                    } else {
7344                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7345                        // and already converts to externally visible package name
7346                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7347                                Binder.getCallingUid(), effectiveFlags, userId);
7348                    }
7349                    if (ai != null) {
7350                        list.add(ai);
7351                    }
7352                }
7353            } else {
7354                list = new ArrayList<>(mPackages.size());
7355                for (PackageParser.Package p : mPackages.values()) {
7356                    if (p.mExtras != null) {
7357                        PackageSetting ps = (PackageSetting) p.mExtras;
7358                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7359                            continue;
7360                        }
7361                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7362                                ps.readUserState(userId), userId);
7363                        if (ai != null) {
7364                            rebaseEnabledOverlays(ai, userId);
7365                            ai.packageName = resolveExternalPackageNameLPr(p);
7366                            list.add(ai);
7367                        }
7368                    }
7369                }
7370            }
7371
7372            return new ParceledListSlice<>(list);
7373        }
7374    }
7375
7376    @Override
7377    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7378        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7379            return null;
7380        }
7381
7382        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7383                "getEphemeralApplications");
7384        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7385                true /* requireFullPermission */, false /* checkShell */,
7386                "getEphemeralApplications");
7387        synchronized (mPackages) {
7388            List<InstantAppInfo> instantApps = mInstantAppRegistry
7389                    .getInstantAppsLPr(userId);
7390            if (instantApps != null) {
7391                return new ParceledListSlice<>(instantApps);
7392            }
7393        }
7394        return null;
7395    }
7396
7397    @Override
7398    public boolean isInstantApp(String packageName, int userId) {
7399        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7400                true /* requireFullPermission */, false /* checkShell */,
7401                "isInstantApp");
7402        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7403            return false;
7404        }
7405        int uid = Binder.getCallingUid();
7406        if (Process.isIsolated(uid)) {
7407            uid = mIsolatedOwners.get(uid);
7408        }
7409
7410        synchronized (mPackages) {
7411            final PackageSetting ps = mSettings.mPackages.get(packageName);
7412            PackageParser.Package pkg = mPackages.get(packageName);
7413            final boolean returnAllowed =
7414                    ps != null
7415                    && (isCallerSameApp(packageName, uid)
7416                            || mContext.checkCallingOrSelfPermission(
7417                                    android.Manifest.permission.ACCESS_INSTANT_APPS)
7418                                            == PERMISSION_GRANTED
7419                            || mInstantAppRegistry.isInstantAccessGranted(
7420                                    userId, UserHandle.getAppId(uid), ps.appId));
7421            if (returnAllowed) {
7422                return ps.getInstantApp(userId);
7423            }
7424        }
7425        return false;
7426    }
7427
7428    @Override
7429    public byte[] getInstantAppCookie(String packageName, int userId) {
7430        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7431            return null;
7432        }
7433
7434        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7435                true /* requireFullPermission */, false /* checkShell */,
7436                "getInstantAppCookie");
7437        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7438            return null;
7439        }
7440        synchronized (mPackages) {
7441            return mInstantAppRegistry.getInstantAppCookieLPw(
7442                    packageName, userId);
7443        }
7444    }
7445
7446    @Override
7447    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7448        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7449            return true;
7450        }
7451
7452        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7453                true /* requireFullPermission */, true /* checkShell */,
7454                "setInstantAppCookie");
7455        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7456            return false;
7457        }
7458        synchronized (mPackages) {
7459            return mInstantAppRegistry.setInstantAppCookieLPw(
7460                    packageName, cookie, userId);
7461        }
7462    }
7463
7464    @Override
7465    public Bitmap getInstantAppIcon(String packageName, int userId) {
7466        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7467            return null;
7468        }
7469
7470        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7471                "getInstantAppIcon");
7472
7473        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7474                true /* requireFullPermission */, false /* checkShell */,
7475                "getInstantAppIcon");
7476
7477        synchronized (mPackages) {
7478            return mInstantAppRegistry.getInstantAppIconLPw(
7479                    packageName, userId);
7480        }
7481    }
7482
7483    private boolean isCallerSameApp(String packageName, int uid) {
7484        PackageParser.Package pkg = mPackages.get(packageName);
7485        return pkg != null
7486                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
7487    }
7488
7489    @Override
7490    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7491        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7492    }
7493
7494    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7495        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7496
7497        // reader
7498        synchronized (mPackages) {
7499            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7500            final int userId = UserHandle.getCallingUserId();
7501            while (i.hasNext()) {
7502                final PackageParser.Package p = i.next();
7503                if (p.applicationInfo == null) continue;
7504
7505                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7506                        && !p.applicationInfo.isDirectBootAware();
7507                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7508                        && p.applicationInfo.isDirectBootAware();
7509
7510                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7511                        && (!mSafeMode || isSystemApp(p))
7512                        && (matchesUnaware || matchesAware)) {
7513                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7514                    if (ps != null) {
7515                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7516                                ps.readUserState(userId), userId);
7517                        if (ai != null) {
7518                            rebaseEnabledOverlays(ai, userId);
7519                            finalList.add(ai);
7520                        }
7521                    }
7522                }
7523            }
7524        }
7525
7526        return finalList;
7527    }
7528
7529    @Override
7530    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7531        if (!sUserManager.exists(userId)) return null;
7532        flags = updateFlagsForComponent(flags, userId, name);
7533        // reader
7534        synchronized (mPackages) {
7535            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7536            PackageSetting ps = provider != null
7537                    ? mSettings.mPackages.get(provider.owner.packageName)
7538                    : null;
7539            return ps != null
7540                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
7541                    ? PackageParser.generateProviderInfo(provider, flags,
7542                            ps.readUserState(userId), userId)
7543                    : null;
7544        }
7545    }
7546
7547    /**
7548     * @deprecated
7549     */
7550    @Deprecated
7551    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7552        // reader
7553        synchronized (mPackages) {
7554            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7555                    .entrySet().iterator();
7556            final int userId = UserHandle.getCallingUserId();
7557            while (i.hasNext()) {
7558                Map.Entry<String, PackageParser.Provider> entry = i.next();
7559                PackageParser.Provider p = entry.getValue();
7560                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7561
7562                if (ps != null && p.syncable
7563                        && (!mSafeMode || (p.info.applicationInfo.flags
7564                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7565                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7566                            ps.readUserState(userId), userId);
7567                    if (info != null) {
7568                        outNames.add(entry.getKey());
7569                        outInfo.add(info);
7570                    }
7571                }
7572            }
7573        }
7574    }
7575
7576    @Override
7577    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7578            int uid, int flags, String metaDataKey) {
7579        final int userId = processName != null ? UserHandle.getUserId(uid)
7580                : UserHandle.getCallingUserId();
7581        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7582        flags = updateFlagsForComponent(flags, userId, processName);
7583
7584        ArrayList<ProviderInfo> finalList = null;
7585        // reader
7586        synchronized (mPackages) {
7587            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7588            while (i.hasNext()) {
7589                final PackageParser.Provider p = i.next();
7590                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7591                if (ps != null && p.info.authority != null
7592                        && (processName == null
7593                                || (p.info.processName.equals(processName)
7594                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7595                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7596
7597                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
7598                    // parameter.
7599                    if (metaDataKey != null
7600                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
7601                        continue;
7602                    }
7603
7604                    if (finalList == null) {
7605                        finalList = new ArrayList<ProviderInfo>(3);
7606                    }
7607                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7608                            ps.readUserState(userId), userId);
7609                    if (info != null) {
7610                        finalList.add(info);
7611                    }
7612                }
7613            }
7614        }
7615
7616        if (finalList != null) {
7617            Collections.sort(finalList, mProviderInitOrderSorter);
7618            return new ParceledListSlice<ProviderInfo>(finalList);
7619        }
7620
7621        return ParceledListSlice.emptyList();
7622    }
7623
7624    @Override
7625    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7626        // reader
7627        synchronized (mPackages) {
7628            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7629            return PackageParser.generateInstrumentationInfo(i, flags);
7630        }
7631    }
7632
7633    @Override
7634    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7635            String targetPackage, int flags) {
7636        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7637    }
7638
7639    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7640            int flags) {
7641        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7642
7643        // reader
7644        synchronized (mPackages) {
7645            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7646            while (i.hasNext()) {
7647                final PackageParser.Instrumentation p = i.next();
7648                if (targetPackage == null
7649                        || targetPackage.equals(p.info.targetPackage)) {
7650                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7651                            flags);
7652                    if (ii != null) {
7653                        finalList.add(ii);
7654                    }
7655                }
7656            }
7657        }
7658
7659        return finalList;
7660    }
7661
7662    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7663        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7664        try {
7665            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7666        } finally {
7667            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7668        }
7669    }
7670
7671    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7672        final File[] files = dir.listFiles();
7673        if (ArrayUtils.isEmpty(files)) {
7674            Log.d(TAG, "No files in app dir " + dir);
7675            return;
7676        }
7677
7678        if (DEBUG_PACKAGE_SCANNING) {
7679            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7680                    + " flags=0x" + Integer.toHexString(parseFlags));
7681        }
7682        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7683                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, mPackageParserCallback);
7684
7685        // Submit files for parsing in parallel
7686        int fileCount = 0;
7687        for (File file : files) {
7688            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7689                    && !PackageInstallerService.isStageName(file.getName());
7690            if (!isPackage) {
7691                // Ignore entries which are not packages
7692                continue;
7693            }
7694            parallelPackageParser.submit(file, parseFlags);
7695            fileCount++;
7696        }
7697
7698        // Process results one by one
7699        for (; fileCount > 0; fileCount--) {
7700            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7701            Throwable throwable = parseResult.throwable;
7702            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7703
7704            if (throwable == null) {
7705                // Static shared libraries have synthetic package names
7706                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
7707                    renameStaticSharedLibraryPackage(parseResult.pkg);
7708                }
7709                try {
7710                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
7711                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7712                                currentTime, null);
7713                    }
7714                } catch (PackageManagerException e) {
7715                    errorCode = e.error;
7716                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7717                }
7718            } else if (throwable instanceof PackageParser.PackageParserException) {
7719                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7720                        throwable;
7721                errorCode = e.error;
7722                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7723            } else {
7724                throw new IllegalStateException("Unexpected exception occurred while parsing "
7725                        + parseResult.scanFile, throwable);
7726            }
7727
7728            // Delete invalid userdata apps
7729            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7730                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7731                logCriticalInfo(Log.WARN,
7732                        "Deleting invalid package at " + parseResult.scanFile);
7733                removeCodePathLI(parseResult.scanFile);
7734            }
7735        }
7736        parallelPackageParser.close();
7737    }
7738
7739    private static File getSettingsProblemFile() {
7740        File dataDir = Environment.getDataDirectory();
7741        File systemDir = new File(dataDir, "system");
7742        File fname = new File(systemDir, "uiderrors.txt");
7743        return fname;
7744    }
7745
7746    static void reportSettingsProblem(int priority, String msg) {
7747        logCriticalInfo(priority, msg);
7748    }
7749
7750    public static void logCriticalInfo(int priority, String msg) {
7751        Slog.println(priority, TAG, msg);
7752        EventLogTags.writePmCriticalInfo(msg);
7753        try {
7754            File fname = getSettingsProblemFile();
7755            FileOutputStream out = new FileOutputStream(fname, true);
7756            PrintWriter pw = new FastPrintWriter(out);
7757            SimpleDateFormat formatter = new SimpleDateFormat();
7758            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7759            pw.println(dateString + ": " + msg);
7760            pw.close();
7761            FileUtils.setPermissions(
7762                    fname.toString(),
7763                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7764                    -1, -1);
7765        } catch (java.io.IOException e) {
7766        }
7767    }
7768
7769    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7770        if (srcFile.isDirectory()) {
7771            final File baseFile = new File(pkg.baseCodePath);
7772            long maxModifiedTime = baseFile.lastModified();
7773            if (pkg.splitCodePaths != null) {
7774                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7775                    final File splitFile = new File(pkg.splitCodePaths[i]);
7776                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7777                }
7778            }
7779            return maxModifiedTime;
7780        }
7781        return srcFile.lastModified();
7782    }
7783
7784    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7785            final int policyFlags) throws PackageManagerException {
7786        // When upgrading from pre-N MR1, verify the package time stamp using the package
7787        // directory and not the APK file.
7788        final long lastModifiedTime = mIsPreNMR1Upgrade
7789                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7790        if (ps != null
7791                && ps.codePath.equals(srcFile)
7792                && ps.timeStamp == lastModifiedTime
7793                && !isCompatSignatureUpdateNeeded(pkg)
7794                && !isRecoverSignatureUpdateNeeded(pkg)) {
7795            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7796            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7797            ArraySet<PublicKey> signingKs;
7798            synchronized (mPackages) {
7799                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7800            }
7801            if (ps.signatures.mSignatures != null
7802                    && ps.signatures.mSignatures.length != 0
7803                    && signingKs != null) {
7804                // Optimization: reuse the existing cached certificates
7805                // if the package appears to be unchanged.
7806                pkg.mSignatures = ps.signatures.mSignatures;
7807                pkg.mSigningKeys = signingKs;
7808                return;
7809            }
7810
7811            Slog.w(TAG, "PackageSetting for " + ps.name
7812                    + " is missing signatures.  Collecting certs again to recover them.");
7813        } else {
7814            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7815        }
7816
7817        try {
7818            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7819            PackageParser.collectCertificates(pkg, policyFlags);
7820        } catch (PackageParserException e) {
7821            throw PackageManagerException.from(e);
7822        } finally {
7823            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7824        }
7825    }
7826
7827    /**
7828     *  Traces a package scan.
7829     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7830     */
7831    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7832            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7833        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7834        try {
7835            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7836        } finally {
7837            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7838        }
7839    }
7840
7841    /**
7842     *  Scans a package and returns the newly parsed package.
7843     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7844     */
7845    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7846            long currentTime, UserHandle user) throws PackageManagerException {
7847        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7848        PackageParser pp = new PackageParser();
7849        pp.setSeparateProcesses(mSeparateProcesses);
7850        pp.setOnlyCoreApps(mOnlyCore);
7851        pp.setDisplayMetrics(mMetrics);
7852        pp.setCallback(mPackageParserCallback);
7853
7854        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7855            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7856        }
7857
7858        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7859        final PackageParser.Package pkg;
7860        try {
7861            pkg = pp.parsePackage(scanFile, parseFlags);
7862        } catch (PackageParserException e) {
7863            throw PackageManagerException.from(e);
7864        } finally {
7865            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7866        }
7867
7868        // Static shared libraries have synthetic package names
7869        if (pkg.applicationInfo.isStaticSharedLibrary()) {
7870            renameStaticSharedLibraryPackage(pkg);
7871        }
7872
7873        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7874    }
7875
7876    /**
7877     *  Scans a package and returns the newly parsed package.
7878     *  @throws PackageManagerException on a parse error.
7879     */
7880    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7881            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7882            throws PackageManagerException {
7883        // If the package has children and this is the first dive in the function
7884        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7885        // packages (parent and children) would be successfully scanned before the
7886        // actual scan since scanning mutates internal state and we want to atomically
7887        // install the package and its children.
7888        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7889            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7890                scanFlags |= SCAN_CHECK_ONLY;
7891            }
7892        } else {
7893            scanFlags &= ~SCAN_CHECK_ONLY;
7894        }
7895
7896        // Scan the parent
7897        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7898                scanFlags, currentTime, user);
7899
7900        // Scan the children
7901        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7902        for (int i = 0; i < childCount; i++) {
7903            PackageParser.Package childPackage = pkg.childPackages.get(i);
7904            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7905                    currentTime, user);
7906        }
7907
7908
7909        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7910            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7911        }
7912
7913        return scannedPkg;
7914    }
7915
7916    /**
7917     *  Scans a package and returns the newly parsed package.
7918     *  @throws PackageManagerException on a parse error.
7919     */
7920    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7921            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7922            throws PackageManagerException {
7923        PackageSetting ps = null;
7924        PackageSetting updatedPkg;
7925        // reader
7926        synchronized (mPackages) {
7927            // Look to see if we already know about this package.
7928            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7929            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7930                // This package has been renamed to its original name.  Let's
7931                // use that.
7932                ps = mSettings.getPackageLPr(oldName);
7933            }
7934            // If there was no original package, see one for the real package name.
7935            if (ps == null) {
7936                ps = mSettings.getPackageLPr(pkg.packageName);
7937            }
7938            // Check to see if this package could be hiding/updating a system
7939            // package.  Must look for it either under the original or real
7940            // package name depending on our state.
7941            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7942            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7943
7944            // If this is a package we don't know about on the system partition, we
7945            // may need to remove disabled child packages on the system partition
7946            // or may need to not add child packages if the parent apk is updated
7947            // on the data partition and no longer defines this child package.
7948            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7949                // If this is a parent package for an updated system app and this system
7950                // app got an OTA update which no longer defines some of the child packages
7951                // we have to prune them from the disabled system packages.
7952                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7953                if (disabledPs != null) {
7954                    final int scannedChildCount = (pkg.childPackages != null)
7955                            ? pkg.childPackages.size() : 0;
7956                    final int disabledChildCount = disabledPs.childPackageNames != null
7957                            ? disabledPs.childPackageNames.size() : 0;
7958                    for (int i = 0; i < disabledChildCount; i++) {
7959                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7960                        boolean disabledPackageAvailable = false;
7961                        for (int j = 0; j < scannedChildCount; j++) {
7962                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7963                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7964                                disabledPackageAvailable = true;
7965                                break;
7966                            }
7967                         }
7968                         if (!disabledPackageAvailable) {
7969                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7970                         }
7971                    }
7972                }
7973            }
7974        }
7975
7976        boolean updatedPkgBetter = false;
7977        // First check if this is a system package that may involve an update
7978        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7979            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7980            // it needs to drop FLAG_PRIVILEGED.
7981            if (locationIsPrivileged(scanFile)) {
7982                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7983            } else {
7984                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7985            }
7986
7987            if (ps != null && !ps.codePath.equals(scanFile)) {
7988                // The path has changed from what was last scanned...  check the
7989                // version of the new path against what we have stored to determine
7990                // what to do.
7991                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7992                if (pkg.mVersionCode <= ps.versionCode) {
7993                    // The system package has been updated and the code path does not match
7994                    // Ignore entry. Skip it.
7995                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7996                            + " ignored: updated version " + ps.versionCode
7997                            + " better than this " + pkg.mVersionCode);
7998                    if (!updatedPkg.codePath.equals(scanFile)) {
7999                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8000                                + ps.name + " changing from " + updatedPkg.codePathString
8001                                + " to " + scanFile);
8002                        updatedPkg.codePath = scanFile;
8003                        updatedPkg.codePathString = scanFile.toString();
8004                        updatedPkg.resourcePath = scanFile;
8005                        updatedPkg.resourcePathString = scanFile.toString();
8006                    }
8007                    updatedPkg.pkg = pkg;
8008                    updatedPkg.versionCode = pkg.mVersionCode;
8009
8010                    // Update the disabled system child packages to point to the package too.
8011                    final int childCount = updatedPkg.childPackageNames != null
8012                            ? updatedPkg.childPackageNames.size() : 0;
8013                    for (int i = 0; i < childCount; i++) {
8014                        String childPackageName = updatedPkg.childPackageNames.get(i);
8015                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8016                                childPackageName);
8017                        if (updatedChildPkg != null) {
8018                            updatedChildPkg.pkg = pkg;
8019                            updatedChildPkg.versionCode = pkg.mVersionCode;
8020                        }
8021                    }
8022
8023                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
8024                            + scanFile + " ignored: updated version " + ps.versionCode
8025                            + " better than this " + pkg.mVersionCode);
8026                } else {
8027                    // The current app on the system partition is better than
8028                    // what we have updated to on the data partition; switch
8029                    // back to the system partition version.
8030                    // At this point, its safely assumed that package installation for
8031                    // apps in system partition will go through. If not there won't be a working
8032                    // version of the app
8033                    // writer
8034                    synchronized (mPackages) {
8035                        // Just remove the loaded entries from package lists.
8036                        mPackages.remove(ps.name);
8037                    }
8038
8039                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8040                            + " reverting from " + ps.codePathString
8041                            + ": new version " + pkg.mVersionCode
8042                            + " better than installed " + ps.versionCode);
8043
8044                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8045                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8046                    synchronized (mInstallLock) {
8047                        args.cleanUpResourcesLI();
8048                    }
8049                    synchronized (mPackages) {
8050                        mSettings.enableSystemPackageLPw(ps.name);
8051                    }
8052                    updatedPkgBetter = true;
8053                }
8054            }
8055        }
8056
8057        if (updatedPkg != null) {
8058            // An updated system app will not have the PARSE_IS_SYSTEM flag set
8059            // initially
8060            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
8061
8062            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
8063            // flag set initially
8064            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
8065                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
8066            }
8067        }
8068
8069        // Verify certificates against what was last scanned
8070        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
8071
8072        /*
8073         * A new system app appeared, but we already had a non-system one of the
8074         * same name installed earlier.
8075         */
8076        boolean shouldHideSystemApp = false;
8077        if (updatedPkg == null && ps != null
8078                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
8079            /*
8080             * Check to make sure the signatures match first. If they don't,
8081             * wipe the installed application and its data.
8082             */
8083            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
8084                    != PackageManager.SIGNATURE_MATCH) {
8085                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
8086                        + " signatures don't match existing userdata copy; removing");
8087                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8088                        "scanPackageInternalLI")) {
8089                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8090                }
8091                ps = null;
8092            } else {
8093                /*
8094                 * If the newly-added system app is an older version than the
8095                 * already installed version, hide it. It will be scanned later
8096                 * and re-added like an update.
8097                 */
8098                if (pkg.mVersionCode <= ps.versionCode) {
8099                    shouldHideSystemApp = true;
8100                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8101                            + " but new version " + pkg.mVersionCode + " better than installed "
8102                            + ps.versionCode + "; hiding system");
8103                } else {
8104                    /*
8105                     * The newly found system app is a newer version that the
8106                     * one previously installed. Simply remove the
8107                     * already-installed application and replace it with our own
8108                     * while keeping the application data.
8109                     */
8110                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8111                            + " reverting from " + ps.codePathString + ": new version "
8112                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8113                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8114                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8115                    synchronized (mInstallLock) {
8116                        args.cleanUpResourcesLI();
8117                    }
8118                }
8119            }
8120        }
8121
8122        // The apk is forward locked (not public) if its code and resources
8123        // are kept in different files. (except for app in either system or
8124        // vendor path).
8125        // TODO grab this value from PackageSettings
8126        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8127            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8128                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8129            }
8130        }
8131
8132        // TODO: extend to support forward-locked splits
8133        String resourcePath = null;
8134        String baseResourcePath = null;
8135        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
8136            if (ps != null && ps.resourcePathString != null) {
8137                resourcePath = ps.resourcePathString;
8138                baseResourcePath = ps.resourcePathString;
8139            } else {
8140                // Should not happen at all. Just log an error.
8141                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8142            }
8143        } else {
8144            resourcePath = pkg.codePath;
8145            baseResourcePath = pkg.baseCodePath;
8146        }
8147
8148        // Set application objects path explicitly.
8149        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8150        pkg.setApplicationInfoCodePath(pkg.codePath);
8151        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8152        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8153        pkg.setApplicationInfoResourcePath(resourcePath);
8154        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8155        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8156
8157        final int userId = ((user == null) ? 0 : user.getIdentifier());
8158        if (ps != null && ps.getInstantApp(userId)) {
8159            scanFlags |= SCAN_AS_INSTANT_APP;
8160        }
8161
8162        // Note that we invoke the following method only if we are about to unpack an application
8163        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8164                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8165
8166        /*
8167         * If the system app should be overridden by a previously installed
8168         * data, hide the system app now and let the /data/app scan pick it up
8169         * again.
8170         */
8171        if (shouldHideSystemApp) {
8172            synchronized (mPackages) {
8173                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8174            }
8175        }
8176
8177        return scannedPkg;
8178    }
8179
8180    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8181        // Derive the new package synthetic package name
8182        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8183                + pkg.staticSharedLibVersion);
8184    }
8185
8186    private static String fixProcessName(String defProcessName,
8187            String processName) {
8188        if (processName == null) {
8189            return defProcessName;
8190        }
8191        return processName;
8192    }
8193
8194    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8195            throws PackageManagerException {
8196        if (pkgSetting.signatures.mSignatures != null) {
8197            // Already existing package. Make sure signatures match
8198            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8199                    == PackageManager.SIGNATURE_MATCH;
8200            if (!match) {
8201                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8202                        == PackageManager.SIGNATURE_MATCH;
8203            }
8204            if (!match) {
8205                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8206                        == PackageManager.SIGNATURE_MATCH;
8207            }
8208            if (!match) {
8209                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8210                        + pkg.packageName + " signatures do not match the "
8211                        + "previously installed version; ignoring!");
8212            }
8213        }
8214
8215        // Check for shared user signatures
8216        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8217            // Already existing package. Make sure signatures match
8218            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8219                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8220            if (!match) {
8221                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8222                        == PackageManager.SIGNATURE_MATCH;
8223            }
8224            if (!match) {
8225                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8226                        == PackageManager.SIGNATURE_MATCH;
8227            }
8228            if (!match) {
8229                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8230                        "Package " + pkg.packageName
8231                        + " has no signatures that match those in shared user "
8232                        + pkgSetting.sharedUser.name + "; ignoring!");
8233            }
8234        }
8235    }
8236
8237    /**
8238     * Enforces that only the system UID or root's UID can call a method exposed
8239     * via Binder.
8240     *
8241     * @param message used as message if SecurityException is thrown
8242     * @throws SecurityException if the caller is not system or root
8243     */
8244    private static final void enforceSystemOrRoot(String message) {
8245        final int uid = Binder.getCallingUid();
8246        if (uid != Process.SYSTEM_UID && uid != 0) {
8247            throw new SecurityException(message);
8248        }
8249    }
8250
8251    @Override
8252    public void performFstrimIfNeeded() {
8253        enforceSystemOrRoot("Only the system can request fstrim");
8254
8255        // Before everything else, see whether we need to fstrim.
8256        try {
8257            IStorageManager sm = PackageHelper.getStorageManager();
8258            if (sm != null) {
8259                boolean doTrim = false;
8260                final long interval = android.provider.Settings.Global.getLong(
8261                        mContext.getContentResolver(),
8262                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8263                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8264                if (interval > 0) {
8265                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8266                    if (timeSinceLast > interval) {
8267                        doTrim = true;
8268                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8269                                + "; running immediately");
8270                    }
8271                }
8272                if (doTrim) {
8273                    final boolean dexOptDialogShown;
8274                    synchronized (mPackages) {
8275                        dexOptDialogShown = mDexOptDialogShown;
8276                    }
8277                    if (!isFirstBoot() && dexOptDialogShown) {
8278                        try {
8279                            ActivityManager.getService().showBootMessage(
8280                                    mContext.getResources().getString(
8281                                            R.string.android_upgrading_fstrim), true);
8282                        } catch (RemoteException e) {
8283                        }
8284                    }
8285                    sm.runMaintenance();
8286                }
8287            } else {
8288                Slog.e(TAG, "storageManager service unavailable!");
8289            }
8290        } catch (RemoteException e) {
8291            // Can't happen; StorageManagerService is local
8292        }
8293    }
8294
8295    @Override
8296    public void updatePackagesIfNeeded() {
8297        enforceSystemOrRoot("Only the system can request package update");
8298
8299        // We need to re-extract after an OTA.
8300        boolean causeUpgrade = isUpgrade();
8301
8302        // First boot or factory reset.
8303        // Note: we also handle devices that are upgrading to N right now as if it is their
8304        //       first boot, as they do not have profile data.
8305        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8306
8307        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8308        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8309
8310        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8311            return;
8312        }
8313
8314        List<PackageParser.Package> pkgs;
8315        synchronized (mPackages) {
8316            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8317        }
8318
8319        final long startTime = System.nanoTime();
8320        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8321                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8322
8323        final int elapsedTimeSeconds =
8324                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8325
8326        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8327        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8328        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8329        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8330        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8331    }
8332
8333    /**
8334     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8335     * containing statistics about the invocation. The array consists of three elements,
8336     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8337     * and {@code numberOfPackagesFailed}.
8338     */
8339    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8340            String compilerFilter) {
8341
8342        int numberOfPackagesVisited = 0;
8343        int numberOfPackagesOptimized = 0;
8344        int numberOfPackagesSkipped = 0;
8345        int numberOfPackagesFailed = 0;
8346        final int numberOfPackagesToDexopt = pkgs.size();
8347
8348        for (PackageParser.Package pkg : pkgs) {
8349            numberOfPackagesVisited++;
8350
8351            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8352                if (DEBUG_DEXOPT) {
8353                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8354                }
8355                numberOfPackagesSkipped++;
8356                continue;
8357            }
8358
8359            if (DEBUG_DEXOPT) {
8360                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8361                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8362            }
8363
8364            if (showDialog) {
8365                try {
8366                    ActivityManager.getService().showBootMessage(
8367                            mContext.getResources().getString(R.string.android_upgrading_apk,
8368                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8369                } catch (RemoteException e) {
8370                }
8371                synchronized (mPackages) {
8372                    mDexOptDialogShown = true;
8373                }
8374            }
8375
8376            // If the OTA updates a system app which was previously preopted to a non-preopted state
8377            // the app might end up being verified at runtime. That's because by default the apps
8378            // are verify-profile but for preopted apps there's no profile.
8379            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8380            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8381            // filter (by default interpret-only).
8382            // Note that at this stage unused apps are already filtered.
8383            if (isSystemApp(pkg) &&
8384                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8385                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8386                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8387            }
8388
8389            // checkProfiles is false to avoid merging profiles during boot which
8390            // might interfere with background compilation (b/28612421).
8391            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8392            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8393            // trade-off worth doing to save boot time work.
8394            int dexOptStatus = performDexOptTraced(pkg.packageName,
8395                    false /* checkProfiles */,
8396                    compilerFilter,
8397                    false /* force */);
8398            switch (dexOptStatus) {
8399                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8400                    numberOfPackagesOptimized++;
8401                    break;
8402                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8403                    numberOfPackagesSkipped++;
8404                    break;
8405                case PackageDexOptimizer.DEX_OPT_FAILED:
8406                    numberOfPackagesFailed++;
8407                    break;
8408                default:
8409                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8410                    break;
8411            }
8412        }
8413
8414        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8415                numberOfPackagesFailed };
8416    }
8417
8418    @Override
8419    public void notifyPackageUse(String packageName, int reason) {
8420        synchronized (mPackages) {
8421            PackageParser.Package p = mPackages.get(packageName);
8422            if (p == null) {
8423                return;
8424            }
8425            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8426        }
8427    }
8428
8429    @Override
8430    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8431        int userId = UserHandle.getCallingUserId();
8432        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8433        if (ai == null) {
8434            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8435                + loadingPackageName + ", user=" + userId);
8436            return;
8437        }
8438        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8439    }
8440
8441    // TODO: this is not used nor needed. Delete it.
8442    @Override
8443    public boolean performDexOptIfNeeded(String packageName) {
8444        int dexOptStatus = performDexOptTraced(packageName,
8445                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
8446        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8447    }
8448
8449    @Override
8450    public boolean performDexOpt(String packageName,
8451            boolean checkProfiles, int compileReason, boolean force) {
8452        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8453                getCompilerFilterForReason(compileReason), force);
8454        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8455    }
8456
8457    @Override
8458    public boolean performDexOptMode(String packageName,
8459            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8460        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8461                targetCompilerFilter, force);
8462        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8463    }
8464
8465    private int performDexOptTraced(String packageName,
8466                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8467        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8468        try {
8469            return performDexOptInternal(packageName, checkProfiles,
8470                    targetCompilerFilter, force);
8471        } finally {
8472            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8473        }
8474    }
8475
8476    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8477    // if the package can now be considered up to date for the given filter.
8478    private int performDexOptInternal(String packageName,
8479                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8480        PackageParser.Package p;
8481        synchronized (mPackages) {
8482            p = mPackages.get(packageName);
8483            if (p == null) {
8484                // Package could not be found. Report failure.
8485                return PackageDexOptimizer.DEX_OPT_FAILED;
8486            }
8487            mPackageUsage.maybeWriteAsync(mPackages);
8488            mCompilerStats.maybeWriteAsync();
8489        }
8490        long callingId = Binder.clearCallingIdentity();
8491        try {
8492            synchronized (mInstallLock) {
8493                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8494                        targetCompilerFilter, force);
8495            }
8496        } finally {
8497            Binder.restoreCallingIdentity(callingId);
8498        }
8499    }
8500
8501    public ArraySet<String> getOptimizablePackages() {
8502        ArraySet<String> pkgs = new ArraySet<String>();
8503        synchronized (mPackages) {
8504            for (PackageParser.Package p : mPackages.values()) {
8505                if (PackageDexOptimizer.canOptimizePackage(p)) {
8506                    pkgs.add(p.packageName);
8507                }
8508            }
8509        }
8510        return pkgs;
8511    }
8512
8513    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8514            boolean checkProfiles, String targetCompilerFilter,
8515            boolean force) {
8516        // Select the dex optimizer based on the force parameter.
8517        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8518        //       allocate an object here.
8519        PackageDexOptimizer pdo = force
8520                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8521                : mPackageDexOptimizer;
8522
8523        // Dexopt all dependencies first. Note: we ignore the return value and march on
8524        // on errors.
8525        // Note that we are going to call performDexOpt on those libraries as many times as
8526        // they are referenced in packages. When we do a batch of performDexOpt (for example
8527        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
8528        // and the first package that uses the library will dexopt it. The
8529        // others will see that the compiled code for the library is up to date.
8530        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8531        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8532        if (!deps.isEmpty()) {
8533            for (PackageParser.Package depPackage : deps) {
8534                // TODO: Analyze and investigate if we (should) profile libraries.
8535                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8536                        false /* checkProfiles */,
8537                        targetCompilerFilter,
8538                        getOrCreateCompilerPackageStats(depPackage),
8539                        true /* isUsedByOtherApps */);
8540            }
8541        }
8542        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8543                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
8544                mDexManager.isUsedByOtherApps(p.packageName));
8545    }
8546
8547    // Performs dexopt on the used secondary dex files belonging to the given package.
8548    // Returns true if all dex files were process successfully (which could mean either dexopt or
8549    // skip). Returns false if any of the files caused errors.
8550    @Override
8551    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8552            boolean force) {
8553        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8554    }
8555
8556    public boolean performDexOptSecondary(String packageName, int compileReason,
8557            boolean force) {
8558        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
8559    }
8560
8561    /**
8562     * Reconcile the information we have about the secondary dex files belonging to
8563     * {@code packagName} and the actual dex files. For all dex files that were
8564     * deleted, update the internal records and delete the generated oat files.
8565     */
8566    @Override
8567    public void reconcileSecondaryDexFiles(String packageName) {
8568        mDexManager.reconcileSecondaryDexFiles(packageName);
8569    }
8570
8571    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8572    // a reference there.
8573    /*package*/ DexManager getDexManager() {
8574        return mDexManager;
8575    }
8576
8577    /**
8578     * Execute the background dexopt job immediately.
8579     */
8580    @Override
8581    public boolean runBackgroundDexoptJob() {
8582        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8583    }
8584
8585    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8586        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8587                || p.usesStaticLibraries != null) {
8588            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8589            Set<String> collectedNames = new HashSet<>();
8590            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8591
8592            retValue.remove(p);
8593
8594            return retValue;
8595        } else {
8596            return Collections.emptyList();
8597        }
8598    }
8599
8600    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8601            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8602        if (!collectedNames.contains(p.packageName)) {
8603            collectedNames.add(p.packageName);
8604            collected.add(p);
8605
8606            if (p.usesLibraries != null) {
8607                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8608                        null, collected, collectedNames);
8609            }
8610            if (p.usesOptionalLibraries != null) {
8611                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8612                        null, collected, collectedNames);
8613            }
8614            if (p.usesStaticLibraries != null) {
8615                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8616                        p.usesStaticLibrariesVersions, collected, collectedNames);
8617            }
8618        }
8619    }
8620
8621    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8622            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8623        final int libNameCount = libs.size();
8624        for (int i = 0; i < libNameCount; i++) {
8625            String libName = libs.get(i);
8626            int version = (versions != null && versions.length == libNameCount)
8627                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8628            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8629            if (libPkg != null) {
8630                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8631            }
8632        }
8633    }
8634
8635    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8636        synchronized (mPackages) {
8637            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8638            if (libEntry != null) {
8639                return mPackages.get(libEntry.apk);
8640            }
8641            return null;
8642        }
8643    }
8644
8645    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8646        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8647        if (versionedLib == null) {
8648            return null;
8649        }
8650        return versionedLib.get(version);
8651    }
8652
8653    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
8654        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
8655                pkg.staticSharedLibName);
8656        if (versionedLib == null) {
8657            return null;
8658        }
8659        int previousLibVersion = -1;
8660        final int versionCount = versionedLib.size();
8661        for (int i = 0; i < versionCount; i++) {
8662            final int libVersion = versionedLib.keyAt(i);
8663            if (libVersion < pkg.staticSharedLibVersion) {
8664                previousLibVersion = Math.max(previousLibVersion, libVersion);
8665            }
8666        }
8667        if (previousLibVersion >= 0) {
8668            return versionedLib.get(previousLibVersion);
8669        }
8670        return null;
8671    }
8672
8673    public void shutdown() {
8674        mPackageUsage.writeNow(mPackages);
8675        mCompilerStats.writeNow();
8676    }
8677
8678    @Override
8679    public void dumpProfiles(String packageName) {
8680        PackageParser.Package pkg;
8681        synchronized (mPackages) {
8682            pkg = mPackages.get(packageName);
8683            if (pkg == null) {
8684                throw new IllegalArgumentException("Unknown package: " + packageName);
8685            }
8686        }
8687        /* Only the shell, root, or the app user should be able to dump profiles. */
8688        int callingUid = Binder.getCallingUid();
8689        if (callingUid != Process.SHELL_UID &&
8690            callingUid != Process.ROOT_UID &&
8691            callingUid != pkg.applicationInfo.uid) {
8692            throw new SecurityException("dumpProfiles");
8693        }
8694
8695        synchronized (mInstallLock) {
8696            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
8697            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
8698            try {
8699                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
8700                String codePaths = TextUtils.join(";", allCodePaths);
8701                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
8702            } catch (InstallerException e) {
8703                Slog.w(TAG, "Failed to dump profiles", e);
8704            }
8705            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8706        }
8707    }
8708
8709    @Override
8710    public void forceDexOpt(String packageName) {
8711        enforceSystemOrRoot("forceDexOpt");
8712
8713        PackageParser.Package pkg;
8714        synchronized (mPackages) {
8715            pkg = mPackages.get(packageName);
8716            if (pkg == null) {
8717                throw new IllegalArgumentException("Unknown package: " + packageName);
8718            }
8719        }
8720
8721        synchronized (mInstallLock) {
8722            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8723
8724            // Whoever is calling forceDexOpt wants a fully compiled package.
8725            // Don't use profiles since that may cause compilation to be skipped.
8726            final int res = performDexOptInternalWithDependenciesLI(pkg,
8727                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
8728                    true /* force */);
8729
8730            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8731            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
8732                throw new IllegalStateException("Failed to dexopt: " + res);
8733            }
8734        }
8735    }
8736
8737    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
8738        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8739            Slog.w(TAG, "Unable to update from " + oldPkg.name
8740                    + " to " + newPkg.packageName
8741                    + ": old package not in system partition");
8742            return false;
8743        } else if (mPackages.get(oldPkg.name) != null) {
8744            Slog.w(TAG, "Unable to update from " + oldPkg.name
8745                    + " to " + newPkg.packageName
8746                    + ": old package still exists");
8747            return false;
8748        }
8749        return true;
8750    }
8751
8752    void removeCodePathLI(File codePath) {
8753        if (codePath.isDirectory()) {
8754            try {
8755                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8756            } catch (InstallerException e) {
8757                Slog.w(TAG, "Failed to remove code path", e);
8758            }
8759        } else {
8760            codePath.delete();
8761        }
8762    }
8763
8764    private int[] resolveUserIds(int userId) {
8765        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8766    }
8767
8768    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8769        if (pkg == null) {
8770            Slog.wtf(TAG, "Package was null!", new Throwable());
8771            return;
8772        }
8773        clearAppDataLeafLIF(pkg, userId, flags);
8774        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8775        for (int i = 0; i < childCount; i++) {
8776            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8777        }
8778    }
8779
8780    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8781        final PackageSetting ps;
8782        synchronized (mPackages) {
8783            ps = mSettings.mPackages.get(pkg.packageName);
8784        }
8785        for (int realUserId : resolveUserIds(userId)) {
8786            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8787            try {
8788                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8789                        ceDataInode);
8790            } catch (InstallerException e) {
8791                Slog.w(TAG, String.valueOf(e));
8792            }
8793        }
8794    }
8795
8796    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8797        if (pkg == null) {
8798            Slog.wtf(TAG, "Package was null!", new Throwable());
8799            return;
8800        }
8801        destroyAppDataLeafLIF(pkg, userId, flags);
8802        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8803        for (int i = 0; i < childCount; i++) {
8804            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8805        }
8806    }
8807
8808    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8809        final PackageSetting ps;
8810        synchronized (mPackages) {
8811            ps = mSettings.mPackages.get(pkg.packageName);
8812        }
8813        for (int realUserId : resolveUserIds(userId)) {
8814            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8815            try {
8816                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8817                        ceDataInode);
8818            } catch (InstallerException e) {
8819                Slog.w(TAG, String.valueOf(e));
8820            }
8821            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
8822        }
8823    }
8824
8825    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8826        if (pkg == null) {
8827            Slog.wtf(TAG, "Package was null!", new Throwable());
8828            return;
8829        }
8830        destroyAppProfilesLeafLIF(pkg);
8831        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8832        for (int i = 0; i < childCount; i++) {
8833            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8834        }
8835    }
8836
8837    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8838        try {
8839            mInstaller.destroyAppProfiles(pkg.packageName);
8840        } catch (InstallerException e) {
8841            Slog.w(TAG, String.valueOf(e));
8842        }
8843    }
8844
8845    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8846        if (pkg == null) {
8847            Slog.wtf(TAG, "Package was null!", new Throwable());
8848            return;
8849        }
8850        clearAppProfilesLeafLIF(pkg);
8851        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8852        for (int i = 0; i < childCount; i++) {
8853            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8854        }
8855    }
8856
8857    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8858        try {
8859            mInstaller.clearAppProfiles(pkg.packageName);
8860        } catch (InstallerException e) {
8861            Slog.w(TAG, String.valueOf(e));
8862        }
8863    }
8864
8865    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8866            long lastUpdateTime) {
8867        // Set parent install/update time
8868        PackageSetting ps = (PackageSetting) pkg.mExtras;
8869        if (ps != null) {
8870            ps.firstInstallTime = firstInstallTime;
8871            ps.lastUpdateTime = lastUpdateTime;
8872        }
8873        // Set children install/update time
8874        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8875        for (int i = 0; i < childCount; i++) {
8876            PackageParser.Package childPkg = pkg.childPackages.get(i);
8877            ps = (PackageSetting) childPkg.mExtras;
8878            if (ps != null) {
8879                ps.firstInstallTime = firstInstallTime;
8880                ps.lastUpdateTime = lastUpdateTime;
8881            }
8882        }
8883    }
8884
8885    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8886            PackageParser.Package changingLib) {
8887        if (file.path != null) {
8888            usesLibraryFiles.add(file.path);
8889            return;
8890        }
8891        PackageParser.Package p = mPackages.get(file.apk);
8892        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8893            // If we are doing this while in the middle of updating a library apk,
8894            // then we need to make sure to use that new apk for determining the
8895            // dependencies here.  (We haven't yet finished committing the new apk
8896            // to the package manager state.)
8897            if (p == null || p.packageName.equals(changingLib.packageName)) {
8898                p = changingLib;
8899            }
8900        }
8901        if (p != null) {
8902            usesLibraryFiles.addAll(p.getAllCodePaths());
8903        }
8904    }
8905
8906    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8907            PackageParser.Package changingLib) throws PackageManagerException {
8908        if (pkg == null) {
8909            return;
8910        }
8911        ArraySet<String> usesLibraryFiles = null;
8912        if (pkg.usesLibraries != null) {
8913            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
8914                    null, null, pkg.packageName, changingLib, true, null);
8915        }
8916        if (pkg.usesStaticLibraries != null) {
8917            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
8918                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
8919                    pkg.packageName, changingLib, true, usesLibraryFiles);
8920        }
8921        if (pkg.usesOptionalLibraries != null) {
8922            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
8923                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
8924        }
8925        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
8926            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
8927        } else {
8928            pkg.usesLibraryFiles = null;
8929        }
8930    }
8931
8932    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
8933            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
8934            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
8935            boolean required, @Nullable ArraySet<String> outUsedLibraries)
8936            throws PackageManagerException {
8937        final int libCount = requestedLibraries.size();
8938        for (int i = 0; i < libCount; i++) {
8939            final String libName = requestedLibraries.get(i);
8940            final int libVersion = requiredVersions != null ? requiredVersions[i]
8941                    : SharedLibraryInfo.VERSION_UNDEFINED;
8942            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
8943            if (libEntry == null) {
8944                if (required) {
8945                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8946                            "Package " + packageName + " requires unavailable shared library "
8947                                    + libName + "; failing!");
8948                } else {
8949                    Slog.w(TAG, "Package " + packageName
8950                            + " desires unavailable shared library "
8951                            + libName + "; ignoring!");
8952                }
8953            } else {
8954                if (requiredVersions != null && requiredCertDigests != null) {
8955                    if (libEntry.info.getVersion() != requiredVersions[i]) {
8956                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8957                            "Package " + packageName + " requires unavailable static shared"
8958                                    + " library " + libName + " version "
8959                                    + libEntry.info.getVersion() + "; failing!");
8960                    }
8961
8962                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
8963                    if (libPkg == null) {
8964                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8965                                "Package " + packageName + " requires unavailable static shared"
8966                                        + " library; failing!");
8967                    }
8968
8969                    String expectedCertDigest = requiredCertDigests[i];
8970                    String libCertDigest = PackageUtils.computeCertSha256Digest(
8971                                libPkg.mSignatures[0]);
8972                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
8973                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8974                                "Package " + packageName + " requires differently signed" +
8975                                        " static shared library; failing!");
8976                    }
8977                }
8978
8979                if (outUsedLibraries == null) {
8980                    outUsedLibraries = new ArraySet<>();
8981                }
8982                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
8983            }
8984        }
8985        return outUsedLibraries;
8986    }
8987
8988    private static boolean hasString(List<String> list, List<String> which) {
8989        if (list == null) {
8990            return false;
8991        }
8992        for (int i=list.size()-1; i>=0; i--) {
8993            for (int j=which.size()-1; j>=0; j--) {
8994                if (which.get(j).equals(list.get(i))) {
8995                    return true;
8996                }
8997            }
8998        }
8999        return false;
9000    }
9001
9002    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9003            PackageParser.Package changingPkg) {
9004        ArrayList<PackageParser.Package> res = null;
9005        for (PackageParser.Package pkg : mPackages.values()) {
9006            if (changingPkg != null
9007                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9008                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9009                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9010                            changingPkg.staticSharedLibName)) {
9011                return null;
9012            }
9013            if (res == null) {
9014                res = new ArrayList<>();
9015            }
9016            res.add(pkg);
9017            try {
9018                updateSharedLibrariesLPr(pkg, changingPkg);
9019            } catch (PackageManagerException e) {
9020                // If a system app update or an app and a required lib missing we
9021                // delete the package and for updated system apps keep the data as
9022                // it is better for the user to reinstall than to be in an limbo
9023                // state. Also libs disappearing under an app should never happen
9024                // - just in case.
9025                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
9026                    final int flags = pkg.isUpdatedSystemApp()
9027                            ? PackageManager.DELETE_KEEP_DATA : 0;
9028                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9029                            flags , null, true, null);
9030                }
9031                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9032            }
9033        }
9034        return res;
9035    }
9036
9037    /**
9038     * Derive the value of the {@code cpuAbiOverride} based on the provided
9039     * value and an optional stored value from the package settings.
9040     */
9041    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
9042        String cpuAbiOverride = null;
9043
9044        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
9045            cpuAbiOverride = null;
9046        } else if (abiOverride != null) {
9047            cpuAbiOverride = abiOverride;
9048        } else if (settings != null) {
9049            cpuAbiOverride = settings.cpuAbiOverrideString;
9050        }
9051
9052        return cpuAbiOverride;
9053    }
9054
9055    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9056            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
9057                    throws PackageManagerException {
9058        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9059        // If the package has children and this is the first dive in the function
9060        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9061        // whether all packages (parent and children) would be successfully scanned
9062        // before the actual scan since scanning mutates internal state and we want
9063        // to atomically install the package and its children.
9064        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9065            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9066                scanFlags |= SCAN_CHECK_ONLY;
9067            }
9068        } else {
9069            scanFlags &= ~SCAN_CHECK_ONLY;
9070        }
9071
9072        final PackageParser.Package scannedPkg;
9073        try {
9074            // Scan the parent
9075            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
9076            // Scan the children
9077            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9078            for (int i = 0; i < childCount; i++) {
9079                PackageParser.Package childPkg = pkg.childPackages.get(i);
9080                scanPackageLI(childPkg, policyFlags,
9081                        scanFlags, currentTime, user);
9082            }
9083        } finally {
9084            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9085        }
9086
9087        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9088            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
9089        }
9090
9091        return scannedPkg;
9092    }
9093
9094    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
9095            int scanFlags, long currentTime, @Nullable UserHandle user)
9096                    throws PackageManagerException {
9097        boolean success = false;
9098        try {
9099            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9100                    currentTime, user);
9101            success = true;
9102            return res;
9103        } finally {
9104            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9105                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9106                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9107                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9108                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9109            }
9110        }
9111    }
9112
9113    /**
9114     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9115     */
9116    private static boolean apkHasCode(String fileName) {
9117        StrictJarFile jarFile = null;
9118        try {
9119            jarFile = new StrictJarFile(fileName,
9120                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9121            return jarFile.findEntry("classes.dex") != null;
9122        } catch (IOException ignore) {
9123        } finally {
9124            try {
9125                if (jarFile != null) {
9126                    jarFile.close();
9127                }
9128            } catch (IOException ignore) {}
9129        }
9130        return false;
9131    }
9132
9133    /**
9134     * Enforces code policy for the package. This ensures that if an APK has
9135     * declared hasCode="true" in its manifest that the APK actually contains
9136     * code.
9137     *
9138     * @throws PackageManagerException If bytecode could not be found when it should exist
9139     */
9140    private static void assertCodePolicy(PackageParser.Package pkg)
9141            throws PackageManagerException {
9142        final boolean shouldHaveCode =
9143                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9144        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9145            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9146                    "Package " + pkg.baseCodePath + " code is missing");
9147        }
9148
9149        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9150            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9151                final boolean splitShouldHaveCode =
9152                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9153                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9154                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9155                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9156                }
9157            }
9158        }
9159    }
9160
9161    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9162            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
9163                    throws PackageManagerException {
9164        if (DEBUG_PACKAGE_SCANNING) {
9165            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9166                Log.d(TAG, "Scanning package " + pkg.packageName);
9167        }
9168
9169        applyPolicy(pkg, policyFlags);
9170
9171        assertPackageIsValid(pkg, policyFlags, scanFlags);
9172
9173        // Initialize package source and resource directories
9174        final File scanFile = new File(pkg.codePath);
9175        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9176        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9177
9178        SharedUserSetting suid = null;
9179        PackageSetting pkgSetting = null;
9180
9181        // Getting the package setting may have a side-effect, so if we
9182        // are only checking if scan would succeed, stash a copy of the
9183        // old setting to restore at the end.
9184        PackageSetting nonMutatedPs = null;
9185
9186        // We keep references to the derived CPU Abis from settings in oder to reuse
9187        // them in the case where we're not upgrading or booting for the first time.
9188        String primaryCpuAbiFromSettings = null;
9189        String secondaryCpuAbiFromSettings = null;
9190
9191        // writer
9192        synchronized (mPackages) {
9193            if (pkg.mSharedUserId != null) {
9194                // SIDE EFFECTS; may potentially allocate a new shared user
9195                suid = mSettings.getSharedUserLPw(
9196                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9197                if (DEBUG_PACKAGE_SCANNING) {
9198                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9199                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9200                                + "): packages=" + suid.packages);
9201                }
9202            }
9203
9204            // Check if we are renaming from an original package name.
9205            PackageSetting origPackage = null;
9206            String realName = null;
9207            if (pkg.mOriginalPackages != null) {
9208                // This package may need to be renamed to a previously
9209                // installed name.  Let's check on that...
9210                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9211                if (pkg.mOriginalPackages.contains(renamed)) {
9212                    // This package had originally been installed as the
9213                    // original name, and we have already taken care of
9214                    // transitioning to the new one.  Just update the new
9215                    // one to continue using the old name.
9216                    realName = pkg.mRealPackage;
9217                    if (!pkg.packageName.equals(renamed)) {
9218                        // Callers into this function may have already taken
9219                        // care of renaming the package; only do it here if
9220                        // it is not already done.
9221                        pkg.setPackageName(renamed);
9222                    }
9223                } else {
9224                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9225                        if ((origPackage = mSettings.getPackageLPr(
9226                                pkg.mOriginalPackages.get(i))) != null) {
9227                            // We do have the package already installed under its
9228                            // original name...  should we use it?
9229                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9230                                // New package is not compatible with original.
9231                                origPackage = null;
9232                                continue;
9233                            } else if (origPackage.sharedUser != null) {
9234                                // Make sure uid is compatible between packages.
9235                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9236                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9237                                            + " to " + pkg.packageName + ": old uid "
9238                                            + origPackage.sharedUser.name
9239                                            + " differs from " + pkg.mSharedUserId);
9240                                    origPackage = null;
9241                                    continue;
9242                                }
9243                                // TODO: Add case when shared user id is added [b/28144775]
9244                            } else {
9245                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9246                                        + pkg.packageName + " to old name " + origPackage.name);
9247                            }
9248                            break;
9249                        }
9250                    }
9251                }
9252            }
9253
9254            if (mTransferedPackages.contains(pkg.packageName)) {
9255                Slog.w(TAG, "Package " + pkg.packageName
9256                        + " was transferred to another, but its .apk remains");
9257            }
9258
9259            // See comments in nonMutatedPs declaration
9260            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9261                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9262                if (foundPs != null) {
9263                    nonMutatedPs = new PackageSetting(foundPs);
9264                }
9265            }
9266
9267            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9268                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9269                if (foundPs != null) {
9270                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9271                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9272                }
9273            }
9274
9275            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9276            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9277                PackageManagerService.reportSettingsProblem(Log.WARN,
9278                        "Package " + pkg.packageName + " shared user changed from "
9279                                + (pkgSetting.sharedUser != null
9280                                        ? pkgSetting.sharedUser.name : "<nothing>")
9281                                + " to "
9282                                + (suid != null ? suid.name : "<nothing>")
9283                                + "; replacing with new");
9284                pkgSetting = null;
9285            }
9286            final PackageSetting oldPkgSetting =
9287                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9288            final PackageSetting disabledPkgSetting =
9289                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9290
9291            String[] usesStaticLibraries = null;
9292            if (pkg.usesStaticLibraries != null) {
9293                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9294                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9295            }
9296
9297            if (pkgSetting == null) {
9298                final String parentPackageName = (pkg.parentPackage != null)
9299                        ? pkg.parentPackage.packageName : null;
9300                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9301                // REMOVE SharedUserSetting from method; update in a separate call
9302                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9303                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9304                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9305                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9306                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9307                        true /*allowInstall*/, instantApp, parentPackageName,
9308                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
9309                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
9310                // SIDE EFFECTS; updates system state; move elsewhere
9311                if (origPackage != null) {
9312                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9313                }
9314                mSettings.addUserToSettingLPw(pkgSetting);
9315            } else {
9316                // REMOVE SharedUserSetting from method; update in a separate call.
9317                //
9318                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9319                // secondaryCpuAbi are not known at this point so we always update them
9320                // to null here, only to reset them at a later point.
9321                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9322                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9323                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9324                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9325                        UserManagerService.getInstance(), usesStaticLibraries,
9326                        pkg.usesStaticLibrariesVersions);
9327            }
9328            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9329            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9330
9331            // SIDE EFFECTS; modifies system state; move elsewhere
9332            if (pkgSetting.origPackage != null) {
9333                // If we are first transitioning from an original package,
9334                // fix up the new package's name now.  We need to do this after
9335                // looking up the package under its new name, so getPackageLP
9336                // can take care of fiddling things correctly.
9337                pkg.setPackageName(origPackage.name);
9338
9339                // File a report about this.
9340                String msg = "New package " + pkgSetting.realName
9341                        + " renamed to replace old package " + pkgSetting.name;
9342                reportSettingsProblem(Log.WARN, msg);
9343
9344                // Make a note of it.
9345                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9346                    mTransferedPackages.add(origPackage.name);
9347                }
9348
9349                // No longer need to retain this.
9350                pkgSetting.origPackage = null;
9351            }
9352
9353            // SIDE EFFECTS; modifies system state; move elsewhere
9354            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9355                // Make a note of it.
9356                mTransferedPackages.add(pkg.packageName);
9357            }
9358
9359            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9360                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9361            }
9362
9363            if ((scanFlags & SCAN_BOOTING) == 0
9364                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9365                // Check all shared libraries and map to their actual file path.
9366                // We only do this here for apps not on a system dir, because those
9367                // are the only ones that can fail an install due to this.  We
9368                // will take care of the system apps by updating all of their
9369                // library paths after the scan is done. Also during the initial
9370                // scan don't update any libs as we do this wholesale after all
9371                // apps are scanned to avoid dependency based scanning.
9372                updateSharedLibrariesLPr(pkg, null);
9373            }
9374
9375            if (mFoundPolicyFile) {
9376                SELinuxMMAC.assignSeInfoValue(pkg);
9377            }
9378            pkg.applicationInfo.uid = pkgSetting.appId;
9379            pkg.mExtras = pkgSetting;
9380
9381
9382            // Static shared libs have same package with different versions where
9383            // we internally use a synthetic package name to allow multiple versions
9384            // of the same package, therefore we need to compare signatures against
9385            // the package setting for the latest library version.
9386            PackageSetting signatureCheckPs = pkgSetting;
9387            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9388                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9389                if (libraryEntry != null) {
9390                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9391                }
9392            }
9393
9394            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9395                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9396                    // We just determined the app is signed correctly, so bring
9397                    // over the latest parsed certs.
9398                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9399                } else {
9400                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9401                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9402                                "Package " + pkg.packageName + " upgrade keys do not match the "
9403                                + "previously installed version");
9404                    } else {
9405                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9406                        String msg = "System package " + pkg.packageName
9407                                + " signature changed; retaining data.";
9408                        reportSettingsProblem(Log.WARN, msg);
9409                    }
9410                }
9411            } else {
9412                try {
9413                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9414                    verifySignaturesLP(signatureCheckPs, pkg);
9415                    // We just determined the app is signed correctly, so bring
9416                    // over the latest parsed certs.
9417                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9418                } catch (PackageManagerException e) {
9419                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9420                        throw e;
9421                    }
9422                    // The signature has changed, but this package is in the system
9423                    // image...  let's recover!
9424                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9425                    // However...  if this package is part of a shared user, but it
9426                    // doesn't match the signature of the shared user, let's fail.
9427                    // What this means is that you can't change the signatures
9428                    // associated with an overall shared user, which doesn't seem all
9429                    // that unreasonable.
9430                    if (signatureCheckPs.sharedUser != null) {
9431                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9432                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9433                            throw new PackageManagerException(
9434                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9435                                    "Signature mismatch for shared user: "
9436                                            + pkgSetting.sharedUser);
9437                        }
9438                    }
9439                    // File a report about this.
9440                    String msg = "System package " + pkg.packageName
9441                            + " signature changed; retaining data.";
9442                    reportSettingsProblem(Log.WARN, msg);
9443                }
9444            }
9445
9446            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9447                // This package wants to adopt ownership of permissions from
9448                // another package.
9449                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9450                    final String origName = pkg.mAdoptPermissions.get(i);
9451                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9452                    if (orig != null) {
9453                        if (verifyPackageUpdateLPr(orig, pkg)) {
9454                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9455                                    + pkg.packageName);
9456                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9457                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9458                        }
9459                    }
9460                }
9461            }
9462        }
9463
9464        pkg.applicationInfo.processName = fixProcessName(
9465                pkg.applicationInfo.packageName,
9466                pkg.applicationInfo.processName);
9467
9468        if (pkg != mPlatformPackage) {
9469            // Get all of our default paths setup
9470            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9471        }
9472
9473        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9474
9475        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9476            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9477                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9478                derivePackageAbi(
9479                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9480                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9481
9482                // Some system apps still use directory structure for native libraries
9483                // in which case we might end up not detecting abi solely based on apk
9484                // structure. Try to detect abi based on directory structure.
9485                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9486                        pkg.applicationInfo.primaryCpuAbi == null) {
9487                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9488                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9489                }
9490            } else {
9491                // This is not a first boot or an upgrade, don't bother deriving the
9492                // ABI during the scan. Instead, trust the value that was stored in the
9493                // package setting.
9494                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9495                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9496
9497                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9498
9499                if (DEBUG_ABI_SELECTION) {
9500                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9501                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9502                        pkg.applicationInfo.secondaryCpuAbi);
9503                }
9504            }
9505        } else {
9506            if ((scanFlags & SCAN_MOVE) != 0) {
9507                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9508                // but we already have this packages package info in the PackageSetting. We just
9509                // use that and derive the native library path based on the new codepath.
9510                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9511                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9512            }
9513
9514            // Set native library paths again. For moves, the path will be updated based on the
9515            // ABIs we've determined above. For non-moves, the path will be updated based on the
9516            // ABIs we determined during compilation, but the path will depend on the final
9517            // package path (after the rename away from the stage path).
9518            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9519        }
9520
9521        // This is a special case for the "system" package, where the ABI is
9522        // dictated by the zygote configuration (and init.rc). We should keep track
9523        // of this ABI so that we can deal with "normal" applications that run under
9524        // the same UID correctly.
9525        if (mPlatformPackage == pkg) {
9526            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9527                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9528        }
9529
9530        // If there's a mismatch between the abi-override in the package setting
9531        // and the abiOverride specified for the install. Warn about this because we
9532        // would've already compiled the app without taking the package setting into
9533        // account.
9534        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9535            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9536                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9537                        " for package " + pkg.packageName);
9538            }
9539        }
9540
9541        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9542        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9543        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9544
9545        // Copy the derived override back to the parsed package, so that we can
9546        // update the package settings accordingly.
9547        pkg.cpuAbiOverride = cpuAbiOverride;
9548
9549        if (DEBUG_ABI_SELECTION) {
9550            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9551                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9552                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9553        }
9554
9555        // Push the derived path down into PackageSettings so we know what to
9556        // clean up at uninstall time.
9557        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9558
9559        if (DEBUG_ABI_SELECTION) {
9560            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9561                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9562                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9563        }
9564
9565        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9566        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9567            // We don't do this here during boot because we can do it all
9568            // at once after scanning all existing packages.
9569            //
9570            // We also do this *before* we perform dexopt on this package, so that
9571            // we can avoid redundant dexopts, and also to make sure we've got the
9572            // code and package path correct.
9573            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9574        }
9575
9576        if (mFactoryTest && pkg.requestedPermissions.contains(
9577                android.Manifest.permission.FACTORY_TEST)) {
9578            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9579        }
9580
9581        if (isSystemApp(pkg)) {
9582            pkgSetting.isOrphaned = true;
9583        }
9584
9585        // Take care of first install / last update times.
9586        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9587        if (currentTime != 0) {
9588            if (pkgSetting.firstInstallTime == 0) {
9589                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9590            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9591                pkgSetting.lastUpdateTime = currentTime;
9592            }
9593        } else if (pkgSetting.firstInstallTime == 0) {
9594            // We need *something*.  Take time time stamp of the file.
9595            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9596        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9597            if (scanFileTime != pkgSetting.timeStamp) {
9598                // A package on the system image has changed; consider this
9599                // to be an update.
9600                pkgSetting.lastUpdateTime = scanFileTime;
9601            }
9602        }
9603        pkgSetting.setTimeStamp(scanFileTime);
9604
9605        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9606            if (nonMutatedPs != null) {
9607                synchronized (mPackages) {
9608                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9609                }
9610            }
9611        } else {
9612            final int userId = user == null ? 0 : user.getIdentifier();
9613            // Modify state for the given package setting
9614            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9615                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9616            if (pkgSetting.getInstantApp(userId)) {
9617                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9618            }
9619        }
9620        return pkg;
9621    }
9622
9623    /**
9624     * Applies policy to the parsed package based upon the given policy flags.
9625     * Ensures the package is in a good state.
9626     * <p>
9627     * Implementation detail: This method must NOT have any side effect. It would
9628     * ideally be static, but, it requires locks to read system state.
9629     */
9630    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9631        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9632            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9633            if (pkg.applicationInfo.isDirectBootAware()) {
9634                // we're direct boot aware; set for all components
9635                for (PackageParser.Service s : pkg.services) {
9636                    s.info.encryptionAware = s.info.directBootAware = true;
9637                }
9638                for (PackageParser.Provider p : pkg.providers) {
9639                    p.info.encryptionAware = p.info.directBootAware = true;
9640                }
9641                for (PackageParser.Activity a : pkg.activities) {
9642                    a.info.encryptionAware = a.info.directBootAware = true;
9643                }
9644                for (PackageParser.Activity r : pkg.receivers) {
9645                    r.info.encryptionAware = r.info.directBootAware = true;
9646                }
9647            }
9648        } else {
9649            // Only allow system apps to be flagged as core apps.
9650            pkg.coreApp = false;
9651            // clear flags not applicable to regular apps
9652            pkg.applicationInfo.privateFlags &=
9653                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
9654            pkg.applicationInfo.privateFlags &=
9655                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
9656        }
9657        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
9658
9659        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
9660            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9661        }
9662
9663        if (!isSystemApp(pkg)) {
9664            // Only system apps can use these features.
9665            pkg.mOriginalPackages = null;
9666            pkg.mRealPackage = null;
9667            pkg.mAdoptPermissions = null;
9668        }
9669    }
9670
9671    /**
9672     * Asserts the parsed package is valid according to the given policy. If the
9673     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
9674     * <p>
9675     * Implementation detail: This method must NOT have any side effects. It would
9676     * ideally be static, but, it requires locks to read system state.
9677     *
9678     * @throws PackageManagerException If the package fails any of the validation checks
9679     */
9680    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
9681            throws PackageManagerException {
9682        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
9683            assertCodePolicy(pkg);
9684        }
9685
9686        if (pkg.applicationInfo.getCodePath() == null ||
9687                pkg.applicationInfo.getResourcePath() == null) {
9688            // Bail out. The resource and code paths haven't been set.
9689            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9690                    "Code and resource paths haven't been set correctly");
9691        }
9692
9693        // Make sure we're not adding any bogus keyset info
9694        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9695        ksms.assertScannedPackageValid(pkg);
9696
9697        synchronized (mPackages) {
9698            // The special "android" package can only be defined once
9699            if (pkg.packageName.equals("android")) {
9700                if (mAndroidApplication != null) {
9701                    Slog.w(TAG, "*************************************************");
9702                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
9703                    Slog.w(TAG, " codePath=" + pkg.codePath);
9704                    Slog.w(TAG, "*************************************************");
9705                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9706                            "Core android package being redefined.  Skipping.");
9707                }
9708            }
9709
9710            // A package name must be unique; don't allow duplicates
9711            if (mPackages.containsKey(pkg.packageName)) {
9712                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9713                        "Application package " + pkg.packageName
9714                        + " already installed.  Skipping duplicate.");
9715            }
9716
9717            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9718                // Static libs have a synthetic package name containing the version
9719                // but we still want the base name to be unique.
9720                if (mPackages.containsKey(pkg.manifestPackageName)) {
9721                    throw new PackageManagerException(
9722                            "Duplicate static shared lib provider package");
9723                }
9724
9725                // Static shared libraries should have at least O target SDK
9726                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
9727                    throw new PackageManagerException(
9728                            "Packages declaring static-shared libs must target O SDK or higher");
9729                }
9730
9731                // Package declaring static a shared lib cannot be instant apps
9732                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
9733                    throw new PackageManagerException(
9734                            "Packages declaring static-shared libs cannot be instant apps");
9735                }
9736
9737                // Package declaring static a shared lib cannot be renamed since the package
9738                // name is synthetic and apps can't code around package manager internals.
9739                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
9740                    throw new PackageManagerException(
9741                            "Packages declaring static-shared libs cannot be renamed");
9742                }
9743
9744                // Package declaring static a shared lib cannot declare child packages
9745                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
9746                    throw new PackageManagerException(
9747                            "Packages declaring static-shared libs cannot have child packages");
9748                }
9749
9750                // Package declaring static a shared lib cannot declare dynamic libs
9751                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
9752                    throw new PackageManagerException(
9753                            "Packages declaring static-shared libs cannot declare dynamic libs");
9754                }
9755
9756                // Package declaring static a shared lib cannot declare shared users
9757                if (pkg.mSharedUserId != null) {
9758                    throw new PackageManagerException(
9759                            "Packages declaring static-shared libs cannot declare shared users");
9760                }
9761
9762                // Static shared libs cannot declare activities
9763                if (!pkg.activities.isEmpty()) {
9764                    throw new PackageManagerException(
9765                            "Static shared libs cannot declare activities");
9766                }
9767
9768                // Static shared libs cannot declare services
9769                if (!pkg.services.isEmpty()) {
9770                    throw new PackageManagerException(
9771                            "Static shared libs cannot declare services");
9772                }
9773
9774                // Static shared libs cannot declare providers
9775                if (!pkg.providers.isEmpty()) {
9776                    throw new PackageManagerException(
9777                            "Static shared libs cannot declare content providers");
9778                }
9779
9780                // Static shared libs cannot declare receivers
9781                if (!pkg.receivers.isEmpty()) {
9782                    throw new PackageManagerException(
9783                            "Static shared libs cannot declare broadcast receivers");
9784                }
9785
9786                // Static shared libs cannot declare permission groups
9787                if (!pkg.permissionGroups.isEmpty()) {
9788                    throw new PackageManagerException(
9789                            "Static shared libs cannot declare permission groups");
9790                }
9791
9792                // Static shared libs cannot declare permissions
9793                if (!pkg.permissions.isEmpty()) {
9794                    throw new PackageManagerException(
9795                            "Static shared libs cannot declare permissions");
9796                }
9797
9798                // Static shared libs cannot declare protected broadcasts
9799                if (pkg.protectedBroadcasts != null) {
9800                    throw new PackageManagerException(
9801                            "Static shared libs cannot declare protected broadcasts");
9802                }
9803
9804                // Static shared libs cannot be overlay targets
9805                if (pkg.mOverlayTarget != null) {
9806                    throw new PackageManagerException(
9807                            "Static shared libs cannot be overlay targets");
9808                }
9809
9810                // The version codes must be ordered as lib versions
9811                int minVersionCode = Integer.MIN_VALUE;
9812                int maxVersionCode = Integer.MAX_VALUE;
9813
9814                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9815                        pkg.staticSharedLibName);
9816                if (versionedLib != null) {
9817                    final int versionCount = versionedLib.size();
9818                    for (int i = 0; i < versionCount; i++) {
9819                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
9820                        // TODO: We will change version code to long, so in the new API it is long
9821                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
9822                                .getVersionCode();
9823                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
9824                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
9825                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
9826                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
9827                        } else {
9828                            minVersionCode = maxVersionCode = libVersionCode;
9829                            break;
9830                        }
9831                    }
9832                }
9833                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
9834                    throw new PackageManagerException("Static shared"
9835                            + " lib version codes must be ordered as lib versions");
9836                }
9837            }
9838
9839            // Only privileged apps and updated privileged apps can add child packages.
9840            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
9841                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
9842                    throw new PackageManagerException("Only privileged apps can add child "
9843                            + "packages. Ignoring package " + pkg.packageName);
9844                }
9845                final int childCount = pkg.childPackages.size();
9846                for (int i = 0; i < childCount; i++) {
9847                    PackageParser.Package childPkg = pkg.childPackages.get(i);
9848                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
9849                            childPkg.packageName)) {
9850                        throw new PackageManagerException("Can't override child of "
9851                                + "another disabled app. Ignoring package " + pkg.packageName);
9852                    }
9853                }
9854            }
9855
9856            // If we're only installing presumed-existing packages, require that the
9857            // scanned APK is both already known and at the path previously established
9858            // for it.  Previously unknown packages we pick up normally, but if we have an
9859            // a priori expectation about this package's install presence, enforce it.
9860            // With a singular exception for new system packages. When an OTA contains
9861            // a new system package, we allow the codepath to change from a system location
9862            // to the user-installed location. If we don't allow this change, any newer,
9863            // user-installed version of the application will be ignored.
9864            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
9865                if (mExpectingBetter.containsKey(pkg.packageName)) {
9866                    logCriticalInfo(Log.WARN,
9867                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
9868                } else {
9869                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
9870                    if (known != null) {
9871                        if (DEBUG_PACKAGE_SCANNING) {
9872                            Log.d(TAG, "Examining " + pkg.codePath
9873                                    + " and requiring known paths " + known.codePathString
9874                                    + " & " + known.resourcePathString);
9875                        }
9876                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
9877                                || !pkg.applicationInfo.getResourcePath().equals(
9878                                        known.resourcePathString)) {
9879                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
9880                                    "Application package " + pkg.packageName
9881                                    + " found at " + pkg.applicationInfo.getCodePath()
9882                                    + " but expected at " + known.codePathString
9883                                    + "; ignoring.");
9884                        }
9885                    }
9886                }
9887            }
9888
9889            // Verify that this new package doesn't have any content providers
9890            // that conflict with existing packages.  Only do this if the
9891            // package isn't already installed, since we don't want to break
9892            // things that are installed.
9893            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
9894                final int N = pkg.providers.size();
9895                int i;
9896                for (i=0; i<N; i++) {
9897                    PackageParser.Provider p = pkg.providers.get(i);
9898                    if (p.info.authority != null) {
9899                        String names[] = p.info.authority.split(";");
9900                        for (int j = 0; j < names.length; j++) {
9901                            if (mProvidersByAuthority.containsKey(names[j])) {
9902                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9903                                final String otherPackageName =
9904                                        ((other != null && other.getComponentName() != null) ?
9905                                                other.getComponentName().getPackageName() : "?");
9906                                throw new PackageManagerException(
9907                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
9908                                        "Can't install because provider name " + names[j]
9909                                                + " (in package " + pkg.applicationInfo.packageName
9910                                                + ") is already used by " + otherPackageName);
9911                            }
9912                        }
9913                    }
9914                }
9915            }
9916        }
9917    }
9918
9919    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
9920            int type, String declaringPackageName, int declaringVersionCode) {
9921        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9922        if (versionedLib == null) {
9923            versionedLib = new SparseArray<>();
9924            mSharedLibraries.put(name, versionedLib);
9925            if (type == SharedLibraryInfo.TYPE_STATIC) {
9926                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
9927            }
9928        } else if (versionedLib.indexOfKey(version) >= 0) {
9929            return false;
9930        }
9931        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
9932                version, type, declaringPackageName, declaringVersionCode);
9933        versionedLib.put(version, libEntry);
9934        return true;
9935    }
9936
9937    private boolean removeSharedLibraryLPw(String name, int version) {
9938        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9939        if (versionedLib == null) {
9940            return false;
9941        }
9942        final int libIdx = versionedLib.indexOfKey(version);
9943        if (libIdx < 0) {
9944            return false;
9945        }
9946        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
9947        versionedLib.remove(version);
9948        if (versionedLib.size() <= 0) {
9949            mSharedLibraries.remove(name);
9950            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
9951                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
9952                        .getPackageName());
9953            }
9954        }
9955        return true;
9956    }
9957
9958    /**
9959     * Adds a scanned package to the system. When this method is finished, the package will
9960     * be available for query, resolution, etc...
9961     */
9962    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
9963            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
9964        final String pkgName = pkg.packageName;
9965        if (mCustomResolverComponentName != null &&
9966                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
9967            setUpCustomResolverActivity(pkg);
9968        }
9969
9970        if (pkg.packageName.equals("android")) {
9971            synchronized (mPackages) {
9972                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9973                    // Set up information for our fall-back user intent resolution activity.
9974                    mPlatformPackage = pkg;
9975                    pkg.mVersionCode = mSdkVersion;
9976                    mAndroidApplication = pkg.applicationInfo;
9977                    if (!mResolverReplaced) {
9978                        mResolveActivity.applicationInfo = mAndroidApplication;
9979                        mResolveActivity.name = ResolverActivity.class.getName();
9980                        mResolveActivity.packageName = mAndroidApplication.packageName;
9981                        mResolveActivity.processName = "system:ui";
9982                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9983                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
9984                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
9985                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
9986                        mResolveActivity.exported = true;
9987                        mResolveActivity.enabled = true;
9988                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
9989                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
9990                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
9991                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
9992                                | ActivityInfo.CONFIG_ORIENTATION
9993                                | ActivityInfo.CONFIG_KEYBOARD
9994                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
9995                        mResolveInfo.activityInfo = mResolveActivity;
9996                        mResolveInfo.priority = 0;
9997                        mResolveInfo.preferredOrder = 0;
9998                        mResolveInfo.match = 0;
9999                        mResolveComponentName = new ComponentName(
10000                                mAndroidApplication.packageName, mResolveActivity.name);
10001                    }
10002                }
10003            }
10004        }
10005
10006        ArrayList<PackageParser.Package> clientLibPkgs = null;
10007        // writer
10008        synchronized (mPackages) {
10009            boolean hasStaticSharedLibs = false;
10010
10011            // Any app can add new static shared libraries
10012            if (pkg.staticSharedLibName != null) {
10013                // Static shared libs don't allow renaming as they have synthetic package
10014                // names to allow install of multiple versions, so use name from manifest.
10015                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
10016                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
10017                        pkg.manifestPackageName, pkg.mVersionCode)) {
10018                    hasStaticSharedLibs = true;
10019                } else {
10020                    Slog.w(TAG, "Package " + pkg.packageName + " library "
10021                                + pkg.staticSharedLibName + " already exists; skipping");
10022                }
10023                // Static shared libs cannot be updated once installed since they
10024                // use synthetic package name which includes the version code, so
10025                // not need to update other packages's shared lib dependencies.
10026            }
10027
10028            if (!hasStaticSharedLibs
10029                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10030                // Only system apps can add new dynamic shared libraries.
10031                if (pkg.libraryNames != null) {
10032                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
10033                        String name = pkg.libraryNames.get(i);
10034                        boolean allowed = false;
10035                        if (pkg.isUpdatedSystemApp()) {
10036                            // New library entries can only be added through the
10037                            // system image.  This is important to get rid of a lot
10038                            // of nasty edge cases: for example if we allowed a non-
10039                            // system update of the app to add a library, then uninstalling
10040                            // the update would make the library go away, and assumptions
10041                            // we made such as through app install filtering would now
10042                            // have allowed apps on the device which aren't compatible
10043                            // with it.  Better to just have the restriction here, be
10044                            // conservative, and create many fewer cases that can negatively
10045                            // impact the user experience.
10046                            final PackageSetting sysPs = mSettings
10047                                    .getDisabledSystemPkgLPr(pkg.packageName);
10048                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
10049                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
10050                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
10051                                        allowed = true;
10052                                        break;
10053                                    }
10054                                }
10055                            }
10056                        } else {
10057                            allowed = true;
10058                        }
10059                        if (allowed) {
10060                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
10061                                    SharedLibraryInfo.VERSION_UNDEFINED,
10062                                    SharedLibraryInfo.TYPE_DYNAMIC,
10063                                    pkg.packageName, pkg.mVersionCode)) {
10064                                Slog.w(TAG, "Package " + pkg.packageName + " library "
10065                                        + name + " already exists; skipping");
10066                            }
10067                        } else {
10068                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
10069                                    + name + " that is not declared on system image; skipping");
10070                        }
10071                    }
10072
10073                    if ((scanFlags & SCAN_BOOTING) == 0) {
10074                        // If we are not booting, we need to update any applications
10075                        // that are clients of our shared library.  If we are booting,
10076                        // this will all be done once the scan is complete.
10077                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
10078                    }
10079                }
10080            }
10081        }
10082
10083        if ((scanFlags & SCAN_BOOTING) != 0) {
10084            // No apps can run during boot scan, so they don't need to be frozen
10085        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
10086            // Caller asked to not kill app, so it's probably not frozen
10087        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
10088            // Caller asked us to ignore frozen check for some reason; they
10089            // probably didn't know the package name
10090        } else {
10091            // We're doing major surgery on this package, so it better be frozen
10092            // right now to keep it from launching
10093            checkPackageFrozen(pkgName);
10094        }
10095
10096        // Also need to kill any apps that are dependent on the library.
10097        if (clientLibPkgs != null) {
10098            for (int i=0; i<clientLibPkgs.size(); i++) {
10099                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10100                killApplication(clientPkg.applicationInfo.packageName,
10101                        clientPkg.applicationInfo.uid, "update lib");
10102            }
10103        }
10104
10105        // writer
10106        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10107
10108        synchronized (mPackages) {
10109            // We don't expect installation to fail beyond this point
10110
10111            // Add the new setting to mSettings
10112            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10113            // Add the new setting to mPackages
10114            mPackages.put(pkg.applicationInfo.packageName, pkg);
10115            // Make sure we don't accidentally delete its data.
10116            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10117            while (iter.hasNext()) {
10118                PackageCleanItem item = iter.next();
10119                if (pkgName.equals(item.packageName)) {
10120                    iter.remove();
10121                }
10122            }
10123
10124            // Add the package's KeySets to the global KeySetManagerService
10125            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10126            ksms.addScannedPackageLPw(pkg);
10127
10128            int N = pkg.providers.size();
10129            StringBuilder r = null;
10130            int i;
10131            for (i=0; i<N; i++) {
10132                PackageParser.Provider p = pkg.providers.get(i);
10133                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10134                        p.info.processName);
10135                mProviders.addProvider(p);
10136                p.syncable = p.info.isSyncable;
10137                if (p.info.authority != null) {
10138                    String names[] = p.info.authority.split(";");
10139                    p.info.authority = null;
10140                    for (int j = 0; j < names.length; j++) {
10141                        if (j == 1 && p.syncable) {
10142                            // We only want the first authority for a provider to possibly be
10143                            // syncable, so if we already added this provider using a different
10144                            // authority clear the syncable flag. We copy the provider before
10145                            // changing it because the mProviders object contains a reference
10146                            // to a provider that we don't want to change.
10147                            // Only do this for the second authority since the resulting provider
10148                            // object can be the same for all future authorities for this provider.
10149                            p = new PackageParser.Provider(p);
10150                            p.syncable = false;
10151                        }
10152                        if (!mProvidersByAuthority.containsKey(names[j])) {
10153                            mProvidersByAuthority.put(names[j], p);
10154                            if (p.info.authority == null) {
10155                                p.info.authority = names[j];
10156                            } else {
10157                                p.info.authority = p.info.authority + ";" + names[j];
10158                            }
10159                            if (DEBUG_PACKAGE_SCANNING) {
10160                                if (chatty)
10161                                    Log.d(TAG, "Registered content provider: " + names[j]
10162                                            + ", className = " + p.info.name + ", isSyncable = "
10163                                            + p.info.isSyncable);
10164                            }
10165                        } else {
10166                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10167                            Slog.w(TAG, "Skipping provider name " + names[j] +
10168                                    " (in package " + pkg.applicationInfo.packageName +
10169                                    "): name already used by "
10170                                    + ((other != null && other.getComponentName() != null)
10171                                            ? other.getComponentName().getPackageName() : "?"));
10172                        }
10173                    }
10174                }
10175                if (chatty) {
10176                    if (r == null) {
10177                        r = new StringBuilder(256);
10178                    } else {
10179                        r.append(' ');
10180                    }
10181                    r.append(p.info.name);
10182                }
10183            }
10184            if (r != null) {
10185                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10186            }
10187
10188            N = pkg.services.size();
10189            r = null;
10190            for (i=0; i<N; i++) {
10191                PackageParser.Service s = pkg.services.get(i);
10192                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10193                        s.info.processName);
10194                mServices.addService(s);
10195                if (chatty) {
10196                    if (r == null) {
10197                        r = new StringBuilder(256);
10198                    } else {
10199                        r.append(' ');
10200                    }
10201                    r.append(s.info.name);
10202                }
10203            }
10204            if (r != null) {
10205                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10206            }
10207
10208            N = pkg.receivers.size();
10209            r = null;
10210            for (i=0; i<N; i++) {
10211                PackageParser.Activity a = pkg.receivers.get(i);
10212                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10213                        a.info.processName);
10214                mReceivers.addActivity(a, "receiver");
10215                if (chatty) {
10216                    if (r == null) {
10217                        r = new StringBuilder(256);
10218                    } else {
10219                        r.append(' ');
10220                    }
10221                    r.append(a.info.name);
10222                }
10223            }
10224            if (r != null) {
10225                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10226            }
10227
10228            N = pkg.activities.size();
10229            r = null;
10230            for (i=0; i<N; i++) {
10231                PackageParser.Activity a = pkg.activities.get(i);
10232                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10233                        a.info.processName);
10234                mActivities.addActivity(a, "activity");
10235                if (chatty) {
10236                    if (r == null) {
10237                        r = new StringBuilder(256);
10238                    } else {
10239                        r.append(' ');
10240                    }
10241                    r.append(a.info.name);
10242                }
10243            }
10244            if (r != null) {
10245                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10246            }
10247
10248            N = pkg.permissionGroups.size();
10249            r = null;
10250            for (i=0; i<N; i++) {
10251                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10252                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10253                final String curPackageName = cur == null ? null : cur.info.packageName;
10254                // Dont allow ephemeral apps to define new permission groups.
10255                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10256                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10257                            + pg.info.packageName
10258                            + " ignored: instant apps cannot define new permission groups.");
10259                    continue;
10260                }
10261                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10262                if (cur == null || isPackageUpdate) {
10263                    mPermissionGroups.put(pg.info.name, pg);
10264                    if (chatty) {
10265                        if (r == null) {
10266                            r = new StringBuilder(256);
10267                        } else {
10268                            r.append(' ');
10269                        }
10270                        if (isPackageUpdate) {
10271                            r.append("UPD:");
10272                        }
10273                        r.append(pg.info.name);
10274                    }
10275                } else {
10276                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10277                            + pg.info.packageName + " ignored: original from "
10278                            + cur.info.packageName);
10279                    if (chatty) {
10280                        if (r == null) {
10281                            r = new StringBuilder(256);
10282                        } else {
10283                            r.append(' ');
10284                        }
10285                        r.append("DUP:");
10286                        r.append(pg.info.name);
10287                    }
10288                }
10289            }
10290            if (r != null) {
10291                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10292            }
10293
10294            N = pkg.permissions.size();
10295            r = null;
10296            for (i=0; i<N; i++) {
10297                PackageParser.Permission p = pkg.permissions.get(i);
10298
10299                // Dont allow ephemeral apps to define new permissions.
10300                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10301                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10302                            + p.info.packageName
10303                            + " ignored: instant apps cannot define new permissions.");
10304                    continue;
10305                }
10306
10307                // Assume by default that we did not install this permission into the system.
10308                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10309
10310                // Now that permission groups have a special meaning, we ignore permission
10311                // groups for legacy apps to prevent unexpected behavior. In particular,
10312                // permissions for one app being granted to someone just becase they happen
10313                // to be in a group defined by another app (before this had no implications).
10314                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10315                    p.group = mPermissionGroups.get(p.info.group);
10316                    // Warn for a permission in an unknown group.
10317                    if (p.info.group != null && p.group == null) {
10318                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10319                                + p.info.packageName + " in an unknown group " + p.info.group);
10320                    }
10321                }
10322
10323                ArrayMap<String, BasePermission> permissionMap =
10324                        p.tree ? mSettings.mPermissionTrees
10325                                : mSettings.mPermissions;
10326                BasePermission bp = permissionMap.get(p.info.name);
10327
10328                // Allow system apps to redefine non-system permissions
10329                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10330                    final boolean currentOwnerIsSystem = (bp.perm != null
10331                            && isSystemApp(bp.perm.owner));
10332                    if (isSystemApp(p.owner)) {
10333                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10334                            // It's a built-in permission and no owner, take ownership now
10335                            bp.packageSetting = pkgSetting;
10336                            bp.perm = p;
10337                            bp.uid = pkg.applicationInfo.uid;
10338                            bp.sourcePackage = p.info.packageName;
10339                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10340                        } else if (!currentOwnerIsSystem) {
10341                            String msg = "New decl " + p.owner + " of permission  "
10342                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10343                            reportSettingsProblem(Log.WARN, msg);
10344                            bp = null;
10345                        }
10346                    }
10347                }
10348
10349                if (bp == null) {
10350                    bp = new BasePermission(p.info.name, p.info.packageName,
10351                            BasePermission.TYPE_NORMAL);
10352                    permissionMap.put(p.info.name, bp);
10353                }
10354
10355                if (bp.perm == null) {
10356                    if (bp.sourcePackage == null
10357                            || bp.sourcePackage.equals(p.info.packageName)) {
10358                        BasePermission tree = findPermissionTreeLP(p.info.name);
10359                        if (tree == null
10360                                || tree.sourcePackage.equals(p.info.packageName)) {
10361                            bp.packageSetting = pkgSetting;
10362                            bp.perm = p;
10363                            bp.uid = pkg.applicationInfo.uid;
10364                            bp.sourcePackage = p.info.packageName;
10365                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10366                            if (chatty) {
10367                                if (r == null) {
10368                                    r = new StringBuilder(256);
10369                                } else {
10370                                    r.append(' ');
10371                                }
10372                                r.append(p.info.name);
10373                            }
10374                        } else {
10375                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10376                                    + p.info.packageName + " ignored: base tree "
10377                                    + tree.name + " is from package "
10378                                    + tree.sourcePackage);
10379                        }
10380                    } else {
10381                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10382                                + p.info.packageName + " ignored: original from "
10383                                + bp.sourcePackage);
10384                    }
10385                } else if (chatty) {
10386                    if (r == null) {
10387                        r = new StringBuilder(256);
10388                    } else {
10389                        r.append(' ');
10390                    }
10391                    r.append("DUP:");
10392                    r.append(p.info.name);
10393                }
10394                if (bp.perm == p) {
10395                    bp.protectionLevel = p.info.protectionLevel;
10396                }
10397            }
10398
10399            if (r != null) {
10400                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10401            }
10402
10403            N = pkg.instrumentation.size();
10404            r = null;
10405            for (i=0; i<N; i++) {
10406                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10407                a.info.packageName = pkg.applicationInfo.packageName;
10408                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10409                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10410                a.info.splitNames = pkg.splitNames;
10411                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10412                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10413                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10414                a.info.dataDir = pkg.applicationInfo.dataDir;
10415                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10416                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10417                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10418                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10419                mInstrumentation.put(a.getComponentName(), a);
10420                if (chatty) {
10421                    if (r == null) {
10422                        r = new StringBuilder(256);
10423                    } else {
10424                        r.append(' ');
10425                    }
10426                    r.append(a.info.name);
10427                }
10428            }
10429            if (r != null) {
10430                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10431            }
10432
10433            if (pkg.protectedBroadcasts != null) {
10434                N = pkg.protectedBroadcasts.size();
10435                for (i=0; i<N; i++) {
10436                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10437                }
10438            }
10439        }
10440
10441        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10442    }
10443
10444    /**
10445     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10446     * is derived purely on the basis of the contents of {@code scanFile} and
10447     * {@code cpuAbiOverride}.
10448     *
10449     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10450     */
10451    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10452                                 String cpuAbiOverride, boolean extractLibs,
10453                                 File appLib32InstallDir)
10454            throws PackageManagerException {
10455        // Give ourselves some initial paths; we'll come back for another
10456        // pass once we've determined ABI below.
10457        setNativeLibraryPaths(pkg, appLib32InstallDir);
10458
10459        // We would never need to extract libs for forward-locked and external packages,
10460        // since the container service will do it for us. We shouldn't attempt to
10461        // extract libs from system app when it was not updated.
10462        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10463                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10464            extractLibs = false;
10465        }
10466
10467        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10468        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10469
10470        NativeLibraryHelper.Handle handle = null;
10471        try {
10472            handle = NativeLibraryHelper.Handle.create(pkg);
10473            // TODO(multiArch): This can be null for apps that didn't go through the
10474            // usual installation process. We can calculate it again, like we
10475            // do during install time.
10476            //
10477            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10478            // unnecessary.
10479            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10480
10481            // Null out the abis so that they can be recalculated.
10482            pkg.applicationInfo.primaryCpuAbi = null;
10483            pkg.applicationInfo.secondaryCpuAbi = null;
10484            if (isMultiArch(pkg.applicationInfo)) {
10485                // Warn if we've set an abiOverride for multi-lib packages..
10486                // By definition, we need to copy both 32 and 64 bit libraries for
10487                // such packages.
10488                if (pkg.cpuAbiOverride != null
10489                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10490                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10491                }
10492
10493                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10494                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10495                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10496                    if (extractLibs) {
10497                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10498                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10499                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10500                                useIsaSpecificSubdirs);
10501                    } else {
10502                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10503                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10504                    }
10505                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10506                }
10507
10508                maybeThrowExceptionForMultiArchCopy(
10509                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10510
10511                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10512                    if (extractLibs) {
10513                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10514                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10515                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10516                                useIsaSpecificSubdirs);
10517                    } else {
10518                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10519                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10520                    }
10521                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10522                }
10523
10524                maybeThrowExceptionForMultiArchCopy(
10525                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10526
10527                if (abi64 >= 0) {
10528                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10529                }
10530
10531                if (abi32 >= 0) {
10532                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10533                    if (abi64 >= 0) {
10534                        if (pkg.use32bitAbi) {
10535                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10536                            pkg.applicationInfo.primaryCpuAbi = abi;
10537                        } else {
10538                            pkg.applicationInfo.secondaryCpuAbi = abi;
10539                        }
10540                    } else {
10541                        pkg.applicationInfo.primaryCpuAbi = abi;
10542                    }
10543                }
10544
10545            } else {
10546                String[] abiList = (cpuAbiOverride != null) ?
10547                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10548
10549                // Enable gross and lame hacks for apps that are built with old
10550                // SDK tools. We must scan their APKs for renderscript bitcode and
10551                // not launch them if it's present. Don't bother checking on devices
10552                // that don't have 64 bit support.
10553                boolean needsRenderScriptOverride = false;
10554                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10555                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10556                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10557                    needsRenderScriptOverride = true;
10558                }
10559
10560                final int copyRet;
10561                if (extractLibs) {
10562                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10563                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10564                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10565                } else {
10566                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10567                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10568                }
10569                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10570
10571                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10572                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10573                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10574                }
10575
10576                if (copyRet >= 0) {
10577                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10578                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10579                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10580                } else if (needsRenderScriptOverride) {
10581                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10582                }
10583            }
10584        } catch (IOException ioe) {
10585            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10586        } finally {
10587            IoUtils.closeQuietly(handle);
10588        }
10589
10590        // Now that we've calculated the ABIs and determined if it's an internal app,
10591        // we will go ahead and populate the nativeLibraryPath.
10592        setNativeLibraryPaths(pkg, appLib32InstallDir);
10593    }
10594
10595    /**
10596     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10597     * i.e, so that all packages can be run inside a single process if required.
10598     *
10599     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10600     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10601     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10602     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10603     * updating a package that belongs to a shared user.
10604     *
10605     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10606     * adds unnecessary complexity.
10607     */
10608    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10609            PackageParser.Package scannedPackage) {
10610        String requiredInstructionSet = null;
10611        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10612            requiredInstructionSet = VMRuntime.getInstructionSet(
10613                     scannedPackage.applicationInfo.primaryCpuAbi);
10614        }
10615
10616        PackageSetting requirer = null;
10617        for (PackageSetting ps : packagesForUser) {
10618            // If packagesForUser contains scannedPackage, we skip it. This will happen
10619            // when scannedPackage is an update of an existing package. Without this check,
10620            // we will never be able to change the ABI of any package belonging to a shared
10621            // user, even if it's compatible with other packages.
10622            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10623                if (ps.primaryCpuAbiString == null) {
10624                    continue;
10625                }
10626
10627                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10628                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10629                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10630                    // this but there's not much we can do.
10631                    String errorMessage = "Instruction set mismatch, "
10632                            + ((requirer == null) ? "[caller]" : requirer)
10633                            + " requires " + requiredInstructionSet + " whereas " + ps
10634                            + " requires " + instructionSet;
10635                    Slog.w(TAG, errorMessage);
10636                }
10637
10638                if (requiredInstructionSet == null) {
10639                    requiredInstructionSet = instructionSet;
10640                    requirer = ps;
10641                }
10642            }
10643        }
10644
10645        if (requiredInstructionSet != null) {
10646            String adjustedAbi;
10647            if (requirer != null) {
10648                // requirer != null implies that either scannedPackage was null or that scannedPackage
10649                // did not require an ABI, in which case we have to adjust scannedPackage to match
10650                // the ABI of the set (which is the same as requirer's ABI)
10651                adjustedAbi = requirer.primaryCpuAbiString;
10652                if (scannedPackage != null) {
10653                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10654                }
10655            } else {
10656                // requirer == null implies that we're updating all ABIs in the set to
10657                // match scannedPackage.
10658                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10659            }
10660
10661            for (PackageSetting ps : packagesForUser) {
10662                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10663                    if (ps.primaryCpuAbiString != null) {
10664                        continue;
10665                    }
10666
10667                    ps.primaryCpuAbiString = adjustedAbi;
10668                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
10669                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
10670                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
10671                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
10672                                + " (requirer="
10673                                + (requirer != null ? requirer.pkg : "null")
10674                                + ", scannedPackage="
10675                                + (scannedPackage != null ? scannedPackage : "null")
10676                                + ")");
10677                        try {
10678                            mInstaller.rmdex(ps.codePathString,
10679                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
10680                        } catch (InstallerException ignored) {
10681                        }
10682                    }
10683                }
10684            }
10685        }
10686    }
10687
10688    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
10689        synchronized (mPackages) {
10690            mResolverReplaced = true;
10691            // Set up information for custom user intent resolution activity.
10692            mResolveActivity.applicationInfo = pkg.applicationInfo;
10693            mResolveActivity.name = mCustomResolverComponentName.getClassName();
10694            mResolveActivity.packageName = pkg.applicationInfo.packageName;
10695            mResolveActivity.processName = pkg.applicationInfo.packageName;
10696            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10697            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
10698                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10699            mResolveActivity.theme = 0;
10700            mResolveActivity.exported = true;
10701            mResolveActivity.enabled = true;
10702            mResolveInfo.activityInfo = mResolveActivity;
10703            mResolveInfo.priority = 0;
10704            mResolveInfo.preferredOrder = 0;
10705            mResolveInfo.match = 0;
10706            mResolveComponentName = mCustomResolverComponentName;
10707            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
10708                    mResolveComponentName);
10709        }
10710    }
10711
10712    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
10713        if (installerActivity == null) {
10714            if (DEBUG_EPHEMERAL) {
10715                Slog.d(TAG, "Clear ephemeral installer activity");
10716            }
10717            mInstantAppInstallerActivity = null;
10718            return;
10719        }
10720
10721        if (DEBUG_EPHEMERAL) {
10722            Slog.d(TAG, "Set ephemeral installer activity: "
10723                    + installerActivity.getComponentName());
10724        }
10725        // Set up information for ephemeral installer activity
10726        mInstantAppInstallerActivity = installerActivity;
10727        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
10728                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10729        mInstantAppInstallerActivity.exported = true;
10730        mInstantAppInstallerActivity.enabled = true;
10731        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
10732        mInstantAppInstallerInfo.priority = 0;
10733        mInstantAppInstallerInfo.preferredOrder = 1;
10734        mInstantAppInstallerInfo.isDefault = true;
10735        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
10736                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
10737    }
10738
10739    private static String calculateBundledApkRoot(final String codePathString) {
10740        final File codePath = new File(codePathString);
10741        final File codeRoot;
10742        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
10743            codeRoot = Environment.getRootDirectory();
10744        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
10745            codeRoot = Environment.getOemDirectory();
10746        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
10747            codeRoot = Environment.getVendorDirectory();
10748        } else {
10749            // Unrecognized code path; take its top real segment as the apk root:
10750            // e.g. /something/app/blah.apk => /something
10751            try {
10752                File f = codePath.getCanonicalFile();
10753                File parent = f.getParentFile();    // non-null because codePath is a file
10754                File tmp;
10755                while ((tmp = parent.getParentFile()) != null) {
10756                    f = parent;
10757                    parent = tmp;
10758                }
10759                codeRoot = f;
10760                Slog.w(TAG, "Unrecognized code path "
10761                        + codePath + " - using " + codeRoot);
10762            } catch (IOException e) {
10763                // Can't canonicalize the code path -- shenanigans?
10764                Slog.w(TAG, "Can't canonicalize code path " + codePath);
10765                return Environment.getRootDirectory().getPath();
10766            }
10767        }
10768        return codeRoot.getPath();
10769    }
10770
10771    /**
10772     * Derive and set the location of native libraries for the given package,
10773     * which varies depending on where and how the package was installed.
10774     */
10775    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
10776        final ApplicationInfo info = pkg.applicationInfo;
10777        final String codePath = pkg.codePath;
10778        final File codeFile = new File(codePath);
10779        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
10780        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
10781
10782        info.nativeLibraryRootDir = null;
10783        info.nativeLibraryRootRequiresIsa = false;
10784        info.nativeLibraryDir = null;
10785        info.secondaryNativeLibraryDir = null;
10786
10787        if (isApkFile(codeFile)) {
10788            // Monolithic install
10789            if (bundledApp) {
10790                // If "/system/lib64/apkname" exists, assume that is the per-package
10791                // native library directory to use; otherwise use "/system/lib/apkname".
10792                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
10793                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
10794                        getPrimaryInstructionSet(info));
10795
10796                // This is a bundled system app so choose the path based on the ABI.
10797                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
10798                // is just the default path.
10799                final String apkName = deriveCodePathName(codePath);
10800                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
10801                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
10802                        apkName).getAbsolutePath();
10803
10804                if (info.secondaryCpuAbi != null) {
10805                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
10806                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
10807                            secondaryLibDir, apkName).getAbsolutePath();
10808                }
10809            } else if (asecApp) {
10810                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
10811                        .getAbsolutePath();
10812            } else {
10813                final String apkName = deriveCodePathName(codePath);
10814                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
10815                        .getAbsolutePath();
10816            }
10817
10818            info.nativeLibraryRootRequiresIsa = false;
10819            info.nativeLibraryDir = info.nativeLibraryRootDir;
10820        } else {
10821            // Cluster install
10822            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10823            info.nativeLibraryRootRequiresIsa = true;
10824
10825            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10826                    getPrimaryInstructionSet(info)).getAbsolutePath();
10827
10828            if (info.secondaryCpuAbi != null) {
10829                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10830                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10831            }
10832        }
10833    }
10834
10835    /**
10836     * Calculate the abis and roots for a bundled app. These can uniquely
10837     * be determined from the contents of the system partition, i.e whether
10838     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10839     * of this information, and instead assume that the system was built
10840     * sensibly.
10841     */
10842    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10843                                           PackageSetting pkgSetting) {
10844        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10845
10846        // If "/system/lib64/apkname" exists, assume that is the per-package
10847        // native library directory to use; otherwise use "/system/lib/apkname".
10848        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10849        setBundledAppAbi(pkg, apkRoot, apkName);
10850        // pkgSetting might be null during rescan following uninstall of updates
10851        // to a bundled app, so accommodate that possibility.  The settings in
10852        // that case will be established later from the parsed package.
10853        //
10854        // If the settings aren't null, sync them up with what we've just derived.
10855        // note that apkRoot isn't stored in the package settings.
10856        if (pkgSetting != null) {
10857            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10858            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10859        }
10860    }
10861
10862    /**
10863     * Deduces the ABI of a bundled app and sets the relevant fields on the
10864     * parsed pkg object.
10865     *
10866     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
10867     *        under which system libraries are installed.
10868     * @param apkName the name of the installed package.
10869     */
10870    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
10871        final File codeFile = new File(pkg.codePath);
10872
10873        final boolean has64BitLibs;
10874        final boolean has32BitLibs;
10875        if (isApkFile(codeFile)) {
10876            // Monolithic install
10877            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
10878            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
10879        } else {
10880            // Cluster install
10881            final File rootDir = new File(codeFile, LIB_DIR_NAME);
10882            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
10883                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
10884                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
10885                has64BitLibs = (new File(rootDir, isa)).exists();
10886            } else {
10887                has64BitLibs = false;
10888            }
10889            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
10890                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
10891                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
10892                has32BitLibs = (new File(rootDir, isa)).exists();
10893            } else {
10894                has32BitLibs = false;
10895            }
10896        }
10897
10898        if (has64BitLibs && !has32BitLibs) {
10899            // The package has 64 bit libs, but not 32 bit libs. Its primary
10900            // ABI should be 64 bit. We can safely assume here that the bundled
10901            // native libraries correspond to the most preferred ABI in the list.
10902
10903            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10904            pkg.applicationInfo.secondaryCpuAbi = null;
10905        } else if (has32BitLibs && !has64BitLibs) {
10906            // The package has 32 bit libs but not 64 bit libs. Its primary
10907            // ABI should be 32 bit.
10908
10909            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10910            pkg.applicationInfo.secondaryCpuAbi = null;
10911        } else if (has32BitLibs && has64BitLibs) {
10912            // The application has both 64 and 32 bit bundled libraries. We check
10913            // here that the app declares multiArch support, and warn if it doesn't.
10914            //
10915            // We will be lenient here and record both ABIs. The primary will be the
10916            // ABI that's higher on the list, i.e, a device that's configured to prefer
10917            // 64 bit apps will see a 64 bit primary ABI,
10918
10919            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
10920                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
10921            }
10922
10923            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
10924                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10925                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10926            } else {
10927                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10928                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10929            }
10930        } else {
10931            pkg.applicationInfo.primaryCpuAbi = null;
10932            pkg.applicationInfo.secondaryCpuAbi = null;
10933        }
10934    }
10935
10936    private void killApplication(String pkgName, int appId, String reason) {
10937        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
10938    }
10939
10940    private void killApplication(String pkgName, int appId, int userId, String reason) {
10941        // Request the ActivityManager to kill the process(only for existing packages)
10942        // so that we do not end up in a confused state while the user is still using the older
10943        // version of the application while the new one gets installed.
10944        final long token = Binder.clearCallingIdentity();
10945        try {
10946            IActivityManager am = ActivityManager.getService();
10947            if (am != null) {
10948                try {
10949                    am.killApplication(pkgName, appId, userId, reason);
10950                } catch (RemoteException e) {
10951                }
10952            }
10953        } finally {
10954            Binder.restoreCallingIdentity(token);
10955        }
10956    }
10957
10958    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10959        // Remove the parent package setting
10960        PackageSetting ps = (PackageSetting) pkg.mExtras;
10961        if (ps != null) {
10962            removePackageLI(ps, chatty);
10963        }
10964        // Remove the child package setting
10965        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10966        for (int i = 0; i < childCount; i++) {
10967            PackageParser.Package childPkg = pkg.childPackages.get(i);
10968            ps = (PackageSetting) childPkg.mExtras;
10969            if (ps != null) {
10970                removePackageLI(ps, chatty);
10971            }
10972        }
10973    }
10974
10975    void removePackageLI(PackageSetting ps, boolean chatty) {
10976        if (DEBUG_INSTALL) {
10977            if (chatty)
10978                Log.d(TAG, "Removing package " + ps.name);
10979        }
10980
10981        // writer
10982        synchronized (mPackages) {
10983            mPackages.remove(ps.name);
10984            final PackageParser.Package pkg = ps.pkg;
10985            if (pkg != null) {
10986                cleanPackageDataStructuresLILPw(pkg, chatty);
10987            }
10988        }
10989    }
10990
10991    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
10992        if (DEBUG_INSTALL) {
10993            if (chatty)
10994                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
10995        }
10996
10997        // writer
10998        synchronized (mPackages) {
10999            // Remove the parent package
11000            mPackages.remove(pkg.applicationInfo.packageName);
11001            cleanPackageDataStructuresLILPw(pkg, chatty);
11002
11003            // Remove the child packages
11004            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11005            for (int i = 0; i < childCount; i++) {
11006                PackageParser.Package childPkg = pkg.childPackages.get(i);
11007                mPackages.remove(childPkg.applicationInfo.packageName);
11008                cleanPackageDataStructuresLILPw(childPkg, chatty);
11009            }
11010        }
11011    }
11012
11013    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
11014        int N = pkg.providers.size();
11015        StringBuilder r = null;
11016        int i;
11017        for (i=0; i<N; i++) {
11018            PackageParser.Provider p = pkg.providers.get(i);
11019            mProviders.removeProvider(p);
11020            if (p.info.authority == null) {
11021
11022                /* There was another ContentProvider with this authority when
11023                 * this app was installed so this authority is null,
11024                 * Ignore it as we don't have to unregister the provider.
11025                 */
11026                continue;
11027            }
11028            String names[] = p.info.authority.split(";");
11029            for (int j = 0; j < names.length; j++) {
11030                if (mProvidersByAuthority.get(names[j]) == p) {
11031                    mProvidersByAuthority.remove(names[j]);
11032                    if (DEBUG_REMOVE) {
11033                        if (chatty)
11034                            Log.d(TAG, "Unregistered content provider: " + names[j]
11035                                    + ", className = " + p.info.name + ", isSyncable = "
11036                                    + p.info.isSyncable);
11037                    }
11038                }
11039            }
11040            if (DEBUG_REMOVE && chatty) {
11041                if (r == null) {
11042                    r = new StringBuilder(256);
11043                } else {
11044                    r.append(' ');
11045                }
11046                r.append(p.info.name);
11047            }
11048        }
11049        if (r != null) {
11050            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
11051        }
11052
11053        N = pkg.services.size();
11054        r = null;
11055        for (i=0; i<N; i++) {
11056            PackageParser.Service s = pkg.services.get(i);
11057            mServices.removeService(s);
11058            if (chatty) {
11059                if (r == null) {
11060                    r = new StringBuilder(256);
11061                } else {
11062                    r.append(' ');
11063                }
11064                r.append(s.info.name);
11065            }
11066        }
11067        if (r != null) {
11068            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
11069        }
11070
11071        N = pkg.receivers.size();
11072        r = null;
11073        for (i=0; i<N; i++) {
11074            PackageParser.Activity a = pkg.receivers.get(i);
11075            mReceivers.removeActivity(a, "receiver");
11076            if (DEBUG_REMOVE && chatty) {
11077                if (r == null) {
11078                    r = new StringBuilder(256);
11079                } else {
11080                    r.append(' ');
11081                }
11082                r.append(a.info.name);
11083            }
11084        }
11085        if (r != null) {
11086            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
11087        }
11088
11089        N = pkg.activities.size();
11090        r = null;
11091        for (i=0; i<N; i++) {
11092            PackageParser.Activity a = pkg.activities.get(i);
11093            mActivities.removeActivity(a, "activity");
11094            if (DEBUG_REMOVE && chatty) {
11095                if (r == null) {
11096                    r = new StringBuilder(256);
11097                } else {
11098                    r.append(' ');
11099                }
11100                r.append(a.info.name);
11101            }
11102        }
11103        if (r != null) {
11104            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11105        }
11106
11107        N = pkg.permissions.size();
11108        r = null;
11109        for (i=0; i<N; i++) {
11110            PackageParser.Permission p = pkg.permissions.get(i);
11111            BasePermission bp = mSettings.mPermissions.get(p.info.name);
11112            if (bp == null) {
11113                bp = mSettings.mPermissionTrees.get(p.info.name);
11114            }
11115            if (bp != null && bp.perm == p) {
11116                bp.perm = null;
11117                if (DEBUG_REMOVE && chatty) {
11118                    if (r == null) {
11119                        r = new StringBuilder(256);
11120                    } else {
11121                        r.append(' ');
11122                    }
11123                    r.append(p.info.name);
11124                }
11125            }
11126            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11127                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11128                if (appOpPkgs != null) {
11129                    appOpPkgs.remove(pkg.packageName);
11130                }
11131            }
11132        }
11133        if (r != null) {
11134            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11135        }
11136
11137        N = pkg.requestedPermissions.size();
11138        r = null;
11139        for (i=0; i<N; i++) {
11140            String perm = pkg.requestedPermissions.get(i);
11141            BasePermission bp = mSettings.mPermissions.get(perm);
11142            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11143                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11144                if (appOpPkgs != null) {
11145                    appOpPkgs.remove(pkg.packageName);
11146                    if (appOpPkgs.isEmpty()) {
11147                        mAppOpPermissionPackages.remove(perm);
11148                    }
11149                }
11150            }
11151        }
11152        if (r != null) {
11153            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11154        }
11155
11156        N = pkg.instrumentation.size();
11157        r = null;
11158        for (i=0; i<N; i++) {
11159            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11160            mInstrumentation.remove(a.getComponentName());
11161            if (DEBUG_REMOVE && chatty) {
11162                if (r == null) {
11163                    r = new StringBuilder(256);
11164                } else {
11165                    r.append(' ');
11166                }
11167                r.append(a.info.name);
11168            }
11169        }
11170        if (r != null) {
11171            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11172        }
11173
11174        r = null;
11175        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11176            // Only system apps can hold shared libraries.
11177            if (pkg.libraryNames != null) {
11178                for (i = 0; i < pkg.libraryNames.size(); i++) {
11179                    String name = pkg.libraryNames.get(i);
11180                    if (removeSharedLibraryLPw(name, 0)) {
11181                        if (DEBUG_REMOVE && chatty) {
11182                            if (r == null) {
11183                                r = new StringBuilder(256);
11184                            } else {
11185                                r.append(' ');
11186                            }
11187                            r.append(name);
11188                        }
11189                    }
11190                }
11191            }
11192        }
11193
11194        r = null;
11195
11196        // Any package can hold static shared libraries.
11197        if (pkg.staticSharedLibName != null) {
11198            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11199                if (DEBUG_REMOVE && chatty) {
11200                    if (r == null) {
11201                        r = new StringBuilder(256);
11202                    } else {
11203                        r.append(' ');
11204                    }
11205                    r.append(pkg.staticSharedLibName);
11206                }
11207            }
11208        }
11209
11210        if (r != null) {
11211            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11212        }
11213    }
11214
11215    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11216        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11217            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11218                return true;
11219            }
11220        }
11221        return false;
11222    }
11223
11224    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11225    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11226    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11227
11228    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11229        // Update the parent permissions
11230        updatePermissionsLPw(pkg.packageName, pkg, flags);
11231        // Update the child permissions
11232        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11233        for (int i = 0; i < childCount; i++) {
11234            PackageParser.Package childPkg = pkg.childPackages.get(i);
11235            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11236        }
11237    }
11238
11239    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11240            int flags) {
11241        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11242        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11243    }
11244
11245    private void updatePermissionsLPw(String changingPkg,
11246            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11247        // Make sure there are no dangling permission trees.
11248        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11249        while (it.hasNext()) {
11250            final BasePermission bp = it.next();
11251            if (bp.packageSetting == null) {
11252                // We may not yet have parsed the package, so just see if
11253                // we still know about its settings.
11254                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11255            }
11256            if (bp.packageSetting == null) {
11257                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11258                        + " from package " + bp.sourcePackage);
11259                it.remove();
11260            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11261                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11262                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11263                            + " from package " + bp.sourcePackage);
11264                    flags |= UPDATE_PERMISSIONS_ALL;
11265                    it.remove();
11266                }
11267            }
11268        }
11269
11270        // Make sure all dynamic permissions have been assigned to a package,
11271        // and make sure there are no dangling permissions.
11272        it = mSettings.mPermissions.values().iterator();
11273        while (it.hasNext()) {
11274            final BasePermission bp = it.next();
11275            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11276                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11277                        + bp.name + " pkg=" + bp.sourcePackage
11278                        + " info=" + bp.pendingInfo);
11279                if (bp.packageSetting == null && bp.pendingInfo != null) {
11280                    final BasePermission tree = findPermissionTreeLP(bp.name);
11281                    if (tree != null && tree.perm != null) {
11282                        bp.packageSetting = tree.packageSetting;
11283                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11284                                new PermissionInfo(bp.pendingInfo));
11285                        bp.perm.info.packageName = tree.perm.info.packageName;
11286                        bp.perm.info.name = bp.name;
11287                        bp.uid = tree.uid;
11288                    }
11289                }
11290            }
11291            if (bp.packageSetting == null) {
11292                // We may not yet have parsed the package, so just see if
11293                // we still know about its settings.
11294                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11295            }
11296            if (bp.packageSetting == null) {
11297                Slog.w(TAG, "Removing dangling permission: " + bp.name
11298                        + " from package " + bp.sourcePackage);
11299                it.remove();
11300            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11301                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11302                    Slog.i(TAG, "Removing old permission: " + bp.name
11303                            + " from package " + bp.sourcePackage);
11304                    flags |= UPDATE_PERMISSIONS_ALL;
11305                    it.remove();
11306                }
11307            }
11308        }
11309
11310        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11311        // Now update the permissions for all packages, in particular
11312        // replace the granted permissions of the system packages.
11313        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11314            for (PackageParser.Package pkg : mPackages.values()) {
11315                if (pkg != pkgInfo) {
11316                    // Only replace for packages on requested volume
11317                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11318                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11319                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11320                    grantPermissionsLPw(pkg, replace, changingPkg);
11321                }
11322            }
11323        }
11324
11325        if (pkgInfo != null) {
11326            // Only replace for packages on requested volume
11327            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11328            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11329                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11330            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11331        }
11332        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11333    }
11334
11335    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11336            String packageOfInterest) {
11337        // IMPORTANT: There are two types of permissions: install and runtime.
11338        // Install time permissions are granted when the app is installed to
11339        // all device users and users added in the future. Runtime permissions
11340        // are granted at runtime explicitly to specific users. Normal and signature
11341        // protected permissions are install time permissions. Dangerous permissions
11342        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11343        // otherwise they are runtime permissions. This function does not manage
11344        // runtime permissions except for the case an app targeting Lollipop MR1
11345        // being upgraded to target a newer SDK, in which case dangerous permissions
11346        // are transformed from install time to runtime ones.
11347
11348        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11349        if (ps == null) {
11350            return;
11351        }
11352
11353        PermissionsState permissionsState = ps.getPermissionsState();
11354        PermissionsState origPermissions = permissionsState;
11355
11356        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11357
11358        boolean runtimePermissionsRevoked = false;
11359        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11360
11361        boolean changedInstallPermission = false;
11362
11363        if (replace) {
11364            ps.installPermissionsFixed = false;
11365            if (!ps.isSharedUser()) {
11366                origPermissions = new PermissionsState(permissionsState);
11367                permissionsState.reset();
11368            } else {
11369                // We need to know only about runtime permission changes since the
11370                // calling code always writes the install permissions state but
11371                // the runtime ones are written only if changed. The only cases of
11372                // changed runtime permissions here are promotion of an install to
11373                // runtime and revocation of a runtime from a shared user.
11374                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11375                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11376                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11377                    runtimePermissionsRevoked = true;
11378                }
11379            }
11380        }
11381
11382        permissionsState.setGlobalGids(mGlobalGids);
11383
11384        final int N = pkg.requestedPermissions.size();
11385        for (int i=0; i<N; i++) {
11386            final String name = pkg.requestedPermissions.get(i);
11387            final BasePermission bp = mSettings.mPermissions.get(name);
11388            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11389                    >= Build.VERSION_CODES.M;
11390
11391            if (DEBUG_INSTALL) {
11392                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11393            }
11394
11395            if (bp == null || bp.packageSetting == null) {
11396                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11397                    Slog.w(TAG, "Unknown permission " + name
11398                            + " in package " + pkg.packageName);
11399                }
11400                continue;
11401            }
11402
11403
11404            // Limit ephemeral apps to ephemeral allowed permissions.
11405            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11406                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11407                        + pkg.packageName);
11408                continue;
11409            }
11410
11411            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
11412                Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
11413                        + pkg.packageName);
11414                continue;
11415            }
11416
11417            final String perm = bp.name;
11418            boolean allowedSig = false;
11419            int grant = GRANT_DENIED;
11420
11421            // Keep track of app op permissions.
11422            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11423                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11424                if (pkgs == null) {
11425                    pkgs = new ArraySet<>();
11426                    mAppOpPermissionPackages.put(bp.name, pkgs);
11427                }
11428                pkgs.add(pkg.packageName);
11429            }
11430
11431            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11432            switch (level) {
11433                case PermissionInfo.PROTECTION_NORMAL: {
11434                    // For all apps normal permissions are install time ones.
11435                    grant = GRANT_INSTALL;
11436                } break;
11437
11438                case PermissionInfo.PROTECTION_DANGEROUS: {
11439                    // If a permission review is required for legacy apps we represent
11440                    // their permissions as always granted runtime ones since we need
11441                    // to keep the review required permission flag per user while an
11442                    // install permission's state is shared across all users.
11443                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11444                        // For legacy apps dangerous permissions are install time ones.
11445                        grant = GRANT_INSTALL;
11446                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11447                        // For legacy apps that became modern, install becomes runtime.
11448                        grant = GRANT_UPGRADE;
11449                    } else if (mPromoteSystemApps
11450                            && isSystemApp(ps)
11451                            && mExistingSystemPackages.contains(ps.name)) {
11452                        // For legacy system apps, install becomes runtime.
11453                        // We cannot check hasInstallPermission() for system apps since those
11454                        // permissions were granted implicitly and not persisted pre-M.
11455                        grant = GRANT_UPGRADE;
11456                    } else {
11457                        // For modern apps keep runtime permissions unchanged.
11458                        grant = GRANT_RUNTIME;
11459                    }
11460                } break;
11461
11462                case PermissionInfo.PROTECTION_SIGNATURE: {
11463                    // For all apps signature permissions are install time ones.
11464                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11465                    if (allowedSig) {
11466                        grant = GRANT_INSTALL;
11467                    }
11468                } break;
11469            }
11470
11471            if (DEBUG_INSTALL) {
11472                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11473            }
11474
11475            if (grant != GRANT_DENIED) {
11476                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11477                    // If this is an existing, non-system package, then
11478                    // we can't add any new permissions to it.
11479                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11480                        // Except...  if this is a permission that was added
11481                        // to the platform (note: need to only do this when
11482                        // updating the platform).
11483                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11484                            grant = GRANT_DENIED;
11485                        }
11486                    }
11487                }
11488
11489                switch (grant) {
11490                    case GRANT_INSTALL: {
11491                        // Revoke this as runtime permission to handle the case of
11492                        // a runtime permission being downgraded to an install one.
11493                        // Also in permission review mode we keep dangerous permissions
11494                        // for legacy apps
11495                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11496                            if (origPermissions.getRuntimePermissionState(
11497                                    bp.name, userId) != null) {
11498                                // Revoke the runtime permission and clear the flags.
11499                                origPermissions.revokeRuntimePermission(bp, userId);
11500                                origPermissions.updatePermissionFlags(bp, userId,
11501                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11502                                // If we revoked a permission permission, we have to write.
11503                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11504                                        changedRuntimePermissionUserIds, userId);
11505                            }
11506                        }
11507                        // Grant an install permission.
11508                        if (permissionsState.grantInstallPermission(bp) !=
11509                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11510                            changedInstallPermission = true;
11511                        }
11512                    } break;
11513
11514                    case GRANT_RUNTIME: {
11515                        // Grant previously granted runtime permissions.
11516                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11517                            PermissionState permissionState = origPermissions
11518                                    .getRuntimePermissionState(bp.name, userId);
11519                            int flags = permissionState != null
11520                                    ? permissionState.getFlags() : 0;
11521                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11522                                // Don't propagate the permission in a permission review mode if
11523                                // the former was revoked, i.e. marked to not propagate on upgrade.
11524                                // Note that in a permission review mode install permissions are
11525                                // represented as constantly granted runtime ones since we need to
11526                                // keep a per user state associated with the permission. Also the
11527                                // revoke on upgrade flag is no longer applicable and is reset.
11528                                final boolean revokeOnUpgrade = (flags & PackageManager
11529                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11530                                if (revokeOnUpgrade) {
11531                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11532                                    // Since we changed the flags, we have to write.
11533                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11534                                            changedRuntimePermissionUserIds, userId);
11535                                }
11536                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11537                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11538                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11539                                        // If we cannot put the permission as it was,
11540                                        // we have to write.
11541                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11542                                                changedRuntimePermissionUserIds, userId);
11543                                    }
11544                                }
11545
11546                                // If the app supports runtime permissions no need for a review.
11547                                if (mPermissionReviewRequired
11548                                        && appSupportsRuntimePermissions
11549                                        && (flags & PackageManager
11550                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11551                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11552                                    // Since we changed the flags, we have to write.
11553                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11554                                            changedRuntimePermissionUserIds, userId);
11555                                }
11556                            } else if (mPermissionReviewRequired
11557                                    && !appSupportsRuntimePermissions) {
11558                                // For legacy apps that need a permission review, every new
11559                                // runtime permission is granted but it is pending a review.
11560                                // We also need to review only platform defined runtime
11561                                // permissions as these are the only ones the platform knows
11562                                // how to disable the API to simulate revocation as legacy
11563                                // apps don't expect to run with revoked permissions.
11564                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11565                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11566                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11567                                        // We changed the flags, hence have to write.
11568                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11569                                                changedRuntimePermissionUserIds, userId);
11570                                    }
11571                                }
11572                                if (permissionsState.grantRuntimePermission(bp, userId)
11573                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11574                                    // We changed the permission, hence have to write.
11575                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11576                                            changedRuntimePermissionUserIds, userId);
11577                                }
11578                            }
11579                            // Propagate the permission flags.
11580                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11581                        }
11582                    } break;
11583
11584                    case GRANT_UPGRADE: {
11585                        // Grant runtime permissions for a previously held install permission.
11586                        PermissionState permissionState = origPermissions
11587                                .getInstallPermissionState(bp.name);
11588                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11589
11590                        if (origPermissions.revokeInstallPermission(bp)
11591                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11592                            // We will be transferring the permission flags, so clear them.
11593                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11594                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11595                            changedInstallPermission = true;
11596                        }
11597
11598                        // If the permission is not to be promoted to runtime we ignore it and
11599                        // also its other flags as they are not applicable to install permissions.
11600                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11601                            for (int userId : currentUserIds) {
11602                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11603                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11604                                    // Transfer the permission flags.
11605                                    permissionsState.updatePermissionFlags(bp, userId,
11606                                            flags, flags);
11607                                    // If we granted the permission, we have to write.
11608                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11609                                            changedRuntimePermissionUserIds, userId);
11610                                }
11611                            }
11612                        }
11613                    } break;
11614
11615                    default: {
11616                        if (packageOfInterest == null
11617                                || packageOfInterest.equals(pkg.packageName)) {
11618                            Slog.w(TAG, "Not granting permission " + perm
11619                                    + " to package " + pkg.packageName
11620                                    + " because it was previously installed without");
11621                        }
11622                    } break;
11623                }
11624            } else {
11625                if (permissionsState.revokeInstallPermission(bp) !=
11626                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11627                    // Also drop the permission flags.
11628                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11629                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11630                    changedInstallPermission = true;
11631                    Slog.i(TAG, "Un-granting permission " + perm
11632                            + " from package " + pkg.packageName
11633                            + " (protectionLevel=" + bp.protectionLevel
11634                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11635                            + ")");
11636                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11637                    // Don't print warning for app op permissions, since it is fine for them
11638                    // not to be granted, there is a UI for the user to decide.
11639                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11640                        Slog.w(TAG, "Not granting permission " + perm
11641                                + " to package " + pkg.packageName
11642                                + " (protectionLevel=" + bp.protectionLevel
11643                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11644                                + ")");
11645                    }
11646                }
11647            }
11648        }
11649
11650        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11651                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11652            // This is the first that we have heard about this package, so the
11653            // permissions we have now selected are fixed until explicitly
11654            // changed.
11655            ps.installPermissionsFixed = true;
11656        }
11657
11658        // Persist the runtime permissions state for users with changes. If permissions
11659        // were revoked because no app in the shared user declares them we have to
11660        // write synchronously to avoid losing runtime permissions state.
11661        for (int userId : changedRuntimePermissionUserIds) {
11662            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11663        }
11664    }
11665
11666    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
11667        boolean allowed = false;
11668        final int NP = PackageParser.NEW_PERMISSIONS.length;
11669        for (int ip=0; ip<NP; ip++) {
11670            final PackageParser.NewPermissionInfo npi
11671                    = PackageParser.NEW_PERMISSIONS[ip];
11672            if (npi.name.equals(perm)
11673                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
11674                allowed = true;
11675                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
11676                        + pkg.packageName);
11677                break;
11678            }
11679        }
11680        return allowed;
11681    }
11682
11683    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
11684            BasePermission bp, PermissionsState origPermissions) {
11685        boolean privilegedPermission = (bp.protectionLevel
11686                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
11687        boolean privappPermissionsDisable =
11688                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
11689        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
11690        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
11691        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
11692                && !platformPackage && platformPermission) {
11693            ArraySet<String> wlPermissions = SystemConfig.getInstance()
11694                    .getPrivAppPermissions(pkg.packageName);
11695            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
11696            if (!whitelisted) {
11697                Slog.w(TAG, "Privileged permission " + perm + " for package "
11698                        + pkg.packageName + " - not in privapp-permissions whitelist");
11699                // Only report violations for apps on system image
11700                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
11701                    if (mPrivappPermissionsViolations == null) {
11702                        mPrivappPermissionsViolations = new ArraySet<>();
11703                    }
11704                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
11705                }
11706                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
11707                    return false;
11708                }
11709            }
11710        }
11711        boolean allowed = (compareSignatures(
11712                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
11713                        == PackageManager.SIGNATURE_MATCH)
11714                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
11715                        == PackageManager.SIGNATURE_MATCH);
11716        if (!allowed && privilegedPermission) {
11717            if (isSystemApp(pkg)) {
11718                // For updated system applications, a system permission
11719                // is granted only if it had been defined by the original application.
11720                if (pkg.isUpdatedSystemApp()) {
11721                    final PackageSetting sysPs = mSettings
11722                            .getDisabledSystemPkgLPr(pkg.packageName);
11723                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
11724                        // If the original was granted this permission, we take
11725                        // that grant decision as read and propagate it to the
11726                        // update.
11727                        if (sysPs.isPrivileged()) {
11728                            allowed = true;
11729                        }
11730                    } else {
11731                        // The system apk may have been updated with an older
11732                        // version of the one on the data partition, but which
11733                        // granted a new system permission that it didn't have
11734                        // before.  In this case we do want to allow the app to
11735                        // now get the new permission if the ancestral apk is
11736                        // privileged to get it.
11737                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
11738                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
11739                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
11740                                    allowed = true;
11741                                    break;
11742                                }
11743                            }
11744                        }
11745                        // Also if a privileged parent package on the system image or any of
11746                        // its children requested a privileged permission, the updated child
11747                        // packages can also get the permission.
11748                        if (pkg.parentPackage != null) {
11749                            final PackageSetting disabledSysParentPs = mSettings
11750                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
11751                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
11752                                    && disabledSysParentPs.isPrivileged()) {
11753                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
11754                                    allowed = true;
11755                                } else if (disabledSysParentPs.pkg.childPackages != null) {
11756                                    final int count = disabledSysParentPs.pkg.childPackages.size();
11757                                    for (int i = 0; i < count; i++) {
11758                                        PackageParser.Package disabledSysChildPkg =
11759                                                disabledSysParentPs.pkg.childPackages.get(i);
11760                                        if (isPackageRequestingPermission(disabledSysChildPkg,
11761                                                perm)) {
11762                                            allowed = true;
11763                                            break;
11764                                        }
11765                                    }
11766                                }
11767                            }
11768                        }
11769                    }
11770                } else {
11771                    allowed = isPrivilegedApp(pkg);
11772                }
11773            }
11774        }
11775        if (!allowed) {
11776            if (!allowed && (bp.protectionLevel
11777                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
11778                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
11779                // If this was a previously normal/dangerous permission that got moved
11780                // to a system permission as part of the runtime permission redesign, then
11781                // we still want to blindly grant it to old apps.
11782                allowed = true;
11783            }
11784            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
11785                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
11786                // If this permission is to be granted to the system installer and
11787                // this app is an installer, then it gets the permission.
11788                allowed = true;
11789            }
11790            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
11791                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
11792                // If this permission is to be granted to the system verifier and
11793                // this app is a verifier, then it gets the permission.
11794                allowed = true;
11795            }
11796            if (!allowed && (bp.protectionLevel
11797                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
11798                    && isSystemApp(pkg)) {
11799                // Any pre-installed system app is allowed to get this permission.
11800                allowed = true;
11801            }
11802            if (!allowed && (bp.protectionLevel
11803                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
11804                // For development permissions, a development permission
11805                // is granted only if it was already granted.
11806                allowed = origPermissions.hasInstallPermission(perm);
11807            }
11808            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
11809                    && pkg.packageName.equals(mSetupWizardPackage)) {
11810                // If this permission is to be granted to the system setup wizard and
11811                // this app is a setup wizard, then it gets the permission.
11812                allowed = true;
11813            }
11814        }
11815        return allowed;
11816    }
11817
11818    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
11819        final int permCount = pkg.requestedPermissions.size();
11820        for (int j = 0; j < permCount; j++) {
11821            String requestedPermission = pkg.requestedPermissions.get(j);
11822            if (permission.equals(requestedPermission)) {
11823                return true;
11824            }
11825        }
11826        return false;
11827    }
11828
11829    final class ActivityIntentResolver
11830            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11831        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11832                boolean defaultOnly, int userId) {
11833            if (!sUserManager.exists(userId)) return null;
11834            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11835            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11836        }
11837
11838        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11839                int userId) {
11840            if (!sUserManager.exists(userId)) return null;
11841            mFlags = flags;
11842            return super.queryIntent(intent, resolvedType,
11843                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11844                    userId);
11845        }
11846
11847        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11848                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11849            if (!sUserManager.exists(userId)) return null;
11850            if (packageActivities == null) {
11851                return null;
11852            }
11853            mFlags = flags;
11854            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11855            final int N = packageActivities.size();
11856            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11857                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11858
11859            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11860            for (int i = 0; i < N; ++i) {
11861                intentFilters = packageActivities.get(i).intents;
11862                if (intentFilters != null && intentFilters.size() > 0) {
11863                    PackageParser.ActivityIntentInfo[] array =
11864                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11865                    intentFilters.toArray(array);
11866                    listCut.add(array);
11867                }
11868            }
11869            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11870        }
11871
11872        /**
11873         * Finds a privileged activity that matches the specified activity names.
11874         */
11875        private PackageParser.Activity findMatchingActivity(
11876                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11877            for (PackageParser.Activity sysActivity : activityList) {
11878                if (sysActivity.info.name.equals(activityInfo.name)) {
11879                    return sysActivity;
11880                }
11881                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11882                    return sysActivity;
11883                }
11884                if (sysActivity.info.targetActivity != null) {
11885                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11886                        return sysActivity;
11887                    }
11888                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11889                        return sysActivity;
11890                    }
11891                }
11892            }
11893            return null;
11894        }
11895
11896        public class IterGenerator<E> {
11897            public Iterator<E> generate(ActivityIntentInfo info) {
11898                return null;
11899            }
11900        }
11901
11902        public class ActionIterGenerator extends IterGenerator<String> {
11903            @Override
11904            public Iterator<String> generate(ActivityIntentInfo info) {
11905                return info.actionsIterator();
11906            }
11907        }
11908
11909        public class CategoriesIterGenerator extends IterGenerator<String> {
11910            @Override
11911            public Iterator<String> generate(ActivityIntentInfo info) {
11912                return info.categoriesIterator();
11913            }
11914        }
11915
11916        public class SchemesIterGenerator extends IterGenerator<String> {
11917            @Override
11918            public Iterator<String> generate(ActivityIntentInfo info) {
11919                return info.schemesIterator();
11920            }
11921        }
11922
11923        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11924            @Override
11925            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11926                return info.authoritiesIterator();
11927            }
11928        }
11929
11930        /**
11931         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11932         * MODIFIED. Do not pass in a list that should not be changed.
11933         */
11934        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11935                IterGenerator<T> generator, Iterator<T> searchIterator) {
11936            // loop through the set of actions; every one must be found in the intent filter
11937            while (searchIterator.hasNext()) {
11938                // we must have at least one filter in the list to consider a match
11939                if (intentList.size() == 0) {
11940                    break;
11941                }
11942
11943                final T searchAction = searchIterator.next();
11944
11945                // loop through the set of intent filters
11946                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11947                while (intentIter.hasNext()) {
11948                    final ActivityIntentInfo intentInfo = intentIter.next();
11949                    boolean selectionFound = false;
11950
11951                    // loop through the intent filter's selection criteria; at least one
11952                    // of them must match the searched criteria
11953                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11954                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11955                        final T intentSelection = intentSelectionIter.next();
11956                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11957                            selectionFound = true;
11958                            break;
11959                        }
11960                    }
11961
11962                    // the selection criteria wasn't found in this filter's set; this filter
11963                    // is not a potential match
11964                    if (!selectionFound) {
11965                        intentIter.remove();
11966                    }
11967                }
11968            }
11969        }
11970
11971        private boolean isProtectedAction(ActivityIntentInfo filter) {
11972            final Iterator<String> actionsIter = filter.actionsIterator();
11973            while (actionsIter != null && actionsIter.hasNext()) {
11974                final String filterAction = actionsIter.next();
11975                if (PROTECTED_ACTIONS.contains(filterAction)) {
11976                    return true;
11977                }
11978            }
11979            return false;
11980        }
11981
11982        /**
11983         * Adjusts the priority of the given intent filter according to policy.
11984         * <p>
11985         * <ul>
11986         * <li>The priority for non privileged applications is capped to '0'</li>
11987         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11988         * <li>The priority for unbundled updates to privileged applications is capped to the
11989         *      priority defined on the system partition</li>
11990         * </ul>
11991         * <p>
11992         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11993         * allowed to obtain any priority on any action.
11994         */
11995        private void adjustPriority(
11996                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11997            // nothing to do; priority is fine as-is
11998            if (intent.getPriority() <= 0) {
11999                return;
12000            }
12001
12002            final ActivityInfo activityInfo = intent.activity.info;
12003            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12004
12005            final boolean privilegedApp =
12006                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12007            if (!privilegedApp) {
12008                // non-privileged applications can never define a priority >0
12009                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
12010                        + " package: " + applicationInfo.packageName
12011                        + " activity: " + intent.activity.className
12012                        + " origPrio: " + intent.getPriority());
12013                intent.setPriority(0);
12014                return;
12015            }
12016
12017            if (systemActivities == null) {
12018                // the system package is not disabled; we're parsing the system partition
12019                if (isProtectedAction(intent)) {
12020                    if (mDeferProtectedFilters) {
12021                        // We can't deal with these just yet. No component should ever obtain a
12022                        // >0 priority for a protected actions, with ONE exception -- the setup
12023                        // wizard. The setup wizard, however, cannot be known until we're able to
12024                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12025                        // until all intent filters have been processed. Chicken, meet egg.
12026                        // Let the filter temporarily have a high priority and rectify the
12027                        // priorities after all system packages have been scanned.
12028                        mProtectedFilters.add(intent);
12029                        if (DEBUG_FILTERS) {
12030                            Slog.i(TAG, "Protected action; save for later;"
12031                                    + " package: " + applicationInfo.packageName
12032                                    + " activity: " + intent.activity.className
12033                                    + " origPrio: " + intent.getPriority());
12034                        }
12035                        return;
12036                    } else {
12037                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12038                            Slog.i(TAG, "No setup wizard;"
12039                                + " All protected intents capped to priority 0");
12040                        }
12041                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12042                            if (DEBUG_FILTERS) {
12043                                Slog.i(TAG, "Found setup wizard;"
12044                                    + " allow priority " + intent.getPriority() + ";"
12045                                    + " package: " + intent.activity.info.packageName
12046                                    + " activity: " + intent.activity.className
12047                                    + " priority: " + intent.getPriority());
12048                            }
12049                            // setup wizard gets whatever it wants
12050                            return;
12051                        }
12052                        Slog.w(TAG, "Protected action; cap priority to 0;"
12053                                + " package: " + intent.activity.info.packageName
12054                                + " activity: " + intent.activity.className
12055                                + " origPrio: " + intent.getPriority());
12056                        intent.setPriority(0);
12057                        return;
12058                    }
12059                }
12060                // privileged apps on the system image get whatever priority they request
12061                return;
12062            }
12063
12064            // privileged app unbundled update ... try to find the same activity
12065            final PackageParser.Activity foundActivity =
12066                    findMatchingActivity(systemActivities, activityInfo);
12067            if (foundActivity == null) {
12068                // this is a new activity; it cannot obtain >0 priority
12069                if (DEBUG_FILTERS) {
12070                    Slog.i(TAG, "New activity; cap priority to 0;"
12071                            + " package: " + applicationInfo.packageName
12072                            + " activity: " + intent.activity.className
12073                            + " origPrio: " + intent.getPriority());
12074                }
12075                intent.setPriority(0);
12076                return;
12077            }
12078
12079            // found activity, now check for filter equivalence
12080
12081            // a shallow copy is enough; we modify the list, not its contents
12082            final List<ActivityIntentInfo> intentListCopy =
12083                    new ArrayList<>(foundActivity.intents);
12084            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12085
12086            // find matching action subsets
12087            final Iterator<String> actionsIterator = intent.actionsIterator();
12088            if (actionsIterator != null) {
12089                getIntentListSubset(
12090                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12091                if (intentListCopy.size() == 0) {
12092                    // no more intents to match; we're not equivalent
12093                    if (DEBUG_FILTERS) {
12094                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12095                                + " package: " + applicationInfo.packageName
12096                                + " activity: " + intent.activity.className
12097                                + " origPrio: " + intent.getPriority());
12098                    }
12099                    intent.setPriority(0);
12100                    return;
12101                }
12102            }
12103
12104            // find matching category subsets
12105            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12106            if (categoriesIterator != null) {
12107                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12108                        categoriesIterator);
12109                if (intentListCopy.size() == 0) {
12110                    // no more intents to match; we're not equivalent
12111                    if (DEBUG_FILTERS) {
12112                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12113                                + " package: " + applicationInfo.packageName
12114                                + " activity: " + intent.activity.className
12115                                + " origPrio: " + intent.getPriority());
12116                    }
12117                    intent.setPriority(0);
12118                    return;
12119                }
12120            }
12121
12122            // find matching schemes subsets
12123            final Iterator<String> schemesIterator = intent.schemesIterator();
12124            if (schemesIterator != null) {
12125                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12126                        schemesIterator);
12127                if (intentListCopy.size() == 0) {
12128                    // no more intents to match; we're not equivalent
12129                    if (DEBUG_FILTERS) {
12130                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12131                                + " package: " + applicationInfo.packageName
12132                                + " activity: " + intent.activity.className
12133                                + " origPrio: " + intent.getPriority());
12134                    }
12135                    intent.setPriority(0);
12136                    return;
12137                }
12138            }
12139
12140            // find matching authorities subsets
12141            final Iterator<IntentFilter.AuthorityEntry>
12142                    authoritiesIterator = intent.authoritiesIterator();
12143            if (authoritiesIterator != null) {
12144                getIntentListSubset(intentListCopy,
12145                        new AuthoritiesIterGenerator(),
12146                        authoritiesIterator);
12147                if (intentListCopy.size() == 0) {
12148                    // no more intents to match; we're not equivalent
12149                    if (DEBUG_FILTERS) {
12150                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12151                                + " package: " + applicationInfo.packageName
12152                                + " activity: " + intent.activity.className
12153                                + " origPrio: " + intent.getPriority());
12154                    }
12155                    intent.setPriority(0);
12156                    return;
12157                }
12158            }
12159
12160            // we found matching filter(s); app gets the max priority of all intents
12161            int cappedPriority = 0;
12162            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12163                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12164            }
12165            if (intent.getPriority() > cappedPriority) {
12166                if (DEBUG_FILTERS) {
12167                    Slog.i(TAG, "Found matching filter(s);"
12168                            + " cap priority to " + cappedPriority + ";"
12169                            + " package: " + applicationInfo.packageName
12170                            + " activity: " + intent.activity.className
12171                            + " origPrio: " + intent.getPriority());
12172                }
12173                intent.setPriority(cappedPriority);
12174                return;
12175            }
12176            // all this for nothing; the requested priority was <= what was on the system
12177        }
12178
12179        public final void addActivity(PackageParser.Activity a, String type) {
12180            mActivities.put(a.getComponentName(), a);
12181            if (DEBUG_SHOW_INFO)
12182                Log.v(
12183                TAG, "  " + type + " " +
12184                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12185            if (DEBUG_SHOW_INFO)
12186                Log.v(TAG, "    Class=" + a.info.name);
12187            final int NI = a.intents.size();
12188            for (int j=0; j<NI; j++) {
12189                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12190                if ("activity".equals(type)) {
12191                    final PackageSetting ps =
12192                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12193                    final List<PackageParser.Activity> systemActivities =
12194                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12195                    adjustPriority(systemActivities, intent);
12196                }
12197                if (DEBUG_SHOW_INFO) {
12198                    Log.v(TAG, "    IntentFilter:");
12199                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12200                }
12201                if (!intent.debugCheck()) {
12202                    Log.w(TAG, "==> For Activity " + a.info.name);
12203                }
12204                addFilter(intent);
12205            }
12206        }
12207
12208        public final void removeActivity(PackageParser.Activity a, String type) {
12209            mActivities.remove(a.getComponentName());
12210            if (DEBUG_SHOW_INFO) {
12211                Log.v(TAG, "  " + type + " "
12212                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12213                                : a.info.name) + ":");
12214                Log.v(TAG, "    Class=" + a.info.name);
12215            }
12216            final int NI = a.intents.size();
12217            for (int j=0; j<NI; j++) {
12218                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12219                if (DEBUG_SHOW_INFO) {
12220                    Log.v(TAG, "    IntentFilter:");
12221                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12222                }
12223                removeFilter(intent);
12224            }
12225        }
12226
12227        @Override
12228        protected boolean allowFilterResult(
12229                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12230            ActivityInfo filterAi = filter.activity.info;
12231            for (int i=dest.size()-1; i>=0; i--) {
12232                ActivityInfo destAi = dest.get(i).activityInfo;
12233                if (destAi.name == filterAi.name
12234                        && destAi.packageName == filterAi.packageName) {
12235                    return false;
12236                }
12237            }
12238            return true;
12239        }
12240
12241        @Override
12242        protected ActivityIntentInfo[] newArray(int size) {
12243            return new ActivityIntentInfo[size];
12244        }
12245
12246        @Override
12247        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12248            if (!sUserManager.exists(userId)) return true;
12249            PackageParser.Package p = filter.activity.owner;
12250            if (p != null) {
12251                PackageSetting ps = (PackageSetting)p.mExtras;
12252                if (ps != null) {
12253                    // System apps are never considered stopped for purposes of
12254                    // filtering, because there may be no way for the user to
12255                    // actually re-launch them.
12256                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12257                            && ps.getStopped(userId);
12258                }
12259            }
12260            return false;
12261        }
12262
12263        @Override
12264        protected boolean isPackageForFilter(String packageName,
12265                PackageParser.ActivityIntentInfo info) {
12266            return packageName.equals(info.activity.owner.packageName);
12267        }
12268
12269        @Override
12270        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12271                int match, int userId) {
12272            if (!sUserManager.exists(userId)) return null;
12273            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12274                return null;
12275            }
12276            final PackageParser.Activity activity = info.activity;
12277            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12278            if (ps == null) {
12279                return null;
12280            }
12281            final PackageUserState userState = ps.readUserState(userId);
12282            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
12283                    userState, userId);
12284            if (ai == null) {
12285                return null;
12286            }
12287            final boolean matchVisibleToInstantApp =
12288                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12289            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12290            // throw out filters that aren't visible to ephemeral apps
12291            if (matchVisibleToInstantApp
12292                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12293                return null;
12294            }
12295            // throw out ephemeral filters if we're not explicitly requesting them
12296            if (!isInstantApp && userState.instantApp) {
12297                return null;
12298            }
12299            // throw out instant app filters if updates are available; will trigger
12300            // instant app resolution
12301            if (userState.instantApp && ps.isUpdateAvailable()) {
12302                return null;
12303            }
12304            final ResolveInfo res = new ResolveInfo();
12305            res.activityInfo = ai;
12306            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12307                res.filter = info;
12308            }
12309            if (info != null) {
12310                res.handleAllWebDataURI = info.handleAllWebDataURI();
12311            }
12312            res.priority = info.getPriority();
12313            res.preferredOrder = activity.owner.mPreferredOrder;
12314            //System.out.println("Result: " + res.activityInfo.className +
12315            //                   " = " + res.priority);
12316            res.match = match;
12317            res.isDefault = info.hasDefault;
12318            res.labelRes = info.labelRes;
12319            res.nonLocalizedLabel = info.nonLocalizedLabel;
12320            if (userNeedsBadging(userId)) {
12321                res.noResourceId = true;
12322            } else {
12323                res.icon = info.icon;
12324            }
12325            res.iconResourceId = info.icon;
12326            res.system = res.activityInfo.applicationInfo.isSystemApp();
12327            res.instantAppAvailable = userState.instantApp;
12328            return res;
12329        }
12330
12331        @Override
12332        protected void sortResults(List<ResolveInfo> results) {
12333            Collections.sort(results, mResolvePrioritySorter);
12334        }
12335
12336        @Override
12337        protected void dumpFilter(PrintWriter out, String prefix,
12338                PackageParser.ActivityIntentInfo filter) {
12339            out.print(prefix); out.print(
12340                    Integer.toHexString(System.identityHashCode(filter.activity)));
12341                    out.print(' ');
12342                    filter.activity.printComponentShortName(out);
12343                    out.print(" filter ");
12344                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12345        }
12346
12347        @Override
12348        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12349            return filter.activity;
12350        }
12351
12352        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12353            PackageParser.Activity activity = (PackageParser.Activity)label;
12354            out.print(prefix); out.print(
12355                    Integer.toHexString(System.identityHashCode(activity)));
12356                    out.print(' ');
12357                    activity.printComponentShortName(out);
12358            if (count > 1) {
12359                out.print(" ("); out.print(count); out.print(" filters)");
12360            }
12361            out.println();
12362        }
12363
12364        // Keys are String (activity class name), values are Activity.
12365        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12366                = new ArrayMap<ComponentName, PackageParser.Activity>();
12367        private int mFlags;
12368    }
12369
12370    private final class ServiceIntentResolver
12371            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12372        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12373                boolean defaultOnly, int userId) {
12374            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12375            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12376        }
12377
12378        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12379                int userId) {
12380            if (!sUserManager.exists(userId)) return null;
12381            mFlags = flags;
12382            return super.queryIntent(intent, resolvedType,
12383                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12384                    userId);
12385        }
12386
12387        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12388                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12389            if (!sUserManager.exists(userId)) return null;
12390            if (packageServices == null) {
12391                return null;
12392            }
12393            mFlags = flags;
12394            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12395            final int N = packageServices.size();
12396            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12397                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12398
12399            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12400            for (int i = 0; i < N; ++i) {
12401                intentFilters = packageServices.get(i).intents;
12402                if (intentFilters != null && intentFilters.size() > 0) {
12403                    PackageParser.ServiceIntentInfo[] array =
12404                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12405                    intentFilters.toArray(array);
12406                    listCut.add(array);
12407                }
12408            }
12409            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12410        }
12411
12412        public final void addService(PackageParser.Service s) {
12413            mServices.put(s.getComponentName(), s);
12414            if (DEBUG_SHOW_INFO) {
12415                Log.v(TAG, "  "
12416                        + (s.info.nonLocalizedLabel != null
12417                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12418                Log.v(TAG, "    Class=" + s.info.name);
12419            }
12420            final int NI = s.intents.size();
12421            int j;
12422            for (j=0; j<NI; j++) {
12423                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12424                if (DEBUG_SHOW_INFO) {
12425                    Log.v(TAG, "    IntentFilter:");
12426                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12427                }
12428                if (!intent.debugCheck()) {
12429                    Log.w(TAG, "==> For Service " + s.info.name);
12430                }
12431                addFilter(intent);
12432            }
12433        }
12434
12435        public final void removeService(PackageParser.Service s) {
12436            mServices.remove(s.getComponentName());
12437            if (DEBUG_SHOW_INFO) {
12438                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12439                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12440                Log.v(TAG, "    Class=" + s.info.name);
12441            }
12442            final int NI = s.intents.size();
12443            int j;
12444            for (j=0; j<NI; j++) {
12445                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12446                if (DEBUG_SHOW_INFO) {
12447                    Log.v(TAG, "    IntentFilter:");
12448                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12449                }
12450                removeFilter(intent);
12451            }
12452        }
12453
12454        @Override
12455        protected boolean allowFilterResult(
12456                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12457            ServiceInfo filterSi = filter.service.info;
12458            for (int i=dest.size()-1; i>=0; i--) {
12459                ServiceInfo destAi = dest.get(i).serviceInfo;
12460                if (destAi.name == filterSi.name
12461                        && destAi.packageName == filterSi.packageName) {
12462                    return false;
12463                }
12464            }
12465            return true;
12466        }
12467
12468        @Override
12469        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12470            return new PackageParser.ServiceIntentInfo[size];
12471        }
12472
12473        @Override
12474        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12475            if (!sUserManager.exists(userId)) return true;
12476            PackageParser.Package p = filter.service.owner;
12477            if (p != null) {
12478                PackageSetting ps = (PackageSetting)p.mExtras;
12479                if (ps != null) {
12480                    // System apps are never considered stopped for purposes of
12481                    // filtering, because there may be no way for the user to
12482                    // actually re-launch them.
12483                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12484                            && ps.getStopped(userId);
12485                }
12486            }
12487            return false;
12488        }
12489
12490        @Override
12491        protected boolean isPackageForFilter(String packageName,
12492                PackageParser.ServiceIntentInfo info) {
12493            return packageName.equals(info.service.owner.packageName);
12494        }
12495
12496        @Override
12497        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12498                int match, int userId) {
12499            if (!sUserManager.exists(userId)) return null;
12500            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12501            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12502                return null;
12503            }
12504            final PackageParser.Service service = info.service;
12505            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12506            if (ps == null) {
12507                return null;
12508            }
12509            final PackageUserState userState = ps.readUserState(userId);
12510            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12511                    userState, userId);
12512            if (si == null) {
12513                return null;
12514            }
12515            final boolean matchVisibleToInstantApp =
12516                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12517            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12518            // throw out filters that aren't visible to ephemeral apps
12519            if (matchVisibleToInstantApp
12520                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12521                return null;
12522            }
12523            // throw out ephemeral filters if we're not explicitly requesting them
12524            if (!isInstantApp && userState.instantApp) {
12525                return null;
12526            }
12527            // throw out instant app filters if updates are available; will trigger
12528            // instant app resolution
12529            if (userState.instantApp && ps.isUpdateAvailable()) {
12530                return null;
12531            }
12532            final ResolveInfo res = new ResolveInfo();
12533            res.serviceInfo = si;
12534            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12535                res.filter = filter;
12536            }
12537            res.priority = info.getPriority();
12538            res.preferredOrder = service.owner.mPreferredOrder;
12539            res.match = match;
12540            res.isDefault = info.hasDefault;
12541            res.labelRes = info.labelRes;
12542            res.nonLocalizedLabel = info.nonLocalizedLabel;
12543            res.icon = info.icon;
12544            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12545            return res;
12546        }
12547
12548        @Override
12549        protected void sortResults(List<ResolveInfo> results) {
12550            Collections.sort(results, mResolvePrioritySorter);
12551        }
12552
12553        @Override
12554        protected void dumpFilter(PrintWriter out, String prefix,
12555                PackageParser.ServiceIntentInfo filter) {
12556            out.print(prefix); out.print(
12557                    Integer.toHexString(System.identityHashCode(filter.service)));
12558                    out.print(' ');
12559                    filter.service.printComponentShortName(out);
12560                    out.print(" filter ");
12561                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12562        }
12563
12564        @Override
12565        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12566            return filter.service;
12567        }
12568
12569        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12570            PackageParser.Service service = (PackageParser.Service)label;
12571            out.print(prefix); out.print(
12572                    Integer.toHexString(System.identityHashCode(service)));
12573                    out.print(' ');
12574                    service.printComponentShortName(out);
12575            if (count > 1) {
12576                out.print(" ("); out.print(count); out.print(" filters)");
12577            }
12578            out.println();
12579        }
12580
12581//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12582//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12583//            final List<ResolveInfo> retList = Lists.newArrayList();
12584//            while (i.hasNext()) {
12585//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12586//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12587//                    retList.add(resolveInfo);
12588//                }
12589//            }
12590//            return retList;
12591//        }
12592
12593        // Keys are String (activity class name), values are Activity.
12594        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12595                = new ArrayMap<ComponentName, PackageParser.Service>();
12596        private int mFlags;
12597    }
12598
12599    private final class ProviderIntentResolver
12600            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12601        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12602                boolean defaultOnly, int userId) {
12603            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12604            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12605        }
12606
12607        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12608                int userId) {
12609            if (!sUserManager.exists(userId))
12610                return null;
12611            mFlags = flags;
12612            return super.queryIntent(intent, resolvedType,
12613                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12614                    userId);
12615        }
12616
12617        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12618                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12619            if (!sUserManager.exists(userId))
12620                return null;
12621            if (packageProviders == null) {
12622                return null;
12623            }
12624            mFlags = flags;
12625            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12626            final int N = packageProviders.size();
12627            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12628                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12629
12630            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12631            for (int i = 0; i < N; ++i) {
12632                intentFilters = packageProviders.get(i).intents;
12633                if (intentFilters != null && intentFilters.size() > 0) {
12634                    PackageParser.ProviderIntentInfo[] array =
12635                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12636                    intentFilters.toArray(array);
12637                    listCut.add(array);
12638                }
12639            }
12640            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12641        }
12642
12643        public final void addProvider(PackageParser.Provider p) {
12644            if (mProviders.containsKey(p.getComponentName())) {
12645                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12646                return;
12647            }
12648
12649            mProviders.put(p.getComponentName(), p);
12650            if (DEBUG_SHOW_INFO) {
12651                Log.v(TAG, "  "
12652                        + (p.info.nonLocalizedLabel != null
12653                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12654                Log.v(TAG, "    Class=" + p.info.name);
12655            }
12656            final int NI = p.intents.size();
12657            int j;
12658            for (j = 0; j < NI; j++) {
12659                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12660                if (DEBUG_SHOW_INFO) {
12661                    Log.v(TAG, "    IntentFilter:");
12662                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12663                }
12664                if (!intent.debugCheck()) {
12665                    Log.w(TAG, "==> For Provider " + p.info.name);
12666                }
12667                addFilter(intent);
12668            }
12669        }
12670
12671        public final void removeProvider(PackageParser.Provider p) {
12672            mProviders.remove(p.getComponentName());
12673            if (DEBUG_SHOW_INFO) {
12674                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12675                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12676                Log.v(TAG, "    Class=" + p.info.name);
12677            }
12678            final int NI = p.intents.size();
12679            int j;
12680            for (j = 0; j < NI; j++) {
12681                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12682                if (DEBUG_SHOW_INFO) {
12683                    Log.v(TAG, "    IntentFilter:");
12684                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12685                }
12686                removeFilter(intent);
12687            }
12688        }
12689
12690        @Override
12691        protected boolean allowFilterResult(
12692                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12693            ProviderInfo filterPi = filter.provider.info;
12694            for (int i = dest.size() - 1; i >= 0; i--) {
12695                ProviderInfo destPi = dest.get(i).providerInfo;
12696                if (destPi.name == filterPi.name
12697                        && destPi.packageName == filterPi.packageName) {
12698                    return false;
12699                }
12700            }
12701            return true;
12702        }
12703
12704        @Override
12705        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12706            return new PackageParser.ProviderIntentInfo[size];
12707        }
12708
12709        @Override
12710        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12711            if (!sUserManager.exists(userId))
12712                return true;
12713            PackageParser.Package p = filter.provider.owner;
12714            if (p != null) {
12715                PackageSetting ps = (PackageSetting) p.mExtras;
12716                if (ps != null) {
12717                    // System apps are never considered stopped for purposes of
12718                    // filtering, because there may be no way for the user to
12719                    // actually re-launch them.
12720                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12721                            && ps.getStopped(userId);
12722                }
12723            }
12724            return false;
12725        }
12726
12727        @Override
12728        protected boolean isPackageForFilter(String packageName,
12729                PackageParser.ProviderIntentInfo info) {
12730            return packageName.equals(info.provider.owner.packageName);
12731        }
12732
12733        @Override
12734        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12735                int match, int userId) {
12736            if (!sUserManager.exists(userId))
12737                return null;
12738            final PackageParser.ProviderIntentInfo info = filter;
12739            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12740                return null;
12741            }
12742            final PackageParser.Provider provider = info.provider;
12743            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12744            if (ps == null) {
12745                return null;
12746            }
12747            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12748                    ps.readUserState(userId), userId);
12749            if (pi == null) {
12750                return null;
12751            }
12752            final ResolveInfo res = new ResolveInfo();
12753            res.providerInfo = pi;
12754            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12755                res.filter = filter;
12756            }
12757            res.priority = info.getPriority();
12758            res.preferredOrder = provider.owner.mPreferredOrder;
12759            res.match = match;
12760            res.isDefault = info.hasDefault;
12761            res.labelRes = info.labelRes;
12762            res.nonLocalizedLabel = info.nonLocalizedLabel;
12763            res.icon = info.icon;
12764            res.system = res.providerInfo.applicationInfo.isSystemApp();
12765            return res;
12766        }
12767
12768        @Override
12769        protected void sortResults(List<ResolveInfo> results) {
12770            Collections.sort(results, mResolvePrioritySorter);
12771        }
12772
12773        @Override
12774        protected void dumpFilter(PrintWriter out, String prefix,
12775                PackageParser.ProviderIntentInfo filter) {
12776            out.print(prefix);
12777            out.print(
12778                    Integer.toHexString(System.identityHashCode(filter.provider)));
12779            out.print(' ');
12780            filter.provider.printComponentShortName(out);
12781            out.print(" filter ");
12782            out.println(Integer.toHexString(System.identityHashCode(filter)));
12783        }
12784
12785        @Override
12786        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12787            return filter.provider;
12788        }
12789
12790        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12791            PackageParser.Provider provider = (PackageParser.Provider)label;
12792            out.print(prefix); out.print(
12793                    Integer.toHexString(System.identityHashCode(provider)));
12794                    out.print(' ');
12795                    provider.printComponentShortName(out);
12796            if (count > 1) {
12797                out.print(" ("); out.print(count); out.print(" filters)");
12798            }
12799            out.println();
12800        }
12801
12802        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12803                = new ArrayMap<ComponentName, PackageParser.Provider>();
12804        private int mFlags;
12805    }
12806
12807    static final class EphemeralIntentResolver
12808            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
12809        /**
12810         * The result that has the highest defined order. Ordering applies on a
12811         * per-package basis. Mapping is from package name to Pair of order and
12812         * EphemeralResolveInfo.
12813         * <p>
12814         * NOTE: This is implemented as a field variable for convenience and efficiency.
12815         * By having a field variable, we're able to track filter ordering as soon as
12816         * a non-zero order is defined. Otherwise, multiple loops across the result set
12817         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12818         * this needs to be contained entirely within {@link #filterResults}.
12819         */
12820        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
12821
12822        @Override
12823        protected AuxiliaryResolveInfo[] newArray(int size) {
12824            return new AuxiliaryResolveInfo[size];
12825        }
12826
12827        @Override
12828        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
12829            return true;
12830        }
12831
12832        @Override
12833        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
12834                int userId) {
12835            if (!sUserManager.exists(userId)) {
12836                return null;
12837            }
12838            final String packageName = responseObj.resolveInfo.getPackageName();
12839            final Integer order = responseObj.getOrder();
12840            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
12841                    mOrderResult.get(packageName);
12842            // ordering is enabled and this item's order isn't high enough
12843            if (lastOrderResult != null && lastOrderResult.first >= order) {
12844                return null;
12845            }
12846            final InstantAppResolveInfo res = responseObj.resolveInfo;
12847            if (order > 0) {
12848                // non-zero order, enable ordering
12849                mOrderResult.put(packageName, new Pair<>(order, res));
12850            }
12851            return responseObj;
12852        }
12853
12854        @Override
12855        protected void filterResults(List<AuxiliaryResolveInfo> results) {
12856            // only do work if ordering is enabled [most of the time it won't be]
12857            if (mOrderResult.size() == 0) {
12858                return;
12859            }
12860            int resultSize = results.size();
12861            for (int i = 0; i < resultSize; i++) {
12862                final InstantAppResolveInfo info = results.get(i).resolveInfo;
12863                final String packageName = info.getPackageName();
12864                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
12865                if (savedInfo == null) {
12866                    // package doesn't having ordering
12867                    continue;
12868                }
12869                if (savedInfo.second == info) {
12870                    // circled back to the highest ordered item; remove from order list
12871                    mOrderResult.remove(savedInfo);
12872                    if (mOrderResult.size() == 0) {
12873                        // no more ordered items
12874                        break;
12875                    }
12876                    continue;
12877                }
12878                // item has a worse order, remove it from the result list
12879                results.remove(i);
12880                resultSize--;
12881                i--;
12882            }
12883        }
12884    }
12885
12886    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12887            new Comparator<ResolveInfo>() {
12888        public int compare(ResolveInfo r1, ResolveInfo r2) {
12889            int v1 = r1.priority;
12890            int v2 = r2.priority;
12891            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12892            if (v1 != v2) {
12893                return (v1 > v2) ? -1 : 1;
12894            }
12895            v1 = r1.preferredOrder;
12896            v2 = r2.preferredOrder;
12897            if (v1 != v2) {
12898                return (v1 > v2) ? -1 : 1;
12899            }
12900            if (r1.isDefault != r2.isDefault) {
12901                return r1.isDefault ? -1 : 1;
12902            }
12903            v1 = r1.match;
12904            v2 = r2.match;
12905            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12906            if (v1 != v2) {
12907                return (v1 > v2) ? -1 : 1;
12908            }
12909            if (r1.system != r2.system) {
12910                return r1.system ? -1 : 1;
12911            }
12912            if (r1.activityInfo != null) {
12913                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12914            }
12915            if (r1.serviceInfo != null) {
12916                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12917            }
12918            if (r1.providerInfo != null) {
12919                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12920            }
12921            return 0;
12922        }
12923    };
12924
12925    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12926            new Comparator<ProviderInfo>() {
12927        public int compare(ProviderInfo p1, ProviderInfo p2) {
12928            final int v1 = p1.initOrder;
12929            final int v2 = p2.initOrder;
12930            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12931        }
12932    };
12933
12934    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12935            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12936            final int[] userIds) {
12937        mHandler.post(new Runnable() {
12938            @Override
12939            public void run() {
12940                try {
12941                    final IActivityManager am = ActivityManager.getService();
12942                    if (am == null) return;
12943                    final int[] resolvedUserIds;
12944                    if (userIds == null) {
12945                        resolvedUserIds = am.getRunningUserIds();
12946                    } else {
12947                        resolvedUserIds = userIds;
12948                    }
12949                    for (int id : resolvedUserIds) {
12950                        final Intent intent = new Intent(action,
12951                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12952                        if (extras != null) {
12953                            intent.putExtras(extras);
12954                        }
12955                        if (targetPkg != null) {
12956                            intent.setPackage(targetPkg);
12957                        }
12958                        // Modify the UID when posting to other users
12959                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12960                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12961                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12962                            intent.putExtra(Intent.EXTRA_UID, uid);
12963                        }
12964                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12965                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12966                        if (DEBUG_BROADCASTS) {
12967                            RuntimeException here = new RuntimeException("here");
12968                            here.fillInStackTrace();
12969                            Slog.d(TAG, "Sending to user " + id + ": "
12970                                    + intent.toShortString(false, true, false, false)
12971                                    + " " + intent.getExtras(), here);
12972                        }
12973                        am.broadcastIntent(null, intent, null, finishedReceiver,
12974                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12975                                null, finishedReceiver != null, false, id);
12976                    }
12977                } catch (RemoteException ex) {
12978                }
12979            }
12980        });
12981    }
12982
12983    /**
12984     * Check if the external storage media is available. This is true if there
12985     * is a mounted external storage medium or if the external storage is
12986     * emulated.
12987     */
12988    private boolean isExternalMediaAvailable() {
12989        return mMediaMounted || Environment.isExternalStorageEmulated();
12990    }
12991
12992    @Override
12993    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12994        // writer
12995        synchronized (mPackages) {
12996            if (!isExternalMediaAvailable()) {
12997                // If the external storage is no longer mounted at this point,
12998                // the caller may not have been able to delete all of this
12999                // packages files and can not delete any more.  Bail.
13000                return null;
13001            }
13002            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13003            if (lastPackage != null) {
13004                pkgs.remove(lastPackage);
13005            }
13006            if (pkgs.size() > 0) {
13007                return pkgs.get(0);
13008            }
13009        }
13010        return null;
13011    }
13012
13013    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13014        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13015                userId, andCode ? 1 : 0, packageName);
13016        if (mSystemReady) {
13017            msg.sendToTarget();
13018        } else {
13019            if (mPostSystemReadyMessages == null) {
13020                mPostSystemReadyMessages = new ArrayList<>();
13021            }
13022            mPostSystemReadyMessages.add(msg);
13023        }
13024    }
13025
13026    void startCleaningPackages() {
13027        // reader
13028        if (!isExternalMediaAvailable()) {
13029            return;
13030        }
13031        synchronized (mPackages) {
13032            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13033                return;
13034            }
13035        }
13036        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13037        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13038        IActivityManager am = ActivityManager.getService();
13039        if (am != null) {
13040            try {
13041                am.startService(null, intent, null, -1, null, false, mContext.getOpPackageName(),
13042                        UserHandle.USER_SYSTEM);
13043            } catch (RemoteException e) {
13044            }
13045        }
13046    }
13047
13048    @Override
13049    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
13050            int installFlags, String installerPackageName, int userId) {
13051        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
13052
13053        final int callingUid = Binder.getCallingUid();
13054        enforceCrossUserPermission(callingUid, userId,
13055                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
13056
13057        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13058            try {
13059                if (observer != null) {
13060                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
13061                }
13062            } catch (RemoteException re) {
13063            }
13064            return;
13065        }
13066
13067        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
13068            installFlags |= PackageManager.INSTALL_FROM_ADB;
13069
13070        } else {
13071            // Caller holds INSTALL_PACKAGES permission, so we're less strict
13072            // about installerPackageName.
13073
13074            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
13075            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
13076        }
13077
13078        UserHandle user;
13079        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
13080            user = UserHandle.ALL;
13081        } else {
13082            user = new UserHandle(userId);
13083        }
13084
13085        // Only system components can circumvent runtime permissions when installing.
13086        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
13087                && mContext.checkCallingOrSelfPermission(Manifest.permission
13088                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
13089            throw new SecurityException("You need the "
13090                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
13091                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
13092        }
13093
13094        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
13095                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13096            throw new IllegalArgumentException(
13097                    "New installs into ASEC containers no longer supported");
13098        }
13099
13100        final File originFile = new File(originPath);
13101        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
13102
13103        final Message msg = mHandler.obtainMessage(INIT_COPY);
13104        final VerificationInfo verificationInfo = new VerificationInfo(
13105                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
13106        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
13107                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
13108                null /*packageAbiOverride*/, null /*grantedPermissions*/,
13109                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
13110        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
13111        msg.obj = params;
13112
13113        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
13114                System.identityHashCode(msg.obj));
13115        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13116                System.identityHashCode(msg.obj));
13117
13118        mHandler.sendMessage(msg);
13119    }
13120
13121
13122    /**
13123     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13124     * it is acting on behalf on an enterprise or the user).
13125     *
13126     * Note that the ordering of the conditionals in this method is important. The checks we perform
13127     * are as follows, in this order:
13128     *
13129     * 1) If the install is being performed by a system app, we can trust the app to have set the
13130     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13131     *    what it is.
13132     * 2) If the install is being performed by a device or profile owner app, the install reason
13133     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13134     *    set the install reason correctly. If the app targets an older SDK version where install
13135     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13136     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13137     * 3) In all other cases, the install is being performed by a regular app that is neither part
13138     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13139     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13140     *    set to enterprise policy and if so, change it to unknown instead.
13141     */
13142    private int fixUpInstallReason(String installerPackageName, int installerUid,
13143            int installReason) {
13144        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13145                == PERMISSION_GRANTED) {
13146            // If the install is being performed by a system app, we trust that app to have set the
13147            // install reason correctly.
13148            return installReason;
13149        }
13150
13151        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13152            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13153        if (dpm != null) {
13154            ComponentName owner = null;
13155            try {
13156                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13157                if (owner == null) {
13158                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13159                }
13160            } catch (RemoteException e) {
13161            }
13162            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13163                // If the install is being performed by a device or profile owner, the install
13164                // reason should be enterprise policy.
13165                return PackageManager.INSTALL_REASON_POLICY;
13166            }
13167        }
13168
13169        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13170            // If the install is being performed by a regular app (i.e. neither system app nor
13171            // device or profile owner), we have no reason to believe that the app is acting on
13172            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13173            // change it to unknown instead.
13174            return PackageManager.INSTALL_REASON_UNKNOWN;
13175        }
13176
13177        // If the install is being performed by a regular app and the install reason was set to any
13178        // value but enterprise policy, leave the install reason unchanged.
13179        return installReason;
13180    }
13181
13182    void installStage(String packageName, File stagedDir, String stagedCid,
13183            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13184            String installerPackageName, int installerUid, UserHandle user,
13185            Certificate[][] certificates) {
13186        if (DEBUG_EPHEMERAL) {
13187            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13188                Slog.d(TAG, "Ephemeral install of " + packageName);
13189            }
13190        }
13191        final VerificationInfo verificationInfo = new VerificationInfo(
13192                sessionParams.originatingUri, sessionParams.referrerUri,
13193                sessionParams.originatingUid, installerUid);
13194
13195        final OriginInfo origin;
13196        if (stagedDir != null) {
13197            origin = OriginInfo.fromStagedFile(stagedDir);
13198        } else {
13199            origin = OriginInfo.fromStagedContainer(stagedCid);
13200        }
13201
13202        final Message msg = mHandler.obtainMessage(INIT_COPY);
13203        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13204                sessionParams.installReason);
13205        final InstallParams params = new InstallParams(origin, null, observer,
13206                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13207                verificationInfo, user, sessionParams.abiOverride,
13208                sessionParams.grantedRuntimePermissions, certificates, installReason);
13209        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13210        msg.obj = params;
13211
13212        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13213                System.identityHashCode(msg.obj));
13214        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13215                System.identityHashCode(msg.obj));
13216
13217        mHandler.sendMessage(msg);
13218    }
13219
13220    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13221            int userId) {
13222        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13223        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13224    }
13225
13226    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
13227            int appId, int... userIds) {
13228        if (ArrayUtils.isEmpty(userIds)) {
13229            return;
13230        }
13231        Bundle extras = new Bundle(1);
13232        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13233        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13234
13235        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13236                packageName, extras, 0, null, null, userIds);
13237        if (isSystem) {
13238            mHandler.post(() -> {
13239                        for (int userId : userIds) {
13240                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13241                        }
13242                    }
13243            );
13244        }
13245    }
13246
13247    /**
13248     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13249     * automatically without needing an explicit launch.
13250     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13251     */
13252    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13253        // If user is not running, the app didn't miss any broadcast
13254        if (!mUserManagerInternal.isUserRunning(userId)) {
13255            return;
13256        }
13257        final IActivityManager am = ActivityManager.getService();
13258        try {
13259            // Deliver LOCKED_BOOT_COMPLETED first
13260            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13261                    .setPackage(packageName);
13262            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13263            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13264                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13265
13266            // Deliver BOOT_COMPLETED only if user is unlocked
13267            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13268                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13269                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13270                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13271            }
13272        } catch (RemoteException e) {
13273            throw e.rethrowFromSystemServer();
13274        }
13275    }
13276
13277    @Override
13278    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13279            int userId) {
13280        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13281        PackageSetting pkgSetting;
13282        final int uid = Binder.getCallingUid();
13283        enforceCrossUserPermission(uid, userId,
13284                true /* requireFullPermission */, true /* checkShell */,
13285                "setApplicationHiddenSetting for user " + userId);
13286
13287        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13288            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13289            return false;
13290        }
13291
13292        long callingId = Binder.clearCallingIdentity();
13293        try {
13294            boolean sendAdded = false;
13295            boolean sendRemoved = false;
13296            // writer
13297            synchronized (mPackages) {
13298                pkgSetting = mSettings.mPackages.get(packageName);
13299                if (pkgSetting == null) {
13300                    return false;
13301                }
13302                // Do not allow "android" is being disabled
13303                if ("android".equals(packageName)) {
13304                    Slog.w(TAG, "Cannot hide package: android");
13305                    return false;
13306                }
13307                // Cannot hide static shared libs as they are considered
13308                // a part of the using app (emulating static linking). Also
13309                // static libs are installed always on internal storage.
13310                PackageParser.Package pkg = mPackages.get(packageName);
13311                if (pkg != null && pkg.staticSharedLibName != null) {
13312                    Slog.w(TAG, "Cannot hide package: " + packageName
13313                            + " providing static shared library: "
13314                            + pkg.staticSharedLibName);
13315                    return false;
13316                }
13317                // Only allow protected packages to hide themselves.
13318                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13319                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13320                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13321                    return false;
13322                }
13323
13324                if (pkgSetting.getHidden(userId) != hidden) {
13325                    pkgSetting.setHidden(hidden, userId);
13326                    mSettings.writePackageRestrictionsLPr(userId);
13327                    if (hidden) {
13328                        sendRemoved = true;
13329                    } else {
13330                        sendAdded = true;
13331                    }
13332                }
13333            }
13334            if (sendAdded) {
13335                sendPackageAddedForUser(packageName, pkgSetting, userId);
13336                return true;
13337            }
13338            if (sendRemoved) {
13339                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13340                        "hiding pkg");
13341                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13342                return true;
13343            }
13344        } finally {
13345            Binder.restoreCallingIdentity(callingId);
13346        }
13347        return false;
13348    }
13349
13350    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13351            int userId) {
13352        final PackageRemovedInfo info = new PackageRemovedInfo();
13353        info.removedPackage = packageName;
13354        info.removedUsers = new int[] {userId};
13355        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13356        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13357    }
13358
13359    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13360        if (pkgList.length > 0) {
13361            Bundle extras = new Bundle(1);
13362            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13363
13364            sendPackageBroadcast(
13365                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13366                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13367                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13368                    new int[] {userId});
13369        }
13370    }
13371
13372    /**
13373     * Returns true if application is not found or there was an error. Otherwise it returns
13374     * the hidden state of the package for the given user.
13375     */
13376    @Override
13377    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13378        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13379        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13380                true /* requireFullPermission */, false /* checkShell */,
13381                "getApplicationHidden for user " + userId);
13382        PackageSetting pkgSetting;
13383        long callingId = Binder.clearCallingIdentity();
13384        try {
13385            // writer
13386            synchronized (mPackages) {
13387                pkgSetting = mSettings.mPackages.get(packageName);
13388                if (pkgSetting == null) {
13389                    return true;
13390                }
13391                return pkgSetting.getHidden(userId);
13392            }
13393        } finally {
13394            Binder.restoreCallingIdentity(callingId);
13395        }
13396    }
13397
13398    /**
13399     * @hide
13400     */
13401    @Override
13402    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13403            int installReason) {
13404        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13405                null);
13406        PackageSetting pkgSetting;
13407        final int uid = Binder.getCallingUid();
13408        enforceCrossUserPermission(uid, userId,
13409                true /* requireFullPermission */, true /* checkShell */,
13410                "installExistingPackage for user " + userId);
13411        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13412            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13413        }
13414
13415        long callingId = Binder.clearCallingIdentity();
13416        try {
13417            boolean installed = false;
13418            final boolean instantApp =
13419                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13420            final boolean fullApp =
13421                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13422
13423            // writer
13424            synchronized (mPackages) {
13425                pkgSetting = mSettings.mPackages.get(packageName);
13426                if (pkgSetting == null) {
13427                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13428                }
13429                if (!pkgSetting.getInstalled(userId)) {
13430                    pkgSetting.setInstalled(true, userId);
13431                    pkgSetting.setHidden(false, userId);
13432                    pkgSetting.setInstallReason(installReason, userId);
13433                    mSettings.writePackageRestrictionsLPr(userId);
13434                    mSettings.writeKernelMappingLPr(pkgSetting);
13435                    installed = true;
13436                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13437                    // upgrade app from instant to full; we don't allow app downgrade
13438                    installed = true;
13439                }
13440                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13441            }
13442
13443            if (installed) {
13444                if (pkgSetting.pkg != null) {
13445                    synchronized (mInstallLock) {
13446                        // We don't need to freeze for a brand new install
13447                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13448                    }
13449                }
13450                sendPackageAddedForUser(packageName, pkgSetting, userId);
13451                synchronized (mPackages) {
13452                    updateSequenceNumberLP(packageName, new int[]{ userId });
13453                }
13454            }
13455        } finally {
13456            Binder.restoreCallingIdentity(callingId);
13457        }
13458
13459        return PackageManager.INSTALL_SUCCEEDED;
13460    }
13461
13462    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13463            boolean instantApp, boolean fullApp) {
13464        // no state specified; do nothing
13465        if (!instantApp && !fullApp) {
13466            return;
13467        }
13468        if (userId != UserHandle.USER_ALL) {
13469            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13470                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13471            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13472                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13473            }
13474        } else {
13475            for (int currentUserId : sUserManager.getUserIds()) {
13476                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13477                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13478                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13479                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13480                }
13481            }
13482        }
13483    }
13484
13485    boolean isUserRestricted(int userId, String restrictionKey) {
13486        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13487        if (restrictions.getBoolean(restrictionKey, false)) {
13488            Log.w(TAG, "User is restricted: " + restrictionKey);
13489            return true;
13490        }
13491        return false;
13492    }
13493
13494    @Override
13495    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13496            int userId) {
13497        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13498        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13499                true /* requireFullPermission */, true /* checkShell */,
13500                "setPackagesSuspended for user " + userId);
13501
13502        if (ArrayUtils.isEmpty(packageNames)) {
13503            return packageNames;
13504        }
13505
13506        // List of package names for whom the suspended state has changed.
13507        List<String> changedPackages = new ArrayList<>(packageNames.length);
13508        // List of package names for whom the suspended state is not set as requested in this
13509        // method.
13510        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13511        long callingId = Binder.clearCallingIdentity();
13512        try {
13513            for (int i = 0; i < packageNames.length; i++) {
13514                String packageName = packageNames[i];
13515                boolean changed = false;
13516                final int appId;
13517                synchronized (mPackages) {
13518                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13519                    if (pkgSetting == null) {
13520                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13521                                + "\". Skipping suspending/un-suspending.");
13522                        unactionedPackages.add(packageName);
13523                        continue;
13524                    }
13525                    appId = pkgSetting.appId;
13526                    if (pkgSetting.getSuspended(userId) != suspended) {
13527                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13528                            unactionedPackages.add(packageName);
13529                            continue;
13530                        }
13531                        pkgSetting.setSuspended(suspended, userId);
13532                        mSettings.writePackageRestrictionsLPr(userId);
13533                        changed = true;
13534                        changedPackages.add(packageName);
13535                    }
13536                }
13537
13538                if (changed && suspended) {
13539                    killApplication(packageName, UserHandle.getUid(userId, appId),
13540                            "suspending package");
13541                }
13542            }
13543        } finally {
13544            Binder.restoreCallingIdentity(callingId);
13545        }
13546
13547        if (!changedPackages.isEmpty()) {
13548            sendPackagesSuspendedForUser(changedPackages.toArray(
13549                    new String[changedPackages.size()]), userId, suspended);
13550        }
13551
13552        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13553    }
13554
13555    @Override
13556    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13557        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13558                true /* requireFullPermission */, false /* checkShell */,
13559                "isPackageSuspendedForUser for user " + userId);
13560        synchronized (mPackages) {
13561            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13562            if (pkgSetting == null) {
13563                throw new IllegalArgumentException("Unknown target package: " + packageName);
13564            }
13565            return pkgSetting.getSuspended(userId);
13566        }
13567    }
13568
13569    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13570        if (isPackageDeviceAdmin(packageName, userId)) {
13571            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13572                    + "\": has an active device admin");
13573            return false;
13574        }
13575
13576        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13577        if (packageName.equals(activeLauncherPackageName)) {
13578            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13579                    + "\": contains the active launcher");
13580            return false;
13581        }
13582
13583        if (packageName.equals(mRequiredInstallerPackage)) {
13584            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13585                    + "\": required for package installation");
13586            return false;
13587        }
13588
13589        if (packageName.equals(mRequiredUninstallerPackage)) {
13590            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13591                    + "\": required for package uninstallation");
13592            return false;
13593        }
13594
13595        if (packageName.equals(mRequiredVerifierPackage)) {
13596            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13597                    + "\": required for package verification");
13598            return false;
13599        }
13600
13601        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13602            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13603                    + "\": is the default dialer");
13604            return false;
13605        }
13606
13607        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13608            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13609                    + "\": protected package");
13610            return false;
13611        }
13612
13613        // Cannot suspend static shared libs as they are considered
13614        // a part of the using app (emulating static linking). Also
13615        // static libs are installed always on internal storage.
13616        PackageParser.Package pkg = mPackages.get(packageName);
13617        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13618            Slog.w(TAG, "Cannot suspend package: " + packageName
13619                    + " providing static shared library: "
13620                    + pkg.staticSharedLibName);
13621            return false;
13622        }
13623
13624        return true;
13625    }
13626
13627    private String getActiveLauncherPackageName(int userId) {
13628        Intent intent = new Intent(Intent.ACTION_MAIN);
13629        intent.addCategory(Intent.CATEGORY_HOME);
13630        ResolveInfo resolveInfo = resolveIntent(
13631                intent,
13632                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13633                PackageManager.MATCH_DEFAULT_ONLY,
13634                userId);
13635
13636        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13637    }
13638
13639    private String getDefaultDialerPackageName(int userId) {
13640        synchronized (mPackages) {
13641            return mSettings.getDefaultDialerPackageNameLPw(userId);
13642        }
13643    }
13644
13645    @Override
13646    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13647        mContext.enforceCallingOrSelfPermission(
13648                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13649                "Only package verification agents can verify applications");
13650
13651        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13652        final PackageVerificationResponse response = new PackageVerificationResponse(
13653                verificationCode, Binder.getCallingUid());
13654        msg.arg1 = id;
13655        msg.obj = response;
13656        mHandler.sendMessage(msg);
13657    }
13658
13659    @Override
13660    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13661            long millisecondsToDelay) {
13662        mContext.enforceCallingOrSelfPermission(
13663                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13664                "Only package verification agents can extend verification timeouts");
13665
13666        final PackageVerificationState state = mPendingVerification.get(id);
13667        final PackageVerificationResponse response = new PackageVerificationResponse(
13668                verificationCodeAtTimeout, Binder.getCallingUid());
13669
13670        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13671            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13672        }
13673        if (millisecondsToDelay < 0) {
13674            millisecondsToDelay = 0;
13675        }
13676        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13677                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13678            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13679        }
13680
13681        if ((state != null) && !state.timeoutExtended()) {
13682            state.extendTimeout();
13683
13684            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13685            msg.arg1 = id;
13686            msg.obj = response;
13687            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13688        }
13689    }
13690
13691    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13692            int verificationCode, UserHandle user) {
13693        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13694        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13695        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13696        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13697        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13698
13699        mContext.sendBroadcastAsUser(intent, user,
13700                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13701    }
13702
13703    private ComponentName matchComponentForVerifier(String packageName,
13704            List<ResolveInfo> receivers) {
13705        ActivityInfo targetReceiver = null;
13706
13707        final int NR = receivers.size();
13708        for (int i = 0; i < NR; i++) {
13709            final ResolveInfo info = receivers.get(i);
13710            if (info.activityInfo == null) {
13711                continue;
13712            }
13713
13714            if (packageName.equals(info.activityInfo.packageName)) {
13715                targetReceiver = info.activityInfo;
13716                break;
13717            }
13718        }
13719
13720        if (targetReceiver == null) {
13721            return null;
13722        }
13723
13724        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13725    }
13726
13727    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13728            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13729        if (pkgInfo.verifiers.length == 0) {
13730            return null;
13731        }
13732
13733        final int N = pkgInfo.verifiers.length;
13734        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13735        for (int i = 0; i < N; i++) {
13736            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13737
13738            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13739                    receivers);
13740            if (comp == null) {
13741                continue;
13742            }
13743
13744            final int verifierUid = getUidForVerifier(verifierInfo);
13745            if (verifierUid == -1) {
13746                continue;
13747            }
13748
13749            if (DEBUG_VERIFY) {
13750                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13751                        + " with the correct signature");
13752            }
13753            sufficientVerifiers.add(comp);
13754            verificationState.addSufficientVerifier(verifierUid);
13755        }
13756
13757        return sufficientVerifiers;
13758    }
13759
13760    private int getUidForVerifier(VerifierInfo verifierInfo) {
13761        synchronized (mPackages) {
13762            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13763            if (pkg == null) {
13764                return -1;
13765            } else if (pkg.mSignatures.length != 1) {
13766                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13767                        + " has more than one signature; ignoring");
13768                return -1;
13769            }
13770
13771            /*
13772             * If the public key of the package's signature does not match
13773             * our expected public key, then this is a different package and
13774             * we should skip.
13775             */
13776
13777            final byte[] expectedPublicKey;
13778            try {
13779                final Signature verifierSig = pkg.mSignatures[0];
13780                final PublicKey publicKey = verifierSig.getPublicKey();
13781                expectedPublicKey = publicKey.getEncoded();
13782            } catch (CertificateException e) {
13783                return -1;
13784            }
13785
13786            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13787
13788            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13789                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13790                        + " does not have the expected public key; ignoring");
13791                return -1;
13792            }
13793
13794            return pkg.applicationInfo.uid;
13795        }
13796    }
13797
13798    @Override
13799    public void finishPackageInstall(int token, boolean didLaunch) {
13800        enforceSystemOrRoot("Only the system is allowed to finish installs");
13801
13802        if (DEBUG_INSTALL) {
13803            Slog.v(TAG, "BM finishing package install for " + token);
13804        }
13805        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13806
13807        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13808        mHandler.sendMessage(msg);
13809    }
13810
13811    /**
13812     * Get the verification agent timeout.
13813     *
13814     * @return verification timeout in milliseconds
13815     */
13816    private long getVerificationTimeout() {
13817        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13818                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13819                DEFAULT_VERIFICATION_TIMEOUT);
13820    }
13821
13822    /**
13823     * Get the default verification agent response code.
13824     *
13825     * @return default verification response code
13826     */
13827    private int getDefaultVerificationResponse() {
13828        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13829                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13830                DEFAULT_VERIFICATION_RESPONSE);
13831    }
13832
13833    /**
13834     * Check whether or not package verification has been enabled.
13835     *
13836     * @return true if verification should be performed
13837     */
13838    private boolean isVerificationEnabled(int userId, int installFlags) {
13839        if (!DEFAULT_VERIFY_ENABLE) {
13840            return false;
13841        }
13842
13843        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13844
13845        // Check if installing from ADB
13846        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13847            // Do not run verification in a test harness environment
13848            if (ActivityManager.isRunningInTestHarness()) {
13849                return false;
13850            }
13851            if (ensureVerifyAppsEnabled) {
13852                return true;
13853            }
13854            // Check if the developer does not want package verification for ADB installs
13855            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13856                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13857                return false;
13858            }
13859        }
13860
13861        if (ensureVerifyAppsEnabled) {
13862            return true;
13863        }
13864
13865        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13866                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13867    }
13868
13869    @Override
13870    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13871            throws RemoteException {
13872        mContext.enforceCallingOrSelfPermission(
13873                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13874                "Only intentfilter verification agents can verify applications");
13875
13876        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13877        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13878                Binder.getCallingUid(), verificationCode, failedDomains);
13879        msg.arg1 = id;
13880        msg.obj = response;
13881        mHandler.sendMessage(msg);
13882    }
13883
13884    @Override
13885    public int getIntentVerificationStatus(String packageName, int userId) {
13886        synchronized (mPackages) {
13887            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13888        }
13889    }
13890
13891    @Override
13892    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13893        mContext.enforceCallingOrSelfPermission(
13894                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13895
13896        boolean result = false;
13897        synchronized (mPackages) {
13898            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13899        }
13900        if (result) {
13901            scheduleWritePackageRestrictionsLocked(userId);
13902        }
13903        return result;
13904    }
13905
13906    @Override
13907    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13908            String packageName) {
13909        synchronized (mPackages) {
13910            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13911        }
13912    }
13913
13914    @Override
13915    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13916        if (TextUtils.isEmpty(packageName)) {
13917            return ParceledListSlice.emptyList();
13918        }
13919        synchronized (mPackages) {
13920            PackageParser.Package pkg = mPackages.get(packageName);
13921            if (pkg == null || pkg.activities == null) {
13922                return ParceledListSlice.emptyList();
13923            }
13924            final int count = pkg.activities.size();
13925            ArrayList<IntentFilter> result = new ArrayList<>();
13926            for (int n=0; n<count; n++) {
13927                PackageParser.Activity activity = pkg.activities.get(n);
13928                if (activity.intents != null && activity.intents.size() > 0) {
13929                    result.addAll(activity.intents);
13930                }
13931            }
13932            return new ParceledListSlice<>(result);
13933        }
13934    }
13935
13936    @Override
13937    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13938        mContext.enforceCallingOrSelfPermission(
13939                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13940
13941        synchronized (mPackages) {
13942            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13943            if (packageName != null) {
13944                result |= updateIntentVerificationStatus(packageName,
13945                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
13946                        userId);
13947                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
13948                        packageName, userId);
13949            }
13950            return result;
13951        }
13952    }
13953
13954    @Override
13955    public String getDefaultBrowserPackageName(int userId) {
13956        synchronized (mPackages) {
13957            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13958        }
13959    }
13960
13961    /**
13962     * Get the "allow unknown sources" setting.
13963     *
13964     * @return the current "allow unknown sources" setting
13965     */
13966    private int getUnknownSourcesSettings() {
13967        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13968                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13969                -1);
13970    }
13971
13972    @Override
13973    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13974        final int uid = Binder.getCallingUid();
13975        // writer
13976        synchronized (mPackages) {
13977            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13978            if (targetPackageSetting == null) {
13979                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13980            }
13981
13982            PackageSetting installerPackageSetting;
13983            if (installerPackageName != null) {
13984                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13985                if (installerPackageSetting == null) {
13986                    throw new IllegalArgumentException("Unknown installer package: "
13987                            + installerPackageName);
13988                }
13989            } else {
13990                installerPackageSetting = null;
13991            }
13992
13993            Signature[] callerSignature;
13994            Object obj = mSettings.getUserIdLPr(uid);
13995            if (obj != null) {
13996                if (obj instanceof SharedUserSetting) {
13997                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13998                } else if (obj instanceof PackageSetting) {
13999                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
14000                } else {
14001                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
14002                }
14003            } else {
14004                throw new SecurityException("Unknown calling UID: " + uid);
14005            }
14006
14007            // Verify: can't set installerPackageName to a package that is
14008            // not signed with the same cert as the caller.
14009            if (installerPackageSetting != null) {
14010                if (compareSignatures(callerSignature,
14011                        installerPackageSetting.signatures.mSignatures)
14012                        != PackageManager.SIGNATURE_MATCH) {
14013                    throw new SecurityException(
14014                            "Caller does not have same cert as new installer package "
14015                            + installerPackageName);
14016                }
14017            }
14018
14019            // Verify: if target already has an installer package, it must
14020            // be signed with the same cert as the caller.
14021            if (targetPackageSetting.installerPackageName != null) {
14022                PackageSetting setting = mSettings.mPackages.get(
14023                        targetPackageSetting.installerPackageName);
14024                // If the currently set package isn't valid, then it's always
14025                // okay to change it.
14026                if (setting != null) {
14027                    if (compareSignatures(callerSignature,
14028                            setting.signatures.mSignatures)
14029                            != PackageManager.SIGNATURE_MATCH) {
14030                        throw new SecurityException(
14031                                "Caller does not have same cert as old installer package "
14032                                + targetPackageSetting.installerPackageName);
14033                    }
14034                }
14035            }
14036
14037            // Okay!
14038            targetPackageSetting.installerPackageName = installerPackageName;
14039            if (installerPackageName != null) {
14040                mSettings.mInstallerPackages.add(installerPackageName);
14041            }
14042            scheduleWriteSettingsLocked();
14043        }
14044    }
14045
14046    @Override
14047    public void setApplicationCategoryHint(String packageName, int categoryHint,
14048            String callerPackageName) {
14049        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14050                callerPackageName);
14051        synchronized (mPackages) {
14052            PackageSetting ps = mSettings.mPackages.get(packageName);
14053            if (ps == null) {
14054                throw new IllegalArgumentException("Unknown target package " + packageName);
14055            }
14056
14057            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14058                throw new IllegalArgumentException("Calling package " + callerPackageName
14059                        + " is not installer for " + packageName);
14060            }
14061
14062            if (ps.categoryHint != categoryHint) {
14063                ps.categoryHint = categoryHint;
14064                scheduleWriteSettingsLocked();
14065            }
14066        }
14067    }
14068
14069    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14070        // Queue up an async operation since the package installation may take a little while.
14071        mHandler.post(new Runnable() {
14072            public void run() {
14073                mHandler.removeCallbacks(this);
14074                 // Result object to be returned
14075                PackageInstalledInfo res = new PackageInstalledInfo();
14076                res.setReturnCode(currentStatus);
14077                res.uid = -1;
14078                res.pkg = null;
14079                res.removedInfo = null;
14080                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14081                    args.doPreInstall(res.returnCode);
14082                    synchronized (mInstallLock) {
14083                        installPackageTracedLI(args, res);
14084                    }
14085                    args.doPostInstall(res.returnCode, res.uid);
14086                }
14087
14088                // A restore should be performed at this point if (a) the install
14089                // succeeded, (b) the operation is not an update, and (c) the new
14090                // package has not opted out of backup participation.
14091                final boolean update = res.removedInfo != null
14092                        && res.removedInfo.removedPackage != null;
14093                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14094                boolean doRestore = !update
14095                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14096
14097                // Set up the post-install work request bookkeeping.  This will be used
14098                // and cleaned up by the post-install event handling regardless of whether
14099                // there's a restore pass performed.  Token values are >= 1.
14100                int token;
14101                if (mNextInstallToken < 0) mNextInstallToken = 1;
14102                token = mNextInstallToken++;
14103
14104                PostInstallData data = new PostInstallData(args, res);
14105                mRunningInstalls.put(token, data);
14106                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14107
14108                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14109                    // Pass responsibility to the Backup Manager.  It will perform a
14110                    // restore if appropriate, then pass responsibility back to the
14111                    // Package Manager to run the post-install observer callbacks
14112                    // and broadcasts.
14113                    IBackupManager bm = IBackupManager.Stub.asInterface(
14114                            ServiceManager.getService(Context.BACKUP_SERVICE));
14115                    if (bm != null) {
14116                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14117                                + " to BM for possible restore");
14118                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14119                        try {
14120                            // TODO: http://b/22388012
14121                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14122                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14123                            } else {
14124                                doRestore = false;
14125                            }
14126                        } catch (RemoteException e) {
14127                            // can't happen; the backup manager is local
14128                        } catch (Exception e) {
14129                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14130                            doRestore = false;
14131                        }
14132                    } else {
14133                        Slog.e(TAG, "Backup Manager not found!");
14134                        doRestore = false;
14135                    }
14136                }
14137
14138                if (!doRestore) {
14139                    // No restore possible, or the Backup Manager was mysteriously not
14140                    // available -- just fire the post-install work request directly.
14141                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14142
14143                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14144
14145                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14146                    mHandler.sendMessage(msg);
14147                }
14148            }
14149        });
14150    }
14151
14152    /**
14153     * Callback from PackageSettings whenever an app is first transitioned out of the
14154     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14155     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14156     * here whether the app is the target of an ongoing install, and only send the
14157     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14158     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14159     * handling.
14160     */
14161    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14162        // Serialize this with the rest of the install-process message chain.  In the
14163        // restore-at-install case, this Runnable will necessarily run before the
14164        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14165        // are coherent.  In the non-restore case, the app has already completed install
14166        // and been launched through some other means, so it is not in a problematic
14167        // state for observers to see the FIRST_LAUNCH signal.
14168        mHandler.post(new Runnable() {
14169            @Override
14170            public void run() {
14171                for (int i = 0; i < mRunningInstalls.size(); i++) {
14172                    final PostInstallData data = mRunningInstalls.valueAt(i);
14173                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14174                        continue;
14175                    }
14176                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14177                        // right package; but is it for the right user?
14178                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14179                            if (userId == data.res.newUsers[uIndex]) {
14180                                if (DEBUG_BACKUP) {
14181                                    Slog.i(TAG, "Package " + pkgName
14182                                            + " being restored so deferring FIRST_LAUNCH");
14183                                }
14184                                return;
14185                            }
14186                        }
14187                    }
14188                }
14189                // didn't find it, so not being restored
14190                if (DEBUG_BACKUP) {
14191                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14192                }
14193                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14194            }
14195        });
14196    }
14197
14198    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14199        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14200                installerPkg, null, userIds);
14201    }
14202
14203    private abstract class HandlerParams {
14204        private static final int MAX_RETRIES = 4;
14205
14206        /**
14207         * Number of times startCopy() has been attempted and had a non-fatal
14208         * error.
14209         */
14210        private int mRetries = 0;
14211
14212        /** User handle for the user requesting the information or installation. */
14213        private final UserHandle mUser;
14214        String traceMethod;
14215        int traceCookie;
14216
14217        HandlerParams(UserHandle user) {
14218            mUser = user;
14219        }
14220
14221        UserHandle getUser() {
14222            return mUser;
14223        }
14224
14225        HandlerParams setTraceMethod(String traceMethod) {
14226            this.traceMethod = traceMethod;
14227            return this;
14228        }
14229
14230        HandlerParams setTraceCookie(int traceCookie) {
14231            this.traceCookie = traceCookie;
14232            return this;
14233        }
14234
14235        final boolean startCopy() {
14236            boolean res;
14237            try {
14238                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14239
14240                if (++mRetries > MAX_RETRIES) {
14241                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14242                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14243                    handleServiceError();
14244                    return false;
14245                } else {
14246                    handleStartCopy();
14247                    res = true;
14248                }
14249            } catch (RemoteException e) {
14250                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14251                mHandler.sendEmptyMessage(MCS_RECONNECT);
14252                res = false;
14253            }
14254            handleReturnCode();
14255            return res;
14256        }
14257
14258        final void serviceError() {
14259            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14260            handleServiceError();
14261            handleReturnCode();
14262        }
14263
14264        abstract void handleStartCopy() throws RemoteException;
14265        abstract void handleServiceError();
14266        abstract void handleReturnCode();
14267    }
14268
14269    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14270        for (File path : paths) {
14271            try {
14272                mcs.clearDirectory(path.getAbsolutePath());
14273            } catch (RemoteException e) {
14274            }
14275        }
14276    }
14277
14278    static class OriginInfo {
14279        /**
14280         * Location where install is coming from, before it has been
14281         * copied/renamed into place. This could be a single monolithic APK
14282         * file, or a cluster directory. This location may be untrusted.
14283         */
14284        final File file;
14285        final String cid;
14286
14287        /**
14288         * Flag indicating that {@link #file} or {@link #cid} has already been
14289         * staged, meaning downstream users don't need to defensively copy the
14290         * contents.
14291         */
14292        final boolean staged;
14293
14294        /**
14295         * Flag indicating that {@link #file} or {@link #cid} is an already
14296         * installed app that is being moved.
14297         */
14298        final boolean existing;
14299
14300        final String resolvedPath;
14301        final File resolvedFile;
14302
14303        static OriginInfo fromNothing() {
14304            return new OriginInfo(null, null, false, false);
14305        }
14306
14307        static OriginInfo fromUntrustedFile(File file) {
14308            return new OriginInfo(file, null, false, false);
14309        }
14310
14311        static OriginInfo fromExistingFile(File file) {
14312            return new OriginInfo(file, null, false, true);
14313        }
14314
14315        static OriginInfo fromStagedFile(File file) {
14316            return new OriginInfo(file, null, true, false);
14317        }
14318
14319        static OriginInfo fromStagedContainer(String cid) {
14320            return new OriginInfo(null, cid, true, false);
14321        }
14322
14323        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14324            this.file = file;
14325            this.cid = cid;
14326            this.staged = staged;
14327            this.existing = existing;
14328
14329            if (cid != null) {
14330                resolvedPath = PackageHelper.getSdDir(cid);
14331                resolvedFile = new File(resolvedPath);
14332            } else if (file != null) {
14333                resolvedPath = file.getAbsolutePath();
14334                resolvedFile = file;
14335            } else {
14336                resolvedPath = null;
14337                resolvedFile = null;
14338            }
14339        }
14340    }
14341
14342    static class MoveInfo {
14343        final int moveId;
14344        final String fromUuid;
14345        final String toUuid;
14346        final String packageName;
14347        final String dataAppName;
14348        final int appId;
14349        final String seinfo;
14350        final int targetSdkVersion;
14351
14352        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14353                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14354            this.moveId = moveId;
14355            this.fromUuid = fromUuid;
14356            this.toUuid = toUuid;
14357            this.packageName = packageName;
14358            this.dataAppName = dataAppName;
14359            this.appId = appId;
14360            this.seinfo = seinfo;
14361            this.targetSdkVersion = targetSdkVersion;
14362        }
14363    }
14364
14365    static class VerificationInfo {
14366        /** A constant used to indicate that a uid value is not present. */
14367        public static final int NO_UID = -1;
14368
14369        /** URI referencing where the package was downloaded from. */
14370        final Uri originatingUri;
14371
14372        /** HTTP referrer URI associated with the originatingURI. */
14373        final Uri referrer;
14374
14375        /** UID of the application that the install request originated from. */
14376        final int originatingUid;
14377
14378        /** UID of application requesting the install */
14379        final int installerUid;
14380
14381        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14382            this.originatingUri = originatingUri;
14383            this.referrer = referrer;
14384            this.originatingUid = originatingUid;
14385            this.installerUid = installerUid;
14386        }
14387    }
14388
14389    class InstallParams extends HandlerParams {
14390        final OriginInfo origin;
14391        final MoveInfo move;
14392        final IPackageInstallObserver2 observer;
14393        int installFlags;
14394        final String installerPackageName;
14395        final String volumeUuid;
14396        private InstallArgs mArgs;
14397        private int mRet;
14398        final String packageAbiOverride;
14399        final String[] grantedRuntimePermissions;
14400        final VerificationInfo verificationInfo;
14401        final Certificate[][] certificates;
14402        final int installReason;
14403
14404        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14405                int installFlags, String installerPackageName, String volumeUuid,
14406                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14407                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14408            super(user);
14409            this.origin = origin;
14410            this.move = move;
14411            this.observer = observer;
14412            this.installFlags = installFlags;
14413            this.installerPackageName = installerPackageName;
14414            this.volumeUuid = volumeUuid;
14415            this.verificationInfo = verificationInfo;
14416            this.packageAbiOverride = packageAbiOverride;
14417            this.grantedRuntimePermissions = grantedPermissions;
14418            this.certificates = certificates;
14419            this.installReason = installReason;
14420        }
14421
14422        @Override
14423        public String toString() {
14424            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14425                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14426        }
14427
14428        private int installLocationPolicy(PackageInfoLite pkgLite) {
14429            String packageName = pkgLite.packageName;
14430            int installLocation = pkgLite.installLocation;
14431            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14432            // reader
14433            synchronized (mPackages) {
14434                // Currently installed package which the new package is attempting to replace or
14435                // null if no such package is installed.
14436                PackageParser.Package installedPkg = mPackages.get(packageName);
14437                // Package which currently owns the data which the new package will own if installed.
14438                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14439                // will be null whereas dataOwnerPkg will contain information about the package
14440                // which was uninstalled while keeping its data.
14441                PackageParser.Package dataOwnerPkg = installedPkg;
14442                if (dataOwnerPkg  == null) {
14443                    PackageSetting ps = mSettings.mPackages.get(packageName);
14444                    if (ps != null) {
14445                        dataOwnerPkg = ps.pkg;
14446                    }
14447                }
14448
14449                if (dataOwnerPkg != null) {
14450                    // If installed, the package will get access to data left on the device by its
14451                    // predecessor. As a security measure, this is permited only if this is not a
14452                    // version downgrade or if the predecessor package is marked as debuggable and
14453                    // a downgrade is explicitly requested.
14454                    //
14455                    // On debuggable platform builds, downgrades are permitted even for
14456                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14457                    // not offer security guarantees and thus it's OK to disable some security
14458                    // mechanisms to make debugging/testing easier on those builds. However, even on
14459                    // debuggable builds downgrades of packages are permitted only if requested via
14460                    // installFlags. This is because we aim to keep the behavior of debuggable
14461                    // platform builds as close as possible to the behavior of non-debuggable
14462                    // platform builds.
14463                    final boolean downgradeRequested =
14464                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14465                    final boolean packageDebuggable =
14466                                (dataOwnerPkg.applicationInfo.flags
14467                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14468                    final boolean downgradePermitted =
14469                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14470                    if (!downgradePermitted) {
14471                        try {
14472                            checkDowngrade(dataOwnerPkg, pkgLite);
14473                        } catch (PackageManagerException e) {
14474                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14475                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14476                        }
14477                    }
14478                }
14479
14480                if (installedPkg != null) {
14481                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14482                        // Check for updated system application.
14483                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14484                            if (onSd) {
14485                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14486                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14487                            }
14488                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14489                        } else {
14490                            if (onSd) {
14491                                // Install flag overrides everything.
14492                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14493                            }
14494                            // If current upgrade specifies particular preference
14495                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14496                                // Application explicitly specified internal.
14497                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14498                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14499                                // App explictly prefers external. Let policy decide
14500                            } else {
14501                                // Prefer previous location
14502                                if (isExternal(installedPkg)) {
14503                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14504                                }
14505                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14506                            }
14507                        }
14508                    } else {
14509                        // Invalid install. Return error code
14510                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14511                    }
14512                }
14513            }
14514            // All the special cases have been taken care of.
14515            // Return result based on recommended install location.
14516            if (onSd) {
14517                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14518            }
14519            return pkgLite.recommendedInstallLocation;
14520        }
14521
14522        /*
14523         * Invoke remote method to get package information and install
14524         * location values. Override install location based on default
14525         * policy if needed and then create install arguments based
14526         * on the install location.
14527         */
14528        public void handleStartCopy() throws RemoteException {
14529            int ret = PackageManager.INSTALL_SUCCEEDED;
14530
14531            // If we're already staged, we've firmly committed to an install location
14532            if (origin.staged) {
14533                if (origin.file != null) {
14534                    installFlags |= PackageManager.INSTALL_INTERNAL;
14535                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14536                } else if (origin.cid != null) {
14537                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14538                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14539                } else {
14540                    throw new IllegalStateException("Invalid stage location");
14541                }
14542            }
14543
14544            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14545            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14546            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14547            PackageInfoLite pkgLite = null;
14548
14549            if (onInt && onSd) {
14550                // Check if both bits are set.
14551                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14552                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14553            } else if (onSd && ephemeral) {
14554                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14555                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14556            } else {
14557                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14558                        packageAbiOverride);
14559
14560                if (DEBUG_EPHEMERAL && ephemeral) {
14561                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14562                }
14563
14564                /*
14565                 * If we have too little free space, try to free cache
14566                 * before giving up.
14567                 */
14568                if (!origin.staged && pkgLite.recommendedInstallLocation
14569                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14570                    // TODO: focus freeing disk space on the target device
14571                    final StorageManager storage = StorageManager.from(mContext);
14572                    final long lowThreshold = storage.getStorageLowBytes(
14573                            Environment.getDataDirectory());
14574
14575                    final long sizeBytes = mContainerService.calculateInstalledSize(
14576                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14577
14578                    try {
14579                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14580                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14581                                installFlags, packageAbiOverride);
14582                    } catch (InstallerException e) {
14583                        Slog.w(TAG, "Failed to free cache", e);
14584                    }
14585
14586                    /*
14587                     * The cache free must have deleted the file we
14588                     * downloaded to install.
14589                     *
14590                     * TODO: fix the "freeCache" call to not delete
14591                     *       the file we care about.
14592                     */
14593                    if (pkgLite.recommendedInstallLocation
14594                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14595                        pkgLite.recommendedInstallLocation
14596                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14597                    }
14598                }
14599            }
14600
14601            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14602                int loc = pkgLite.recommendedInstallLocation;
14603                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14604                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14605                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14606                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14607                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14608                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14609                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14610                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14611                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14612                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14613                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14614                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14615                } else {
14616                    // Override with defaults if needed.
14617                    loc = installLocationPolicy(pkgLite);
14618                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14619                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14620                    } else if (!onSd && !onInt) {
14621                        // Override install location with flags
14622                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14623                            // Set the flag to install on external media.
14624                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14625                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14626                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14627                            if (DEBUG_EPHEMERAL) {
14628                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14629                            }
14630                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14631                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14632                                    |PackageManager.INSTALL_INTERNAL);
14633                        } else {
14634                            // Make sure the flag for installing on external
14635                            // media is unset
14636                            installFlags |= PackageManager.INSTALL_INTERNAL;
14637                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14638                        }
14639                    }
14640                }
14641            }
14642
14643            final InstallArgs args = createInstallArgs(this);
14644            mArgs = args;
14645
14646            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14647                // TODO: http://b/22976637
14648                // Apps installed for "all" users use the device owner to verify the app
14649                UserHandle verifierUser = getUser();
14650                if (verifierUser == UserHandle.ALL) {
14651                    verifierUser = UserHandle.SYSTEM;
14652                }
14653
14654                /*
14655                 * Determine if we have any installed package verifiers. If we
14656                 * do, then we'll defer to them to verify the packages.
14657                 */
14658                final int requiredUid = mRequiredVerifierPackage == null ? -1
14659                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14660                                verifierUser.getIdentifier());
14661                if (!origin.existing && requiredUid != -1
14662                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
14663                    final Intent verification = new Intent(
14664                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14665                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14666                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14667                            PACKAGE_MIME_TYPE);
14668                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14669
14670                    // Query all live verifiers based on current user state
14671                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14672                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
14673
14674                    if (DEBUG_VERIFY) {
14675                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14676                                + verification.toString() + " with " + pkgLite.verifiers.length
14677                                + " optional verifiers");
14678                    }
14679
14680                    final int verificationId = mPendingVerificationToken++;
14681
14682                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14683
14684                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14685                            installerPackageName);
14686
14687                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14688                            installFlags);
14689
14690                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14691                            pkgLite.packageName);
14692
14693                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14694                            pkgLite.versionCode);
14695
14696                    if (verificationInfo != null) {
14697                        if (verificationInfo.originatingUri != null) {
14698                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14699                                    verificationInfo.originatingUri);
14700                        }
14701                        if (verificationInfo.referrer != null) {
14702                            verification.putExtra(Intent.EXTRA_REFERRER,
14703                                    verificationInfo.referrer);
14704                        }
14705                        if (verificationInfo.originatingUid >= 0) {
14706                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14707                                    verificationInfo.originatingUid);
14708                        }
14709                        if (verificationInfo.installerUid >= 0) {
14710                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14711                                    verificationInfo.installerUid);
14712                        }
14713                    }
14714
14715                    final PackageVerificationState verificationState = new PackageVerificationState(
14716                            requiredUid, args);
14717
14718                    mPendingVerification.append(verificationId, verificationState);
14719
14720                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14721                            receivers, verificationState);
14722
14723                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
14724                    final long idleDuration = getVerificationTimeout();
14725
14726                    /*
14727                     * If any sufficient verifiers were listed in the package
14728                     * manifest, attempt to ask them.
14729                     */
14730                    if (sufficientVerifiers != null) {
14731                        final int N = sufficientVerifiers.size();
14732                        if (N == 0) {
14733                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14734                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14735                        } else {
14736                            for (int i = 0; i < N; i++) {
14737                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14738                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14739                                        verifierComponent.getPackageName(), idleDuration,
14740                                        verifierUser.getIdentifier(), false, "package verifier");
14741
14742                                final Intent sufficientIntent = new Intent(verification);
14743                                sufficientIntent.setComponent(verifierComponent);
14744                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14745                            }
14746                        }
14747                    }
14748
14749                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14750                            mRequiredVerifierPackage, receivers);
14751                    if (ret == PackageManager.INSTALL_SUCCEEDED
14752                            && mRequiredVerifierPackage != null) {
14753                        Trace.asyncTraceBegin(
14754                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14755                        /*
14756                         * Send the intent to the required verification agent,
14757                         * but only start the verification timeout after the
14758                         * target BroadcastReceivers have run.
14759                         */
14760                        verification.setComponent(requiredVerifierComponent);
14761                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14762                                mRequiredVerifierPackage, idleDuration,
14763                                verifierUser.getIdentifier(), false, "package verifier");
14764                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14765                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14766                                new BroadcastReceiver() {
14767                                    @Override
14768                                    public void onReceive(Context context, Intent intent) {
14769                                        final Message msg = mHandler
14770                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14771                                        msg.arg1 = verificationId;
14772                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14773                                    }
14774                                }, null, 0, null, null);
14775
14776                        /*
14777                         * We don't want the copy to proceed until verification
14778                         * succeeds, so null out this field.
14779                         */
14780                        mArgs = null;
14781                    }
14782                } else {
14783                    /*
14784                     * No package verification is enabled, so immediately start
14785                     * the remote call to initiate copy using temporary file.
14786                     */
14787                    ret = args.copyApk(mContainerService, true);
14788                }
14789            }
14790
14791            mRet = ret;
14792        }
14793
14794        @Override
14795        void handleReturnCode() {
14796            // If mArgs is null, then MCS couldn't be reached. When it
14797            // reconnects, it will try again to install. At that point, this
14798            // will succeed.
14799            if (mArgs != null) {
14800                processPendingInstall(mArgs, mRet);
14801            }
14802        }
14803
14804        @Override
14805        void handleServiceError() {
14806            mArgs = createInstallArgs(this);
14807            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14808        }
14809
14810        public boolean isForwardLocked() {
14811            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14812        }
14813    }
14814
14815    /**
14816     * Used during creation of InstallArgs
14817     *
14818     * @param installFlags package installation flags
14819     * @return true if should be installed on external storage
14820     */
14821    private static boolean installOnExternalAsec(int installFlags) {
14822        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
14823            return false;
14824        }
14825        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14826            return true;
14827        }
14828        return false;
14829    }
14830
14831    /**
14832     * Used during creation of InstallArgs
14833     *
14834     * @param installFlags package installation flags
14835     * @return true if should be installed as forward locked
14836     */
14837    private static boolean installForwardLocked(int installFlags) {
14838        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14839    }
14840
14841    private InstallArgs createInstallArgs(InstallParams params) {
14842        if (params.move != null) {
14843            return new MoveInstallArgs(params);
14844        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
14845            return new AsecInstallArgs(params);
14846        } else {
14847            return new FileInstallArgs(params);
14848        }
14849    }
14850
14851    /**
14852     * Create args that describe an existing installed package. Typically used
14853     * when cleaning up old installs, or used as a move source.
14854     */
14855    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14856            String resourcePath, String[] instructionSets) {
14857        final boolean isInAsec;
14858        if (installOnExternalAsec(installFlags)) {
14859            /* Apps on SD card are always in ASEC containers. */
14860            isInAsec = true;
14861        } else if (installForwardLocked(installFlags)
14862                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
14863            /*
14864             * Forward-locked apps are only in ASEC containers if they're the
14865             * new style
14866             */
14867            isInAsec = true;
14868        } else {
14869            isInAsec = false;
14870        }
14871
14872        if (isInAsec) {
14873            return new AsecInstallArgs(codePath, instructionSets,
14874                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
14875        } else {
14876            return new FileInstallArgs(codePath, resourcePath, instructionSets);
14877        }
14878    }
14879
14880    static abstract class InstallArgs {
14881        /** @see InstallParams#origin */
14882        final OriginInfo origin;
14883        /** @see InstallParams#move */
14884        final MoveInfo move;
14885
14886        final IPackageInstallObserver2 observer;
14887        // Always refers to PackageManager flags only
14888        final int installFlags;
14889        final String installerPackageName;
14890        final String volumeUuid;
14891        final UserHandle user;
14892        final String abiOverride;
14893        final String[] installGrantPermissions;
14894        /** If non-null, drop an async trace when the install completes */
14895        final String traceMethod;
14896        final int traceCookie;
14897        final Certificate[][] certificates;
14898        final int installReason;
14899
14900        // The list of instruction sets supported by this app. This is currently
14901        // only used during the rmdex() phase to clean up resources. We can get rid of this
14902        // if we move dex files under the common app path.
14903        /* nullable */ String[] instructionSets;
14904
14905        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14906                int installFlags, String installerPackageName, String volumeUuid,
14907                UserHandle user, String[] instructionSets,
14908                String abiOverride, String[] installGrantPermissions,
14909                String traceMethod, int traceCookie, Certificate[][] certificates,
14910                int installReason) {
14911            this.origin = origin;
14912            this.move = move;
14913            this.installFlags = installFlags;
14914            this.observer = observer;
14915            this.installerPackageName = installerPackageName;
14916            this.volumeUuid = volumeUuid;
14917            this.user = user;
14918            this.instructionSets = instructionSets;
14919            this.abiOverride = abiOverride;
14920            this.installGrantPermissions = installGrantPermissions;
14921            this.traceMethod = traceMethod;
14922            this.traceCookie = traceCookie;
14923            this.certificates = certificates;
14924            this.installReason = installReason;
14925        }
14926
14927        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14928        abstract int doPreInstall(int status);
14929
14930        /**
14931         * Rename package into final resting place. All paths on the given
14932         * scanned package should be updated to reflect the rename.
14933         */
14934        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14935        abstract int doPostInstall(int status, int uid);
14936
14937        /** @see PackageSettingBase#codePathString */
14938        abstract String getCodePath();
14939        /** @see PackageSettingBase#resourcePathString */
14940        abstract String getResourcePath();
14941
14942        // Need installer lock especially for dex file removal.
14943        abstract void cleanUpResourcesLI();
14944        abstract boolean doPostDeleteLI(boolean delete);
14945
14946        /**
14947         * Called before the source arguments are copied. This is used mostly
14948         * for MoveParams when it needs to read the source file to put it in the
14949         * destination.
14950         */
14951        int doPreCopy() {
14952            return PackageManager.INSTALL_SUCCEEDED;
14953        }
14954
14955        /**
14956         * Called after the source arguments are copied. This is used mostly for
14957         * MoveParams when it needs to read the source file to put it in the
14958         * destination.
14959         */
14960        int doPostCopy(int uid) {
14961            return PackageManager.INSTALL_SUCCEEDED;
14962        }
14963
14964        protected boolean isFwdLocked() {
14965            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14966        }
14967
14968        protected boolean isExternalAsec() {
14969            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14970        }
14971
14972        protected boolean isEphemeral() {
14973            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14974        }
14975
14976        UserHandle getUser() {
14977            return user;
14978        }
14979    }
14980
14981    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14982        if (!allCodePaths.isEmpty()) {
14983            if (instructionSets == null) {
14984                throw new IllegalStateException("instructionSet == null");
14985            }
14986            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14987            for (String codePath : allCodePaths) {
14988                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14989                    try {
14990                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14991                    } catch (InstallerException ignored) {
14992                    }
14993                }
14994            }
14995        }
14996    }
14997
14998    /**
14999     * Logic to handle installation of non-ASEC applications, including copying
15000     * and renaming logic.
15001     */
15002    class FileInstallArgs extends InstallArgs {
15003        private File codeFile;
15004        private File resourceFile;
15005
15006        // Example topology:
15007        // /data/app/com.example/base.apk
15008        // /data/app/com.example/split_foo.apk
15009        // /data/app/com.example/lib/arm/libfoo.so
15010        // /data/app/com.example/lib/arm64/libfoo.so
15011        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15012
15013        /** New install */
15014        FileInstallArgs(InstallParams params) {
15015            super(params.origin, params.move, params.observer, params.installFlags,
15016                    params.installerPackageName, params.volumeUuid,
15017                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15018                    params.grantedRuntimePermissions,
15019                    params.traceMethod, params.traceCookie, params.certificates,
15020                    params.installReason);
15021            if (isFwdLocked()) {
15022                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15023            }
15024        }
15025
15026        /** Existing install */
15027        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15028            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15029                    null, null, null, 0, null /*certificates*/,
15030                    PackageManager.INSTALL_REASON_UNKNOWN);
15031            this.codeFile = (codePath != null) ? new File(codePath) : null;
15032            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15033        }
15034
15035        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15036            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15037            try {
15038                return doCopyApk(imcs, temp);
15039            } finally {
15040                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15041            }
15042        }
15043
15044        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15045            if (origin.staged) {
15046                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15047                codeFile = origin.file;
15048                resourceFile = origin.file;
15049                return PackageManager.INSTALL_SUCCEEDED;
15050            }
15051
15052            try {
15053                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15054                final File tempDir =
15055                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15056                codeFile = tempDir;
15057                resourceFile = tempDir;
15058            } catch (IOException e) {
15059                Slog.w(TAG, "Failed to create copy file: " + e);
15060                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15061            }
15062
15063            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15064                @Override
15065                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15066                    if (!FileUtils.isValidExtFilename(name)) {
15067                        throw new IllegalArgumentException("Invalid filename: " + name);
15068                    }
15069                    try {
15070                        final File file = new File(codeFile, name);
15071                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15072                                O_RDWR | O_CREAT, 0644);
15073                        Os.chmod(file.getAbsolutePath(), 0644);
15074                        return new ParcelFileDescriptor(fd);
15075                    } catch (ErrnoException e) {
15076                        throw new RemoteException("Failed to open: " + e.getMessage());
15077                    }
15078                }
15079            };
15080
15081            int ret = PackageManager.INSTALL_SUCCEEDED;
15082            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15083            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15084                Slog.e(TAG, "Failed to copy package");
15085                return ret;
15086            }
15087
15088            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15089            NativeLibraryHelper.Handle handle = null;
15090            try {
15091                handle = NativeLibraryHelper.Handle.create(codeFile);
15092                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15093                        abiOverride);
15094            } catch (IOException e) {
15095                Slog.e(TAG, "Copying native libraries failed", e);
15096                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15097            } finally {
15098                IoUtils.closeQuietly(handle);
15099            }
15100
15101            return ret;
15102        }
15103
15104        int doPreInstall(int status) {
15105            if (status != PackageManager.INSTALL_SUCCEEDED) {
15106                cleanUp();
15107            }
15108            return status;
15109        }
15110
15111        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15112            if (status != PackageManager.INSTALL_SUCCEEDED) {
15113                cleanUp();
15114                return false;
15115            }
15116
15117            final File targetDir = codeFile.getParentFile();
15118            final File beforeCodeFile = codeFile;
15119            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15120
15121            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15122            try {
15123                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15124            } catch (ErrnoException e) {
15125                Slog.w(TAG, "Failed to rename", e);
15126                return false;
15127            }
15128
15129            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15130                Slog.w(TAG, "Failed to restorecon");
15131                return false;
15132            }
15133
15134            // Reflect the rename internally
15135            codeFile = afterCodeFile;
15136            resourceFile = afterCodeFile;
15137
15138            // Reflect the rename in scanned details
15139            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15140            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15141                    afterCodeFile, pkg.baseCodePath));
15142            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15143                    afterCodeFile, pkg.splitCodePaths));
15144
15145            // Reflect the rename in app info
15146            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15147            pkg.setApplicationInfoCodePath(pkg.codePath);
15148            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15149            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15150            pkg.setApplicationInfoResourcePath(pkg.codePath);
15151            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15152            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15153
15154            return true;
15155        }
15156
15157        int doPostInstall(int status, int uid) {
15158            if (status != PackageManager.INSTALL_SUCCEEDED) {
15159                cleanUp();
15160            }
15161            return status;
15162        }
15163
15164        @Override
15165        String getCodePath() {
15166            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15167        }
15168
15169        @Override
15170        String getResourcePath() {
15171            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15172        }
15173
15174        private boolean cleanUp() {
15175            if (codeFile == null || !codeFile.exists()) {
15176                return false;
15177            }
15178
15179            removeCodePathLI(codeFile);
15180
15181            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15182                resourceFile.delete();
15183            }
15184
15185            return true;
15186        }
15187
15188        void cleanUpResourcesLI() {
15189            // Try enumerating all code paths before deleting
15190            List<String> allCodePaths = Collections.EMPTY_LIST;
15191            if (codeFile != null && codeFile.exists()) {
15192                try {
15193                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15194                    allCodePaths = pkg.getAllCodePaths();
15195                } catch (PackageParserException e) {
15196                    // Ignored; we tried our best
15197                }
15198            }
15199
15200            cleanUp();
15201            removeDexFiles(allCodePaths, instructionSets);
15202        }
15203
15204        boolean doPostDeleteLI(boolean delete) {
15205            // XXX err, shouldn't we respect the delete flag?
15206            cleanUpResourcesLI();
15207            return true;
15208        }
15209    }
15210
15211    private boolean isAsecExternal(String cid) {
15212        final String asecPath = PackageHelper.getSdFilesystem(cid);
15213        return !asecPath.startsWith(mAsecInternalPath);
15214    }
15215
15216    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15217            PackageManagerException {
15218        if (copyRet < 0) {
15219            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15220                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15221                throw new PackageManagerException(copyRet, message);
15222            }
15223        }
15224    }
15225
15226    /**
15227     * Extract the StorageManagerService "container ID" from the full code path of an
15228     * .apk.
15229     */
15230    static String cidFromCodePath(String fullCodePath) {
15231        int eidx = fullCodePath.lastIndexOf("/");
15232        String subStr1 = fullCodePath.substring(0, eidx);
15233        int sidx = subStr1.lastIndexOf("/");
15234        return subStr1.substring(sidx+1, eidx);
15235    }
15236
15237    /**
15238     * Logic to handle installation of ASEC applications, including copying and
15239     * renaming logic.
15240     */
15241    class AsecInstallArgs extends InstallArgs {
15242        static final String RES_FILE_NAME = "pkg.apk";
15243        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15244
15245        String cid;
15246        String packagePath;
15247        String resourcePath;
15248
15249        /** New install */
15250        AsecInstallArgs(InstallParams params) {
15251            super(params.origin, params.move, params.observer, params.installFlags,
15252                    params.installerPackageName, params.volumeUuid,
15253                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15254                    params.grantedRuntimePermissions,
15255                    params.traceMethod, params.traceCookie, params.certificates,
15256                    params.installReason);
15257        }
15258
15259        /** Existing install */
15260        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15261                        boolean isExternal, boolean isForwardLocked) {
15262            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15263                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15264                    instructionSets, null, null, null, 0, null /*certificates*/,
15265                    PackageManager.INSTALL_REASON_UNKNOWN);
15266            // Hackily pretend we're still looking at a full code path
15267            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15268                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15269            }
15270
15271            // Extract cid from fullCodePath
15272            int eidx = fullCodePath.lastIndexOf("/");
15273            String subStr1 = fullCodePath.substring(0, eidx);
15274            int sidx = subStr1.lastIndexOf("/");
15275            cid = subStr1.substring(sidx+1, eidx);
15276            setMountPath(subStr1);
15277        }
15278
15279        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15280            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15281                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15282                    instructionSets, null, null, null, 0, null /*certificates*/,
15283                    PackageManager.INSTALL_REASON_UNKNOWN);
15284            this.cid = cid;
15285            setMountPath(PackageHelper.getSdDir(cid));
15286        }
15287
15288        void createCopyFile() {
15289            cid = mInstallerService.allocateExternalStageCidLegacy();
15290        }
15291
15292        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15293            if (origin.staged && origin.cid != null) {
15294                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15295                cid = origin.cid;
15296                setMountPath(PackageHelper.getSdDir(cid));
15297                return PackageManager.INSTALL_SUCCEEDED;
15298            }
15299
15300            if (temp) {
15301                createCopyFile();
15302            } else {
15303                /*
15304                 * Pre-emptively destroy the container since it's destroyed if
15305                 * copying fails due to it existing anyway.
15306                 */
15307                PackageHelper.destroySdDir(cid);
15308            }
15309
15310            final String newMountPath = imcs.copyPackageToContainer(
15311                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15312                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15313
15314            if (newMountPath != null) {
15315                setMountPath(newMountPath);
15316                return PackageManager.INSTALL_SUCCEEDED;
15317            } else {
15318                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15319            }
15320        }
15321
15322        @Override
15323        String getCodePath() {
15324            return packagePath;
15325        }
15326
15327        @Override
15328        String getResourcePath() {
15329            return resourcePath;
15330        }
15331
15332        int doPreInstall(int status) {
15333            if (status != PackageManager.INSTALL_SUCCEEDED) {
15334                // Destroy container
15335                PackageHelper.destroySdDir(cid);
15336            } else {
15337                boolean mounted = PackageHelper.isContainerMounted(cid);
15338                if (!mounted) {
15339                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15340                            Process.SYSTEM_UID);
15341                    if (newMountPath != null) {
15342                        setMountPath(newMountPath);
15343                    } else {
15344                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15345                    }
15346                }
15347            }
15348            return status;
15349        }
15350
15351        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15352            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15353            String newMountPath = null;
15354            if (PackageHelper.isContainerMounted(cid)) {
15355                // Unmount the container
15356                if (!PackageHelper.unMountSdDir(cid)) {
15357                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15358                    return false;
15359                }
15360            }
15361            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15362                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15363                        " which might be stale. Will try to clean up.");
15364                // Clean up the stale container and proceed to recreate.
15365                if (!PackageHelper.destroySdDir(newCacheId)) {
15366                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15367                    return false;
15368                }
15369                // Successfully cleaned up stale container. Try to rename again.
15370                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15371                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15372                            + " inspite of cleaning it up.");
15373                    return false;
15374                }
15375            }
15376            if (!PackageHelper.isContainerMounted(newCacheId)) {
15377                Slog.w(TAG, "Mounting container " + newCacheId);
15378                newMountPath = PackageHelper.mountSdDir(newCacheId,
15379                        getEncryptKey(), Process.SYSTEM_UID);
15380            } else {
15381                newMountPath = PackageHelper.getSdDir(newCacheId);
15382            }
15383            if (newMountPath == null) {
15384                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15385                return false;
15386            }
15387            Log.i(TAG, "Succesfully renamed " + cid +
15388                    " to " + newCacheId +
15389                    " at new path: " + newMountPath);
15390            cid = newCacheId;
15391
15392            final File beforeCodeFile = new File(packagePath);
15393            setMountPath(newMountPath);
15394            final File afterCodeFile = new File(packagePath);
15395
15396            // Reflect the rename in scanned details
15397            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15398            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15399                    afterCodeFile, pkg.baseCodePath));
15400            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15401                    afterCodeFile, pkg.splitCodePaths));
15402
15403            // Reflect the rename in app info
15404            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15405            pkg.setApplicationInfoCodePath(pkg.codePath);
15406            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15407            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15408            pkg.setApplicationInfoResourcePath(pkg.codePath);
15409            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15410            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15411
15412            return true;
15413        }
15414
15415        private void setMountPath(String mountPath) {
15416            final File mountFile = new File(mountPath);
15417
15418            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15419            if (monolithicFile.exists()) {
15420                packagePath = monolithicFile.getAbsolutePath();
15421                if (isFwdLocked()) {
15422                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15423                } else {
15424                    resourcePath = packagePath;
15425                }
15426            } else {
15427                packagePath = mountFile.getAbsolutePath();
15428                resourcePath = packagePath;
15429            }
15430        }
15431
15432        int doPostInstall(int status, int uid) {
15433            if (status != PackageManager.INSTALL_SUCCEEDED) {
15434                cleanUp();
15435            } else {
15436                final int groupOwner;
15437                final String protectedFile;
15438                if (isFwdLocked()) {
15439                    groupOwner = UserHandle.getSharedAppGid(uid);
15440                    protectedFile = RES_FILE_NAME;
15441                } else {
15442                    groupOwner = -1;
15443                    protectedFile = null;
15444                }
15445
15446                if (uid < Process.FIRST_APPLICATION_UID
15447                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15448                    Slog.e(TAG, "Failed to finalize " + cid);
15449                    PackageHelper.destroySdDir(cid);
15450                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15451                }
15452
15453                boolean mounted = PackageHelper.isContainerMounted(cid);
15454                if (!mounted) {
15455                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15456                }
15457            }
15458            return status;
15459        }
15460
15461        private void cleanUp() {
15462            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15463
15464            // Destroy secure container
15465            PackageHelper.destroySdDir(cid);
15466        }
15467
15468        private List<String> getAllCodePaths() {
15469            final File codeFile = new File(getCodePath());
15470            if (codeFile != null && codeFile.exists()) {
15471                try {
15472                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15473                    return pkg.getAllCodePaths();
15474                } catch (PackageParserException e) {
15475                    // Ignored; we tried our best
15476                }
15477            }
15478            return Collections.EMPTY_LIST;
15479        }
15480
15481        void cleanUpResourcesLI() {
15482            // Enumerate all code paths before deleting
15483            cleanUpResourcesLI(getAllCodePaths());
15484        }
15485
15486        private void cleanUpResourcesLI(List<String> allCodePaths) {
15487            cleanUp();
15488            removeDexFiles(allCodePaths, instructionSets);
15489        }
15490
15491        String getPackageName() {
15492            return getAsecPackageName(cid);
15493        }
15494
15495        boolean doPostDeleteLI(boolean delete) {
15496            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15497            final List<String> allCodePaths = getAllCodePaths();
15498            boolean mounted = PackageHelper.isContainerMounted(cid);
15499            if (mounted) {
15500                // Unmount first
15501                if (PackageHelper.unMountSdDir(cid)) {
15502                    mounted = false;
15503                }
15504            }
15505            if (!mounted && delete) {
15506                cleanUpResourcesLI(allCodePaths);
15507            }
15508            return !mounted;
15509        }
15510
15511        @Override
15512        int doPreCopy() {
15513            if (isFwdLocked()) {
15514                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15515                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15516                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15517                }
15518            }
15519
15520            return PackageManager.INSTALL_SUCCEEDED;
15521        }
15522
15523        @Override
15524        int doPostCopy(int uid) {
15525            if (isFwdLocked()) {
15526                if (uid < Process.FIRST_APPLICATION_UID
15527                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15528                                RES_FILE_NAME)) {
15529                    Slog.e(TAG, "Failed to finalize " + cid);
15530                    PackageHelper.destroySdDir(cid);
15531                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15532                }
15533            }
15534
15535            return PackageManager.INSTALL_SUCCEEDED;
15536        }
15537    }
15538
15539    /**
15540     * Logic to handle movement of existing installed applications.
15541     */
15542    class MoveInstallArgs extends InstallArgs {
15543        private File codeFile;
15544        private File resourceFile;
15545
15546        /** New install */
15547        MoveInstallArgs(InstallParams params) {
15548            super(params.origin, params.move, params.observer, params.installFlags,
15549                    params.installerPackageName, params.volumeUuid,
15550                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15551                    params.grantedRuntimePermissions,
15552                    params.traceMethod, params.traceCookie, params.certificates,
15553                    params.installReason);
15554        }
15555
15556        int copyApk(IMediaContainerService imcs, boolean temp) {
15557            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15558                    + move.fromUuid + " to " + move.toUuid);
15559            synchronized (mInstaller) {
15560                try {
15561                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15562                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15563                } catch (InstallerException e) {
15564                    Slog.w(TAG, "Failed to move app", e);
15565                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15566                }
15567            }
15568
15569            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15570            resourceFile = codeFile;
15571            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15572
15573            return PackageManager.INSTALL_SUCCEEDED;
15574        }
15575
15576        int doPreInstall(int status) {
15577            if (status != PackageManager.INSTALL_SUCCEEDED) {
15578                cleanUp(move.toUuid);
15579            }
15580            return status;
15581        }
15582
15583        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15584            if (status != PackageManager.INSTALL_SUCCEEDED) {
15585                cleanUp(move.toUuid);
15586                return false;
15587            }
15588
15589            // Reflect the move in app info
15590            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15591            pkg.setApplicationInfoCodePath(pkg.codePath);
15592            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15593            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15594            pkg.setApplicationInfoResourcePath(pkg.codePath);
15595            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15596            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15597
15598            return true;
15599        }
15600
15601        int doPostInstall(int status, int uid) {
15602            if (status == PackageManager.INSTALL_SUCCEEDED) {
15603                cleanUp(move.fromUuid);
15604            } else {
15605                cleanUp(move.toUuid);
15606            }
15607            return status;
15608        }
15609
15610        @Override
15611        String getCodePath() {
15612            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15613        }
15614
15615        @Override
15616        String getResourcePath() {
15617            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15618        }
15619
15620        private boolean cleanUp(String volumeUuid) {
15621            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15622                    move.dataAppName);
15623            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15624            final int[] userIds = sUserManager.getUserIds();
15625            synchronized (mInstallLock) {
15626                // Clean up both app data and code
15627                // All package moves are frozen until finished
15628                for (int userId : userIds) {
15629                    try {
15630                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15631                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15632                    } catch (InstallerException e) {
15633                        Slog.w(TAG, String.valueOf(e));
15634                    }
15635                }
15636                removeCodePathLI(codeFile);
15637            }
15638            return true;
15639        }
15640
15641        void cleanUpResourcesLI() {
15642            throw new UnsupportedOperationException();
15643        }
15644
15645        boolean doPostDeleteLI(boolean delete) {
15646            throw new UnsupportedOperationException();
15647        }
15648    }
15649
15650    static String getAsecPackageName(String packageCid) {
15651        int idx = packageCid.lastIndexOf("-");
15652        if (idx == -1) {
15653            return packageCid;
15654        }
15655        return packageCid.substring(0, idx);
15656    }
15657
15658    // Utility method used to create code paths based on package name and available index.
15659    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15660        String idxStr = "";
15661        int idx = 1;
15662        // Fall back to default value of idx=1 if prefix is not
15663        // part of oldCodePath
15664        if (oldCodePath != null) {
15665            String subStr = oldCodePath;
15666            // Drop the suffix right away
15667            if (suffix != null && subStr.endsWith(suffix)) {
15668                subStr = subStr.substring(0, subStr.length() - suffix.length());
15669            }
15670            // If oldCodePath already contains prefix find out the
15671            // ending index to either increment or decrement.
15672            int sidx = subStr.lastIndexOf(prefix);
15673            if (sidx != -1) {
15674                subStr = subStr.substring(sidx + prefix.length());
15675                if (subStr != null) {
15676                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15677                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15678                    }
15679                    try {
15680                        idx = Integer.parseInt(subStr);
15681                        if (idx <= 1) {
15682                            idx++;
15683                        } else {
15684                            idx--;
15685                        }
15686                    } catch(NumberFormatException e) {
15687                    }
15688                }
15689            }
15690        }
15691        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15692        return prefix + idxStr;
15693    }
15694
15695    private File getNextCodePath(File targetDir, String packageName) {
15696        File result;
15697        SecureRandom random = new SecureRandom();
15698        byte[] bytes = new byte[16];
15699        do {
15700            random.nextBytes(bytes);
15701            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15702            result = new File(targetDir, packageName + "-" + suffix);
15703        } while (result.exists());
15704        return result;
15705    }
15706
15707    // Utility method that returns the relative package path with respect
15708    // to the installation directory. Like say for /data/data/com.test-1.apk
15709    // string com.test-1 is returned.
15710    static String deriveCodePathName(String codePath) {
15711        if (codePath == null) {
15712            return null;
15713        }
15714        final File codeFile = new File(codePath);
15715        final String name = codeFile.getName();
15716        if (codeFile.isDirectory()) {
15717            return name;
15718        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15719            final int lastDot = name.lastIndexOf('.');
15720            return name.substring(0, lastDot);
15721        } else {
15722            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15723            return null;
15724        }
15725    }
15726
15727    static class PackageInstalledInfo {
15728        String name;
15729        int uid;
15730        // The set of users that originally had this package installed.
15731        int[] origUsers;
15732        // The set of users that now have this package installed.
15733        int[] newUsers;
15734        PackageParser.Package pkg;
15735        int returnCode;
15736        String returnMsg;
15737        PackageRemovedInfo removedInfo;
15738        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15739
15740        public void setError(int code, String msg) {
15741            setReturnCode(code);
15742            setReturnMessage(msg);
15743            Slog.w(TAG, msg);
15744        }
15745
15746        public void setError(String msg, PackageParserException e) {
15747            setReturnCode(e.error);
15748            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15749            Slog.w(TAG, msg, e);
15750        }
15751
15752        public void setError(String msg, PackageManagerException e) {
15753            returnCode = e.error;
15754            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15755            Slog.w(TAG, msg, e);
15756        }
15757
15758        public void setReturnCode(int returnCode) {
15759            this.returnCode = returnCode;
15760            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15761            for (int i = 0; i < childCount; i++) {
15762                addedChildPackages.valueAt(i).returnCode = returnCode;
15763            }
15764        }
15765
15766        private void setReturnMessage(String returnMsg) {
15767            this.returnMsg = returnMsg;
15768            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15769            for (int i = 0; i < childCount; i++) {
15770                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15771            }
15772        }
15773
15774        // In some error cases we want to convey more info back to the observer
15775        String origPackage;
15776        String origPermission;
15777    }
15778
15779    /*
15780     * Install a non-existing package.
15781     */
15782    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15783            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15784            PackageInstalledInfo res, int installReason) {
15785        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15786
15787        // Remember this for later, in case we need to rollback this install
15788        String pkgName = pkg.packageName;
15789
15790        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15791
15792        synchronized(mPackages) {
15793            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15794            if (renamedPackage != null) {
15795                // A package with the same name is already installed, though
15796                // it has been renamed to an older name.  The package we
15797                // are trying to install should be installed as an update to
15798                // the existing one, but that has not been requested, so bail.
15799                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15800                        + " without first uninstalling package running as "
15801                        + renamedPackage);
15802                return;
15803            }
15804            if (mPackages.containsKey(pkgName)) {
15805                // Don't allow installation over an existing package with the same name.
15806                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15807                        + " without first uninstalling.");
15808                return;
15809            }
15810        }
15811
15812        try {
15813            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15814                    System.currentTimeMillis(), user);
15815
15816            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15817
15818            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15819                prepareAppDataAfterInstallLIF(newPackage);
15820
15821            } else {
15822                // Remove package from internal structures, but keep around any
15823                // data that might have already existed
15824                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15825                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15826            }
15827        } catch (PackageManagerException e) {
15828            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15829        }
15830
15831        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15832    }
15833
15834    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
15835        // Can't rotate keys during boot or if sharedUser.
15836        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
15837                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
15838            return false;
15839        }
15840        // app is using upgradeKeySets; make sure all are valid
15841        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15842        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
15843        for (int i = 0; i < upgradeKeySets.length; i++) {
15844            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
15845                Slog.wtf(TAG, "Package "
15846                         + (oldPs.name != null ? oldPs.name : "<null>")
15847                         + " contains upgrade-key-set reference to unknown key-set: "
15848                         + upgradeKeySets[i]
15849                         + " reverting to signatures check.");
15850                return false;
15851            }
15852        }
15853        return true;
15854    }
15855
15856    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
15857        // Upgrade keysets are being used.  Determine if new package has a superset of the
15858        // required keys.
15859        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
15860        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15861        for (int i = 0; i < upgradeKeySets.length; i++) {
15862            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
15863            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
15864                return true;
15865            }
15866        }
15867        return false;
15868    }
15869
15870    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15871        try (DigestInputStream digestStream =
15872                new DigestInputStream(new FileInputStream(file), digest)) {
15873            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15874        }
15875    }
15876
15877    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
15878            UserHandle user, String installerPackageName, PackageInstalledInfo res,
15879            int installReason) {
15880        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15881
15882        final PackageParser.Package oldPackage;
15883        final String pkgName = pkg.packageName;
15884        final int[] allUsers;
15885        final int[] installedUsers;
15886
15887        synchronized(mPackages) {
15888            oldPackage = mPackages.get(pkgName);
15889            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15890
15891            // don't allow upgrade to target a release SDK from a pre-release SDK
15892            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15893                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15894            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15895                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15896            if (oldTargetsPreRelease
15897                    && !newTargetsPreRelease
15898                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15899                Slog.w(TAG, "Can't install package targeting released sdk");
15900                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15901                return;
15902            }
15903
15904            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15905
15906            // verify signatures are valid
15907            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15908                if (!checkUpgradeKeySetLP(ps, pkg)) {
15909                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15910                            "New package not signed by keys specified by upgrade-keysets: "
15911                                    + pkgName);
15912                    return;
15913                }
15914            } else {
15915                // default to original signature matching
15916                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15917                        != PackageManager.SIGNATURE_MATCH) {
15918                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15919                            "New package has a different signature: " + pkgName);
15920                    return;
15921                }
15922            }
15923
15924            // don't allow a system upgrade unless the upgrade hash matches
15925            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
15926                byte[] digestBytes = null;
15927                try {
15928                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15929                    updateDigest(digest, new File(pkg.baseCodePath));
15930                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15931                        for (String path : pkg.splitCodePaths) {
15932                            updateDigest(digest, new File(path));
15933                        }
15934                    }
15935                    digestBytes = digest.digest();
15936                } catch (NoSuchAlgorithmException | IOException e) {
15937                    res.setError(INSTALL_FAILED_INVALID_APK,
15938                            "Could not compute hash: " + pkgName);
15939                    return;
15940                }
15941                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15942                    res.setError(INSTALL_FAILED_INVALID_APK,
15943                            "New package fails restrict-update check: " + pkgName);
15944                    return;
15945                }
15946                // retain upgrade restriction
15947                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15948            }
15949
15950            // Check for shared user id changes
15951            String invalidPackageName =
15952                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15953            if (invalidPackageName != null) {
15954                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15955                        "Package " + invalidPackageName + " tried to change user "
15956                                + oldPackage.mSharedUserId);
15957                return;
15958            }
15959
15960            // In case of rollback, remember per-user/profile install state
15961            allUsers = sUserManager.getUserIds();
15962            installedUsers = ps.queryInstalledUsers(allUsers, true);
15963
15964            // don't allow an upgrade from full to ephemeral
15965            if (isInstantApp) {
15966                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
15967                    for (int currentUser : allUsers) {
15968                        if (!ps.getInstantApp(currentUser)) {
15969                            // can't downgrade from full to instant
15970                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15971                                    + " for user: " + currentUser);
15972                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15973                            return;
15974                        }
15975                    }
15976                } else if (!ps.getInstantApp(user.getIdentifier())) {
15977                    // can't downgrade from full to instant
15978                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15979                            + " for user: " + user.getIdentifier());
15980                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15981                    return;
15982                }
15983            }
15984        }
15985
15986        // Update what is removed
15987        res.removedInfo = new PackageRemovedInfo();
15988        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15989        res.removedInfo.removedPackage = oldPackage.packageName;
15990        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15991        res.removedInfo.isUpdate = true;
15992        res.removedInfo.origUsers = installedUsers;
15993        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
15994        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15995        for (int i = 0; i < installedUsers.length; i++) {
15996            final int userId = installedUsers[i];
15997            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15998        }
15999
16000        final int childCount = (oldPackage.childPackages != null)
16001                ? oldPackage.childPackages.size() : 0;
16002        for (int i = 0; i < childCount; i++) {
16003            boolean childPackageUpdated = false;
16004            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16005            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16006            if (res.addedChildPackages != null) {
16007                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16008                if (childRes != null) {
16009                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16010                    childRes.removedInfo.removedPackage = childPkg.packageName;
16011                    childRes.removedInfo.isUpdate = true;
16012                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16013                    childPackageUpdated = true;
16014                }
16015            }
16016            if (!childPackageUpdated) {
16017                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
16018                childRemovedRes.removedPackage = childPkg.packageName;
16019                childRemovedRes.isUpdate = false;
16020                childRemovedRes.dataRemoved = true;
16021                synchronized (mPackages) {
16022                    if (childPs != null) {
16023                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16024                    }
16025                }
16026                if (res.removedInfo.removedChildPackages == null) {
16027                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16028                }
16029                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16030            }
16031        }
16032
16033        boolean sysPkg = (isSystemApp(oldPackage));
16034        if (sysPkg) {
16035            // Set the system/privileged flags as needed
16036            final boolean privileged =
16037                    (oldPackage.applicationInfo.privateFlags
16038                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16039            final int systemPolicyFlags = policyFlags
16040                    | PackageParser.PARSE_IS_SYSTEM
16041                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
16042
16043            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
16044                    user, allUsers, installerPackageName, res, installReason);
16045        } else {
16046            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
16047                    user, allUsers, installerPackageName, res, installReason);
16048        }
16049    }
16050
16051    public List<String> getPreviousCodePaths(String packageName) {
16052        final PackageSetting ps = mSettings.mPackages.get(packageName);
16053        final List<String> result = new ArrayList<String>();
16054        if (ps != null && ps.oldCodePaths != null) {
16055            result.addAll(ps.oldCodePaths);
16056        }
16057        return result;
16058    }
16059
16060    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16061            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16062            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16063            int installReason) {
16064        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16065                + deletedPackage);
16066
16067        String pkgName = deletedPackage.packageName;
16068        boolean deletedPkg = true;
16069        boolean addedPkg = false;
16070        boolean updatedSettings = false;
16071        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16072        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16073                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16074
16075        final long origUpdateTime = (pkg.mExtras != null)
16076                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16077
16078        // First delete the existing package while retaining the data directory
16079        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16080                res.removedInfo, true, pkg)) {
16081            // If the existing package wasn't successfully deleted
16082            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16083            deletedPkg = false;
16084        } else {
16085            // Successfully deleted the old package; proceed with replace.
16086
16087            // If deleted package lived in a container, give users a chance to
16088            // relinquish resources before killing.
16089            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16090                if (DEBUG_INSTALL) {
16091                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16092                }
16093                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16094                final ArrayList<String> pkgList = new ArrayList<String>(1);
16095                pkgList.add(deletedPackage.applicationInfo.packageName);
16096                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16097            }
16098
16099            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16100                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16101            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16102
16103            try {
16104                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
16105                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16106                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16107                        installReason);
16108
16109                // Update the in-memory copy of the previous code paths.
16110                PackageSetting ps = mSettings.mPackages.get(pkgName);
16111                if (!killApp) {
16112                    if (ps.oldCodePaths == null) {
16113                        ps.oldCodePaths = new ArraySet<>();
16114                    }
16115                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16116                    if (deletedPackage.splitCodePaths != null) {
16117                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16118                    }
16119                } else {
16120                    ps.oldCodePaths = null;
16121                }
16122                if (ps.childPackageNames != null) {
16123                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16124                        final String childPkgName = ps.childPackageNames.get(i);
16125                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16126                        childPs.oldCodePaths = ps.oldCodePaths;
16127                    }
16128                }
16129                // set instant app status, but, only if it's explicitly specified
16130                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16131                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16132                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16133                prepareAppDataAfterInstallLIF(newPackage);
16134                addedPkg = true;
16135                mDexManager.notifyPackageUpdated(newPackage.packageName,
16136                        newPackage.baseCodePath, newPackage.splitCodePaths);
16137            } catch (PackageManagerException e) {
16138                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16139            }
16140        }
16141
16142        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16143            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16144
16145            // Revert all internal state mutations and added folders for the failed install
16146            if (addedPkg) {
16147                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16148                        res.removedInfo, true, null);
16149            }
16150
16151            // Restore the old package
16152            if (deletedPkg) {
16153                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16154                File restoreFile = new File(deletedPackage.codePath);
16155                // Parse old package
16156                boolean oldExternal = isExternal(deletedPackage);
16157                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16158                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16159                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16160                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16161                try {
16162                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16163                            null);
16164                } catch (PackageManagerException e) {
16165                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16166                            + e.getMessage());
16167                    return;
16168                }
16169
16170                synchronized (mPackages) {
16171                    // Ensure the installer package name up to date
16172                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16173
16174                    // Update permissions for restored package
16175                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16176
16177                    mSettings.writeLPr();
16178                }
16179
16180                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16181            }
16182        } else {
16183            synchronized (mPackages) {
16184                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16185                if (ps != null) {
16186                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16187                    if (res.removedInfo.removedChildPackages != null) {
16188                        final int childCount = res.removedInfo.removedChildPackages.size();
16189                        // Iterate in reverse as we may modify the collection
16190                        for (int i = childCount - 1; i >= 0; i--) {
16191                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16192                            if (res.addedChildPackages.containsKey(childPackageName)) {
16193                                res.removedInfo.removedChildPackages.removeAt(i);
16194                            } else {
16195                                PackageRemovedInfo childInfo = res.removedInfo
16196                                        .removedChildPackages.valueAt(i);
16197                                childInfo.removedForAllUsers = mPackages.get(
16198                                        childInfo.removedPackage) == null;
16199                            }
16200                        }
16201                    }
16202                }
16203            }
16204        }
16205    }
16206
16207    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16208            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16209            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16210            int installReason) {
16211        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16212                + ", old=" + deletedPackage);
16213
16214        final boolean disabledSystem;
16215
16216        // Remove existing system package
16217        removePackageLI(deletedPackage, true);
16218
16219        synchronized (mPackages) {
16220            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16221        }
16222        if (!disabledSystem) {
16223            // We didn't need to disable the .apk as a current system package,
16224            // which means we are replacing another update that is already
16225            // installed.  We need to make sure to delete the older one's .apk.
16226            res.removedInfo.args = createInstallArgsForExisting(0,
16227                    deletedPackage.applicationInfo.getCodePath(),
16228                    deletedPackage.applicationInfo.getResourcePath(),
16229                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16230        } else {
16231            res.removedInfo.args = null;
16232        }
16233
16234        // Successfully disabled the old package. Now proceed with re-installation
16235        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16236                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16237        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16238
16239        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16240        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16241                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16242
16243        PackageParser.Package newPackage = null;
16244        try {
16245            // Add the package to the internal data structures
16246            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16247
16248            // Set the update and install times
16249            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16250            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16251                    System.currentTimeMillis());
16252
16253            // Update the package dynamic state if succeeded
16254            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16255                // Now that the install succeeded make sure we remove data
16256                // directories for any child package the update removed.
16257                final int deletedChildCount = (deletedPackage.childPackages != null)
16258                        ? deletedPackage.childPackages.size() : 0;
16259                final int newChildCount = (newPackage.childPackages != null)
16260                        ? newPackage.childPackages.size() : 0;
16261                for (int i = 0; i < deletedChildCount; i++) {
16262                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16263                    boolean childPackageDeleted = true;
16264                    for (int j = 0; j < newChildCount; j++) {
16265                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16266                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16267                            childPackageDeleted = false;
16268                            break;
16269                        }
16270                    }
16271                    if (childPackageDeleted) {
16272                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16273                                deletedChildPkg.packageName);
16274                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16275                            PackageRemovedInfo removedChildRes = res.removedInfo
16276                                    .removedChildPackages.get(deletedChildPkg.packageName);
16277                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16278                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16279                        }
16280                    }
16281                }
16282
16283                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16284                        installReason);
16285                prepareAppDataAfterInstallLIF(newPackage);
16286
16287                mDexManager.notifyPackageUpdated(newPackage.packageName,
16288                            newPackage.baseCodePath, newPackage.splitCodePaths);
16289            }
16290        } catch (PackageManagerException e) {
16291            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16292            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16293        }
16294
16295        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16296            // Re installation failed. Restore old information
16297            // Remove new pkg information
16298            if (newPackage != null) {
16299                removeInstalledPackageLI(newPackage, true);
16300            }
16301            // Add back the old system package
16302            try {
16303                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16304            } catch (PackageManagerException e) {
16305                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16306            }
16307
16308            synchronized (mPackages) {
16309                if (disabledSystem) {
16310                    enableSystemPackageLPw(deletedPackage);
16311                }
16312
16313                // Ensure the installer package name up to date
16314                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16315
16316                // Update permissions for restored package
16317                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16318
16319                mSettings.writeLPr();
16320            }
16321
16322            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16323                    + " after failed upgrade");
16324        }
16325    }
16326
16327    /**
16328     * Checks whether the parent or any of the child packages have a change shared
16329     * user. For a package to be a valid update the shred users of the parent and
16330     * the children should match. We may later support changing child shared users.
16331     * @param oldPkg The updated package.
16332     * @param newPkg The update package.
16333     * @return The shared user that change between the versions.
16334     */
16335    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16336            PackageParser.Package newPkg) {
16337        // Check parent shared user
16338        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16339            return newPkg.packageName;
16340        }
16341        // Check child shared users
16342        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16343        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16344        for (int i = 0; i < newChildCount; i++) {
16345            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16346            // If this child was present, did it have the same shared user?
16347            for (int j = 0; j < oldChildCount; j++) {
16348                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16349                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16350                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16351                    return newChildPkg.packageName;
16352                }
16353            }
16354        }
16355        return null;
16356    }
16357
16358    private void removeNativeBinariesLI(PackageSetting ps) {
16359        // Remove the lib path for the parent package
16360        if (ps != null) {
16361            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16362            // Remove the lib path for the child packages
16363            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16364            for (int i = 0; i < childCount; i++) {
16365                PackageSetting childPs = null;
16366                synchronized (mPackages) {
16367                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16368                }
16369                if (childPs != null) {
16370                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16371                            .legacyNativeLibraryPathString);
16372                }
16373            }
16374        }
16375    }
16376
16377    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16378        // Enable the parent package
16379        mSettings.enableSystemPackageLPw(pkg.packageName);
16380        // Enable the child packages
16381        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16382        for (int i = 0; i < childCount; i++) {
16383            PackageParser.Package childPkg = pkg.childPackages.get(i);
16384            mSettings.enableSystemPackageLPw(childPkg.packageName);
16385        }
16386    }
16387
16388    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16389            PackageParser.Package newPkg) {
16390        // Disable the parent package (parent always replaced)
16391        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16392        // Disable the child packages
16393        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16394        for (int i = 0; i < childCount; i++) {
16395            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16396            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16397            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16398        }
16399        return disabled;
16400    }
16401
16402    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16403            String installerPackageName) {
16404        // Enable the parent package
16405        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16406        // Enable the child packages
16407        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16408        for (int i = 0; i < childCount; i++) {
16409            PackageParser.Package childPkg = pkg.childPackages.get(i);
16410            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16411        }
16412    }
16413
16414    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16415        // Collect all used permissions in the UID
16416        ArraySet<String> usedPermissions = new ArraySet<>();
16417        final int packageCount = su.packages.size();
16418        for (int i = 0; i < packageCount; i++) {
16419            PackageSetting ps = su.packages.valueAt(i);
16420            if (ps.pkg == null) {
16421                continue;
16422            }
16423            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16424            for (int j = 0; j < requestedPermCount; j++) {
16425                String permission = ps.pkg.requestedPermissions.get(j);
16426                BasePermission bp = mSettings.mPermissions.get(permission);
16427                if (bp != null) {
16428                    usedPermissions.add(permission);
16429                }
16430            }
16431        }
16432
16433        PermissionsState permissionsState = su.getPermissionsState();
16434        // Prune install permissions
16435        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16436        final int installPermCount = installPermStates.size();
16437        for (int i = installPermCount - 1; i >= 0;  i--) {
16438            PermissionState permissionState = installPermStates.get(i);
16439            if (!usedPermissions.contains(permissionState.getName())) {
16440                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16441                if (bp != null) {
16442                    permissionsState.revokeInstallPermission(bp);
16443                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16444                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16445                }
16446            }
16447        }
16448
16449        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16450
16451        // Prune runtime permissions
16452        for (int userId : allUserIds) {
16453            List<PermissionState> runtimePermStates = permissionsState
16454                    .getRuntimePermissionStates(userId);
16455            final int runtimePermCount = runtimePermStates.size();
16456            for (int i = runtimePermCount - 1; i >= 0; i--) {
16457                PermissionState permissionState = runtimePermStates.get(i);
16458                if (!usedPermissions.contains(permissionState.getName())) {
16459                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16460                    if (bp != null) {
16461                        permissionsState.revokeRuntimePermission(bp, userId);
16462                        permissionsState.updatePermissionFlags(bp, userId,
16463                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16464                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16465                                runtimePermissionChangedUserIds, userId);
16466                    }
16467                }
16468            }
16469        }
16470
16471        return runtimePermissionChangedUserIds;
16472    }
16473
16474    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16475            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16476        // Update the parent package setting
16477        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16478                res, user, installReason);
16479        // Update the child packages setting
16480        final int childCount = (newPackage.childPackages != null)
16481                ? newPackage.childPackages.size() : 0;
16482        for (int i = 0; i < childCount; i++) {
16483            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16484            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16485            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16486                    childRes.origUsers, childRes, user, installReason);
16487        }
16488    }
16489
16490    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16491            String installerPackageName, int[] allUsers, int[] installedForUsers,
16492            PackageInstalledInfo res, UserHandle user, int installReason) {
16493        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16494
16495        String pkgName = newPackage.packageName;
16496        synchronized (mPackages) {
16497            //write settings. the installStatus will be incomplete at this stage.
16498            //note that the new package setting would have already been
16499            //added to mPackages. It hasn't been persisted yet.
16500            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16501            // TODO: Remove this write? It's also written at the end of this method
16502            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16503            mSettings.writeLPr();
16504            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16505        }
16506
16507        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16508        synchronized (mPackages) {
16509            updatePermissionsLPw(newPackage.packageName, newPackage,
16510                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16511                            ? UPDATE_PERMISSIONS_ALL : 0));
16512            // For system-bundled packages, we assume that installing an upgraded version
16513            // of the package implies that the user actually wants to run that new code,
16514            // so we enable the package.
16515            PackageSetting ps = mSettings.mPackages.get(pkgName);
16516            final int userId = user.getIdentifier();
16517            if (ps != null) {
16518                if (isSystemApp(newPackage)) {
16519                    if (DEBUG_INSTALL) {
16520                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16521                    }
16522                    // Enable system package for requested users
16523                    if (res.origUsers != null) {
16524                        for (int origUserId : res.origUsers) {
16525                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16526                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16527                                        origUserId, installerPackageName);
16528                            }
16529                        }
16530                    }
16531                    // Also convey the prior install/uninstall state
16532                    if (allUsers != null && installedForUsers != null) {
16533                        for (int currentUserId : allUsers) {
16534                            final boolean installed = ArrayUtils.contains(
16535                                    installedForUsers, currentUserId);
16536                            if (DEBUG_INSTALL) {
16537                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16538                            }
16539                            ps.setInstalled(installed, currentUserId);
16540                        }
16541                        // these install state changes will be persisted in the
16542                        // upcoming call to mSettings.writeLPr().
16543                    }
16544                }
16545                // It's implied that when a user requests installation, they want the app to be
16546                // installed and enabled.
16547                if (userId != UserHandle.USER_ALL) {
16548                    ps.setInstalled(true, userId);
16549                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16550                }
16551
16552                // When replacing an existing package, preserve the original install reason for all
16553                // users that had the package installed before.
16554                final Set<Integer> previousUserIds = new ArraySet<>();
16555                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16556                    final int installReasonCount = res.removedInfo.installReasons.size();
16557                    for (int i = 0; i < installReasonCount; i++) {
16558                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16559                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16560                        ps.setInstallReason(previousInstallReason, previousUserId);
16561                        previousUserIds.add(previousUserId);
16562                    }
16563                }
16564
16565                // Set install reason for users that are having the package newly installed.
16566                if (userId == UserHandle.USER_ALL) {
16567                    for (int currentUserId : sUserManager.getUserIds()) {
16568                        if (!previousUserIds.contains(currentUserId)) {
16569                            ps.setInstallReason(installReason, currentUserId);
16570                        }
16571                    }
16572                } else if (!previousUserIds.contains(userId)) {
16573                    ps.setInstallReason(installReason, userId);
16574                }
16575                mSettings.writeKernelMappingLPr(ps);
16576            }
16577            res.name = pkgName;
16578            res.uid = newPackage.applicationInfo.uid;
16579            res.pkg = newPackage;
16580            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16581            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16582            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16583            //to update install status
16584            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16585            mSettings.writeLPr();
16586            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16587        }
16588
16589        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16590    }
16591
16592    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16593        try {
16594            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16595            installPackageLI(args, res);
16596        } finally {
16597            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16598        }
16599    }
16600
16601    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16602        final int installFlags = args.installFlags;
16603        final String installerPackageName = args.installerPackageName;
16604        final String volumeUuid = args.volumeUuid;
16605        final File tmpPackageFile = new File(args.getCodePath());
16606        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16607        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16608                || (args.volumeUuid != null));
16609        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16610        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16611        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16612        boolean replace = false;
16613        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16614        if (args.move != null) {
16615            // moving a complete application; perform an initial scan on the new install location
16616            scanFlags |= SCAN_INITIAL;
16617        }
16618        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16619            scanFlags |= SCAN_DONT_KILL_APP;
16620        }
16621        if (instantApp) {
16622            scanFlags |= SCAN_AS_INSTANT_APP;
16623        }
16624        if (fullApp) {
16625            scanFlags |= SCAN_AS_FULL_APP;
16626        }
16627
16628        // Result object to be returned
16629        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16630
16631        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16632
16633        // Sanity check
16634        if (instantApp && (forwardLocked || onExternal)) {
16635            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16636                    + " external=" + onExternal);
16637            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16638            return;
16639        }
16640
16641        // Retrieve PackageSettings and parse package
16642        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16643                | PackageParser.PARSE_ENFORCE_CODE
16644                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16645                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16646                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16647                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16648        PackageParser pp = new PackageParser();
16649        pp.setSeparateProcesses(mSeparateProcesses);
16650        pp.setDisplayMetrics(mMetrics);
16651        pp.setCallback(mPackageParserCallback);
16652
16653        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16654        final PackageParser.Package pkg;
16655        try {
16656            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16657        } catch (PackageParserException e) {
16658            res.setError("Failed parse during installPackageLI", e);
16659            return;
16660        } finally {
16661            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16662        }
16663
16664        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
16665        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16666            Slog.w(TAG, "Instant app package " + pkg.packageName
16667                    + " does not target O, this will be a fatal error.");
16668            // STOPSHIP: Make this a fatal error
16669            pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O;
16670        }
16671        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
16672            Slog.w(TAG, "Instant app package " + pkg.packageName
16673                    + " does not target targetSandboxVersion 2, this will be a fatal error.");
16674            // STOPSHIP: Make this a fatal error
16675            pkg.applicationInfo.targetSandboxVersion = 2;
16676        }
16677
16678        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16679            // Static shared libraries have synthetic package names
16680            renameStaticSharedLibraryPackage(pkg);
16681
16682            // No static shared libs on external storage
16683            if (onExternal) {
16684                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16685                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16686                        "Packages declaring static-shared libs cannot be updated");
16687                return;
16688            }
16689        }
16690
16691        // If we are installing a clustered package add results for the children
16692        if (pkg.childPackages != null) {
16693            synchronized (mPackages) {
16694                final int childCount = pkg.childPackages.size();
16695                for (int i = 0; i < childCount; i++) {
16696                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16697                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16698                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16699                    childRes.pkg = childPkg;
16700                    childRes.name = childPkg.packageName;
16701                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16702                    if (childPs != null) {
16703                        childRes.origUsers = childPs.queryInstalledUsers(
16704                                sUserManager.getUserIds(), true);
16705                    }
16706                    if ((mPackages.containsKey(childPkg.packageName))) {
16707                        childRes.removedInfo = new PackageRemovedInfo();
16708                        childRes.removedInfo.removedPackage = childPkg.packageName;
16709                    }
16710                    if (res.addedChildPackages == null) {
16711                        res.addedChildPackages = new ArrayMap<>();
16712                    }
16713                    res.addedChildPackages.put(childPkg.packageName, childRes);
16714                }
16715            }
16716        }
16717
16718        // If package doesn't declare API override, mark that we have an install
16719        // time CPU ABI override.
16720        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16721            pkg.cpuAbiOverride = args.abiOverride;
16722        }
16723
16724        String pkgName = res.name = pkg.packageName;
16725        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16726            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16727                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16728                return;
16729            }
16730        }
16731
16732        try {
16733            // either use what we've been given or parse directly from the APK
16734            if (args.certificates != null) {
16735                try {
16736                    PackageParser.populateCertificates(pkg, args.certificates);
16737                } catch (PackageParserException e) {
16738                    // there was something wrong with the certificates we were given;
16739                    // try to pull them from the APK
16740                    PackageParser.collectCertificates(pkg, parseFlags);
16741                }
16742            } else {
16743                PackageParser.collectCertificates(pkg, parseFlags);
16744            }
16745        } catch (PackageParserException e) {
16746            res.setError("Failed collect during installPackageLI", e);
16747            return;
16748        }
16749
16750        // Get rid of all references to package scan path via parser.
16751        pp = null;
16752        String oldCodePath = null;
16753        boolean systemApp = false;
16754        synchronized (mPackages) {
16755            // Check if installing already existing package
16756            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16757                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16758                if (pkg.mOriginalPackages != null
16759                        && pkg.mOriginalPackages.contains(oldName)
16760                        && mPackages.containsKey(oldName)) {
16761                    // This package is derived from an original package,
16762                    // and this device has been updating from that original
16763                    // name.  We must continue using the original name, so
16764                    // rename the new package here.
16765                    pkg.setPackageName(oldName);
16766                    pkgName = pkg.packageName;
16767                    replace = true;
16768                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16769                            + oldName + " pkgName=" + pkgName);
16770                } else if (mPackages.containsKey(pkgName)) {
16771                    // This package, under its official name, already exists
16772                    // on the device; we should replace it.
16773                    replace = true;
16774                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16775                }
16776
16777                // Child packages are installed through the parent package
16778                if (pkg.parentPackage != null) {
16779                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16780                            "Package " + pkg.packageName + " is child of package "
16781                                    + pkg.parentPackage.parentPackage + ". Child packages "
16782                                    + "can be updated only through the parent package.");
16783                    return;
16784                }
16785
16786                if (replace) {
16787                    // Prevent apps opting out from runtime permissions
16788                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16789                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16790                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16791                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16792                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16793                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16794                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16795                                        + " doesn't support runtime permissions but the old"
16796                                        + " target SDK " + oldTargetSdk + " does.");
16797                        return;
16798                    }
16799                    // Prevent apps from downgrading their targetSandbox.
16800                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16801                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16802                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16803                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16804                                "Package " + pkg.packageName + " new target sandbox "
16805                                + newTargetSandbox + " is incompatible with the previous value of"
16806                                + oldTargetSandbox + ".");
16807                        return;
16808                    }
16809
16810                    // Prevent installing of child packages
16811                    if (oldPackage.parentPackage != null) {
16812                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16813                                "Package " + pkg.packageName + " is child of package "
16814                                        + oldPackage.parentPackage + ". Child packages "
16815                                        + "can be updated only through the parent package.");
16816                        return;
16817                    }
16818                }
16819            }
16820
16821            PackageSetting ps = mSettings.mPackages.get(pkgName);
16822            if (ps != null) {
16823                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16824
16825                // Static shared libs have same package with different versions where
16826                // we internally use a synthetic package name to allow multiple versions
16827                // of the same package, therefore we need to compare signatures against
16828                // the package setting for the latest library version.
16829                PackageSetting signatureCheckPs = ps;
16830                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16831                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16832                    if (libraryEntry != null) {
16833                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16834                    }
16835                }
16836
16837                // Quick sanity check that we're signed correctly if updating;
16838                // we'll check this again later when scanning, but we want to
16839                // bail early here before tripping over redefined permissions.
16840                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
16841                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
16842                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16843                                + pkg.packageName + " upgrade keys do not match the "
16844                                + "previously installed version");
16845                        return;
16846                    }
16847                } else {
16848                    try {
16849                        verifySignaturesLP(signatureCheckPs, pkg);
16850                    } catch (PackageManagerException e) {
16851                        res.setError(e.error, e.getMessage());
16852                        return;
16853                    }
16854                }
16855
16856                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16857                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16858                    systemApp = (ps.pkg.applicationInfo.flags &
16859                            ApplicationInfo.FLAG_SYSTEM) != 0;
16860                }
16861                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16862            }
16863
16864            int N = pkg.permissions.size();
16865            for (int i = N-1; i >= 0; i--) {
16866                PackageParser.Permission perm = pkg.permissions.get(i);
16867                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
16868
16869                // Don't allow anyone but the platform to define ephemeral permissions.
16870                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
16871                        && !PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16872                    Slog.w(TAG, "Package " + pkg.packageName
16873                            + " attempting to delcare ephemeral permission "
16874                            + perm.info.name + "; Removing ephemeral.");
16875                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
16876                }
16877                // Check whether the newly-scanned package wants to define an already-defined perm
16878                if (bp != null) {
16879                    // If the defining package is signed with our cert, it's okay.  This
16880                    // also includes the "updating the same package" case, of course.
16881                    // "updating same package" could also involve key-rotation.
16882                    final boolean sigsOk;
16883                    if (bp.sourcePackage.equals(pkg.packageName)
16884                            && (bp.packageSetting instanceof PackageSetting)
16885                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
16886                                    scanFlags))) {
16887                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
16888                    } else {
16889                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
16890                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16891                    }
16892                    if (!sigsOk) {
16893                        // If the owning package is the system itself, we log but allow
16894                        // install to proceed; we fail the install on all other permission
16895                        // redefinitions.
16896                        if (!bp.sourcePackage.equals("android")) {
16897                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16898                                    + pkg.packageName + " attempting to redeclare permission "
16899                                    + perm.info.name + " already owned by " + bp.sourcePackage);
16900                            res.origPermission = perm.info.name;
16901                            res.origPackage = bp.sourcePackage;
16902                            return;
16903                        } else {
16904                            Slog.w(TAG, "Package " + pkg.packageName
16905                                    + " attempting to redeclare system permission "
16906                                    + perm.info.name + "; ignoring new declaration");
16907                            pkg.permissions.remove(i);
16908                        }
16909                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16910                        // Prevent apps to change protection level to dangerous from any other
16911                        // type as this would allow a privilege escalation where an app adds a
16912                        // normal/signature permission in other app's group and later redefines
16913                        // it as dangerous leading to the group auto-grant.
16914                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16915                                == PermissionInfo.PROTECTION_DANGEROUS) {
16916                            if (bp != null && !bp.isRuntime()) {
16917                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16918                                        + "non-runtime permission " + perm.info.name
16919                                        + " to runtime; keeping old protection level");
16920                                perm.info.protectionLevel = bp.protectionLevel;
16921                            }
16922                        }
16923                    }
16924                }
16925            }
16926        }
16927
16928        if (systemApp) {
16929            if (onExternal) {
16930                // Abort update; system app can't be replaced with app on sdcard
16931                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16932                        "Cannot install updates to system apps on sdcard");
16933                return;
16934            } else if (instantApp) {
16935                // Abort update; system app can't be replaced with an instant app
16936                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16937                        "Cannot update a system app with an instant app");
16938                return;
16939            }
16940        }
16941
16942        if (args.move != null) {
16943            // We did an in-place move, so dex is ready to roll
16944            scanFlags |= SCAN_NO_DEX;
16945            scanFlags |= SCAN_MOVE;
16946
16947            synchronized (mPackages) {
16948                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16949                if (ps == null) {
16950                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16951                            "Missing settings for moved package " + pkgName);
16952                }
16953
16954                // We moved the entire application as-is, so bring over the
16955                // previously derived ABI information.
16956                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16957                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16958            }
16959
16960        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16961            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16962            scanFlags |= SCAN_NO_DEX;
16963
16964            try {
16965                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16966                    args.abiOverride : pkg.cpuAbiOverride);
16967                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
16968                        true /*extractLibs*/, mAppLib32InstallDir);
16969            } catch (PackageManagerException pme) {
16970                Slog.e(TAG, "Error deriving application ABI", pme);
16971                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16972                return;
16973            }
16974
16975            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16976            // Do not run PackageDexOptimizer through the local performDexOpt
16977            // method because `pkg` may not be in `mPackages` yet.
16978            //
16979            // Also, don't fail application installs if the dexopt step fails.
16980            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16981                    null /* instructionSets */, false /* checkProfiles */,
16982                    getCompilerFilterForReason(REASON_INSTALL),
16983                    getOrCreateCompilerPackageStats(pkg),
16984                    mDexManager.isUsedByOtherApps(pkg.packageName));
16985            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16986
16987            // Notify BackgroundDexOptService that the package has been changed.
16988            // If this is an update of a package which used to fail to compile,
16989            // BDOS will remove it from its blacklist.
16990            // TODO: Layering violation
16991            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
16992        }
16993
16994        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16995            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16996            return;
16997        }
16998
16999        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17000
17001        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17002                "installPackageLI")) {
17003            if (replace) {
17004                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17005                    // Static libs have a synthetic package name containing the version
17006                    // and cannot be updated as an update would get a new package name,
17007                    // unless this is the exact same version code which is useful for
17008                    // development.
17009                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17010                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
17011                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17012                                + "static-shared libs cannot be updated");
17013                        return;
17014                    }
17015                }
17016                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
17017                        installerPackageName, res, args.installReason);
17018            } else {
17019                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17020                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17021            }
17022        }
17023        synchronized (mPackages) {
17024            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17025            if (ps != null) {
17026                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17027                ps.setUpdateAvailable(false /*updateAvailable*/);
17028            }
17029
17030            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17031            for (int i = 0; i < childCount; i++) {
17032                PackageParser.Package childPkg = pkg.childPackages.get(i);
17033                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17034                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17035                if (childPs != null) {
17036                    childRes.newUsers = childPs.queryInstalledUsers(
17037                            sUserManager.getUserIds(), true);
17038                }
17039            }
17040
17041            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17042                updateSequenceNumberLP(pkgName, res.newUsers);
17043                updateInstantAppInstallerLocked();
17044            }
17045        }
17046    }
17047
17048    private void startIntentFilterVerifications(int userId, boolean replacing,
17049            PackageParser.Package pkg) {
17050        if (mIntentFilterVerifierComponent == null) {
17051            Slog.w(TAG, "No IntentFilter verification will not be done as "
17052                    + "there is no IntentFilterVerifier available!");
17053            return;
17054        }
17055
17056        final int verifierUid = getPackageUid(
17057                mIntentFilterVerifierComponent.getPackageName(),
17058                MATCH_DEBUG_TRIAGED_MISSING,
17059                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17060
17061        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17062        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17063        mHandler.sendMessage(msg);
17064
17065        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17066        for (int i = 0; i < childCount; i++) {
17067            PackageParser.Package childPkg = pkg.childPackages.get(i);
17068            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17069            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17070            mHandler.sendMessage(msg);
17071        }
17072    }
17073
17074    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17075            PackageParser.Package pkg) {
17076        int size = pkg.activities.size();
17077        if (size == 0) {
17078            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17079                    "No activity, so no need to verify any IntentFilter!");
17080            return;
17081        }
17082
17083        final boolean hasDomainURLs = hasDomainURLs(pkg);
17084        if (!hasDomainURLs) {
17085            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17086                    "No domain URLs, so no need to verify any IntentFilter!");
17087            return;
17088        }
17089
17090        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17091                + " if any IntentFilter from the " + size
17092                + " Activities needs verification ...");
17093
17094        int count = 0;
17095        final String packageName = pkg.packageName;
17096
17097        synchronized (mPackages) {
17098            // If this is a new install and we see that we've already run verification for this
17099            // package, we have nothing to do: it means the state was restored from backup.
17100            if (!replacing) {
17101                IntentFilterVerificationInfo ivi =
17102                        mSettings.getIntentFilterVerificationLPr(packageName);
17103                if (ivi != null) {
17104                    if (DEBUG_DOMAIN_VERIFICATION) {
17105                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17106                                + ivi.getStatusString());
17107                    }
17108                    return;
17109                }
17110            }
17111
17112            // If any filters need to be verified, then all need to be.
17113            boolean needToVerify = false;
17114            for (PackageParser.Activity a : pkg.activities) {
17115                for (ActivityIntentInfo filter : a.intents) {
17116                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17117                        if (DEBUG_DOMAIN_VERIFICATION) {
17118                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
17119                        }
17120                        needToVerify = true;
17121                        break;
17122                    }
17123                }
17124            }
17125
17126            if (needToVerify) {
17127                final int verificationId = mIntentFilterVerificationToken++;
17128                for (PackageParser.Activity a : pkg.activities) {
17129                    for (ActivityIntentInfo filter : a.intents) {
17130                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17131                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17132                                    "Verification needed for IntentFilter:" + filter.toString());
17133                            mIntentFilterVerifier.addOneIntentFilterVerification(
17134                                    verifierUid, userId, verificationId, filter, packageName);
17135                            count++;
17136                        }
17137                    }
17138                }
17139            }
17140        }
17141
17142        if (count > 0) {
17143            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17144                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17145                    +  " for userId:" + userId);
17146            mIntentFilterVerifier.startVerifications(userId);
17147        } else {
17148            if (DEBUG_DOMAIN_VERIFICATION) {
17149                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17150            }
17151        }
17152    }
17153
17154    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17155        final ComponentName cn  = filter.activity.getComponentName();
17156        final String packageName = cn.getPackageName();
17157
17158        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17159                packageName);
17160        if (ivi == null) {
17161            return true;
17162        }
17163        int status = ivi.getStatus();
17164        switch (status) {
17165            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17166            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17167                return true;
17168
17169            default:
17170                // Nothing to do
17171                return false;
17172        }
17173    }
17174
17175    private static boolean isMultiArch(ApplicationInfo info) {
17176        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17177    }
17178
17179    private static boolean isExternal(PackageParser.Package pkg) {
17180        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17181    }
17182
17183    private static boolean isExternal(PackageSetting ps) {
17184        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17185    }
17186
17187    private static boolean isSystemApp(PackageParser.Package pkg) {
17188        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17189    }
17190
17191    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17192        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17193    }
17194
17195    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17196        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17197    }
17198
17199    private static boolean isSystemApp(PackageSetting ps) {
17200        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17201    }
17202
17203    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17204        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17205    }
17206
17207    private int packageFlagsToInstallFlags(PackageSetting ps) {
17208        int installFlags = 0;
17209        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17210            // This existing package was an external ASEC install when we have
17211            // the external flag without a UUID
17212            installFlags |= PackageManager.INSTALL_EXTERNAL;
17213        }
17214        if (ps.isForwardLocked()) {
17215            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17216        }
17217        return installFlags;
17218    }
17219
17220    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17221        if (isExternal(pkg)) {
17222            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17223                return StorageManager.UUID_PRIMARY_PHYSICAL;
17224            } else {
17225                return pkg.volumeUuid;
17226            }
17227        } else {
17228            return StorageManager.UUID_PRIVATE_INTERNAL;
17229        }
17230    }
17231
17232    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17233        if (isExternal(pkg)) {
17234            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17235                return mSettings.getExternalVersion();
17236            } else {
17237                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17238            }
17239        } else {
17240            return mSettings.getInternalVersion();
17241        }
17242    }
17243
17244    private void deleteTempPackageFiles() {
17245        final FilenameFilter filter = new FilenameFilter() {
17246            public boolean accept(File dir, String name) {
17247                return name.startsWith("vmdl") && name.endsWith(".tmp");
17248            }
17249        };
17250        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17251            file.delete();
17252        }
17253    }
17254
17255    @Override
17256    public void deletePackageAsUser(String packageName, int versionCode,
17257            IPackageDeleteObserver observer, int userId, int flags) {
17258        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17259                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17260    }
17261
17262    @Override
17263    public void deletePackageVersioned(VersionedPackage versionedPackage,
17264            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17265        mContext.enforceCallingOrSelfPermission(
17266                android.Manifest.permission.DELETE_PACKAGES, null);
17267        Preconditions.checkNotNull(versionedPackage);
17268        Preconditions.checkNotNull(observer);
17269        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17270                PackageManager.VERSION_CODE_HIGHEST,
17271                Integer.MAX_VALUE, "versionCode must be >= -1");
17272
17273        final String packageName = versionedPackage.getPackageName();
17274        // TODO: We will change version code to long, so in the new API it is long
17275        final int versionCode = (int) versionedPackage.getVersionCode();
17276        final String internalPackageName;
17277        synchronized (mPackages) {
17278            // Normalize package name to handle renamed packages and static libs
17279            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17280                    // TODO: We will change version code to long, so in the new API it is long
17281                    (int) versionedPackage.getVersionCode());
17282        }
17283
17284        final int uid = Binder.getCallingUid();
17285        if (!isOrphaned(internalPackageName)
17286                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17287            try {
17288                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17289                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17290                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17291                observer.onUserActionRequired(intent);
17292            } catch (RemoteException re) {
17293            }
17294            return;
17295        }
17296        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17297        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17298        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17299            mContext.enforceCallingOrSelfPermission(
17300                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17301                    "deletePackage for user " + userId);
17302        }
17303
17304        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17305            try {
17306                observer.onPackageDeleted(packageName,
17307                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17308            } catch (RemoteException re) {
17309            }
17310            return;
17311        }
17312
17313        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17314            try {
17315                observer.onPackageDeleted(packageName,
17316                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17317            } catch (RemoteException re) {
17318            }
17319            return;
17320        }
17321
17322        if (DEBUG_REMOVE) {
17323            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17324                    + " deleteAllUsers: " + deleteAllUsers + " version="
17325                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17326                    ? "VERSION_CODE_HIGHEST" : versionCode));
17327        }
17328        // Queue up an async operation since the package deletion may take a little while.
17329        mHandler.post(new Runnable() {
17330            public void run() {
17331                mHandler.removeCallbacks(this);
17332                int returnCode;
17333                if (!deleteAllUsers) {
17334                    returnCode = deletePackageX(internalPackageName, versionCode,
17335                            userId, deleteFlags);
17336                } else {
17337                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17338                            internalPackageName, users);
17339                    // If nobody is blocking uninstall, proceed with delete for all users
17340                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17341                        returnCode = deletePackageX(internalPackageName, versionCode,
17342                                userId, deleteFlags);
17343                    } else {
17344                        // Otherwise uninstall individually for users with blockUninstalls=false
17345                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17346                        for (int userId : users) {
17347                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17348                                returnCode = deletePackageX(internalPackageName, versionCode,
17349                                        userId, userFlags);
17350                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17351                                    Slog.w(TAG, "Package delete failed for user " + userId
17352                                            + ", returnCode " + returnCode);
17353                                }
17354                            }
17355                        }
17356                        // The app has only been marked uninstalled for certain users.
17357                        // We still need to report that delete was blocked
17358                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17359                    }
17360                }
17361                try {
17362                    observer.onPackageDeleted(packageName, returnCode, null);
17363                } catch (RemoteException e) {
17364                    Log.i(TAG, "Observer no longer exists.");
17365                } //end catch
17366            } //end run
17367        });
17368    }
17369
17370    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17371        if (pkg.staticSharedLibName != null) {
17372            return pkg.manifestPackageName;
17373        }
17374        return pkg.packageName;
17375    }
17376
17377    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17378        // Handle renamed packages
17379        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17380        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17381
17382        // Is this a static library?
17383        SparseArray<SharedLibraryEntry> versionedLib =
17384                mStaticLibsByDeclaringPackage.get(packageName);
17385        if (versionedLib == null || versionedLib.size() <= 0) {
17386            return packageName;
17387        }
17388
17389        // Figure out which lib versions the caller can see
17390        SparseIntArray versionsCallerCanSee = null;
17391        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17392        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17393                && callingAppId != Process.ROOT_UID) {
17394            versionsCallerCanSee = new SparseIntArray();
17395            String libName = versionedLib.valueAt(0).info.getName();
17396            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17397            if (uidPackages != null) {
17398                for (String uidPackage : uidPackages) {
17399                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17400                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17401                    if (libIdx >= 0) {
17402                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17403                        versionsCallerCanSee.append(libVersion, libVersion);
17404                    }
17405                }
17406            }
17407        }
17408
17409        // Caller can see nothing - done
17410        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17411            return packageName;
17412        }
17413
17414        // Find the version the caller can see and the app version code
17415        SharedLibraryEntry highestVersion = null;
17416        final int versionCount = versionedLib.size();
17417        for (int i = 0; i < versionCount; i++) {
17418            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17419            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17420                    libEntry.info.getVersion()) < 0) {
17421                continue;
17422            }
17423            // TODO: We will change version code to long, so in the new API it is long
17424            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17425            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17426                if (libVersionCode == versionCode) {
17427                    return libEntry.apk;
17428                }
17429            } else if (highestVersion == null) {
17430                highestVersion = libEntry;
17431            } else if (libVersionCode  > highestVersion.info
17432                    .getDeclaringPackage().getVersionCode()) {
17433                highestVersion = libEntry;
17434            }
17435        }
17436
17437        if (highestVersion != null) {
17438            return highestVersion.apk;
17439        }
17440
17441        return packageName;
17442    }
17443
17444    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17445        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17446              || callingUid == Process.SYSTEM_UID) {
17447            return true;
17448        }
17449        final int callingUserId = UserHandle.getUserId(callingUid);
17450        // If the caller installed the pkgName, then allow it to silently uninstall.
17451        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17452            return true;
17453        }
17454
17455        // Allow package verifier to silently uninstall.
17456        if (mRequiredVerifierPackage != null &&
17457                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17458            return true;
17459        }
17460
17461        // Allow package uninstaller to silently uninstall.
17462        if (mRequiredUninstallerPackage != null &&
17463                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17464            return true;
17465        }
17466
17467        // Allow storage manager to silently uninstall.
17468        if (mStorageManagerPackage != null &&
17469                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17470            return true;
17471        }
17472        return false;
17473    }
17474
17475    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17476        int[] result = EMPTY_INT_ARRAY;
17477        for (int userId : userIds) {
17478            if (getBlockUninstallForUser(packageName, userId)) {
17479                result = ArrayUtils.appendInt(result, userId);
17480            }
17481        }
17482        return result;
17483    }
17484
17485    @Override
17486    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17487        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17488    }
17489
17490    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17491        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17492                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17493        try {
17494            if (dpm != null) {
17495                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17496                        /* callingUserOnly =*/ false);
17497                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17498                        : deviceOwnerComponentName.getPackageName();
17499                // Does the package contains the device owner?
17500                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17501                // this check is probably not needed, since DO should be registered as a device
17502                // admin on some user too. (Original bug for this: b/17657954)
17503                if (packageName.equals(deviceOwnerPackageName)) {
17504                    return true;
17505                }
17506                // Does it contain a device admin for any user?
17507                int[] users;
17508                if (userId == UserHandle.USER_ALL) {
17509                    users = sUserManager.getUserIds();
17510                } else {
17511                    users = new int[]{userId};
17512                }
17513                for (int i = 0; i < users.length; ++i) {
17514                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17515                        return true;
17516                    }
17517                }
17518            }
17519        } catch (RemoteException e) {
17520        }
17521        return false;
17522    }
17523
17524    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17525        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17526    }
17527
17528    /**
17529     *  This method is an internal method that could be get invoked either
17530     *  to delete an installed package or to clean up a failed installation.
17531     *  After deleting an installed package, a broadcast is sent to notify any
17532     *  listeners that the package has been removed. For cleaning up a failed
17533     *  installation, the broadcast is not necessary since the package's
17534     *  installation wouldn't have sent the initial broadcast either
17535     *  The key steps in deleting a package are
17536     *  deleting the package information in internal structures like mPackages,
17537     *  deleting the packages base directories through installd
17538     *  updating mSettings to reflect current status
17539     *  persisting settings for later use
17540     *  sending a broadcast if necessary
17541     */
17542    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17543        final PackageRemovedInfo info = new PackageRemovedInfo();
17544        final boolean res;
17545
17546        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17547                ? UserHandle.USER_ALL : userId;
17548
17549        if (isPackageDeviceAdmin(packageName, removeUser)) {
17550            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17551            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17552        }
17553
17554        PackageSetting uninstalledPs = null;
17555        PackageParser.Package pkg = null;
17556
17557        // for the uninstall-updates case and restricted profiles, remember the per-
17558        // user handle installed state
17559        int[] allUsers;
17560        synchronized (mPackages) {
17561            uninstalledPs = mSettings.mPackages.get(packageName);
17562            if (uninstalledPs == null) {
17563                Slog.w(TAG, "Not removing non-existent package " + packageName);
17564                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17565            }
17566
17567            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17568                    && uninstalledPs.versionCode != versionCode) {
17569                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17570                        + uninstalledPs.versionCode + " != " + versionCode);
17571                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17572            }
17573
17574            // Static shared libs can be declared by any package, so let us not
17575            // allow removing a package if it provides a lib others depend on.
17576            pkg = mPackages.get(packageName);
17577            if (pkg != null && pkg.staticSharedLibName != null) {
17578                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17579                        pkg.staticSharedLibVersion);
17580                if (libEntry != null) {
17581                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17582                            libEntry.info, 0, userId);
17583                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17584                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17585                                + " hosting lib " + libEntry.info.getName() + " version "
17586                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17587                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17588                    }
17589                }
17590            }
17591
17592            allUsers = sUserManager.getUserIds();
17593            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17594        }
17595
17596        final int freezeUser;
17597        if (isUpdatedSystemApp(uninstalledPs)
17598                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17599            // We're downgrading a system app, which will apply to all users, so
17600            // freeze them all during the downgrade
17601            freezeUser = UserHandle.USER_ALL;
17602        } else {
17603            freezeUser = removeUser;
17604        }
17605
17606        synchronized (mInstallLock) {
17607            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17608            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17609                    deleteFlags, "deletePackageX")) {
17610                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17611                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
17612            }
17613            synchronized (mPackages) {
17614                if (res) {
17615                    if (pkg != null) {
17616                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17617                    }
17618                    updateSequenceNumberLP(packageName, info.removedUsers);
17619                    updateInstantAppInstallerLocked();
17620                }
17621            }
17622        }
17623
17624        if (res) {
17625            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17626            info.sendPackageRemovedBroadcasts(killApp);
17627            info.sendSystemPackageUpdatedBroadcasts();
17628            info.sendSystemPackageAppearedBroadcasts();
17629        }
17630        // Force a gc here.
17631        Runtime.getRuntime().gc();
17632        // Delete the resources here after sending the broadcast to let
17633        // other processes clean up before deleting resources.
17634        if (info.args != null) {
17635            synchronized (mInstallLock) {
17636                info.args.doPostDeleteLI(true);
17637            }
17638        }
17639
17640        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17641    }
17642
17643    class PackageRemovedInfo {
17644        String removedPackage;
17645        int uid = -1;
17646        int removedAppId = -1;
17647        int[] origUsers;
17648        int[] removedUsers = null;
17649        SparseArray<Integer> installReasons;
17650        boolean isRemovedPackageSystemUpdate = false;
17651        boolean isUpdate;
17652        boolean dataRemoved;
17653        boolean removedForAllUsers;
17654        boolean isStaticSharedLib;
17655        // Clean up resources deleted packages.
17656        InstallArgs args = null;
17657        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17658        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17659
17660        void sendPackageRemovedBroadcasts(boolean killApp) {
17661            sendPackageRemovedBroadcastInternal(killApp);
17662            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17663            for (int i = 0; i < childCount; i++) {
17664                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17665                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17666            }
17667        }
17668
17669        void sendSystemPackageUpdatedBroadcasts() {
17670            if (isRemovedPackageSystemUpdate) {
17671                sendSystemPackageUpdatedBroadcastsInternal();
17672                final int childCount = (removedChildPackages != null)
17673                        ? removedChildPackages.size() : 0;
17674                for (int i = 0; i < childCount; i++) {
17675                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17676                    if (childInfo.isRemovedPackageSystemUpdate) {
17677                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17678                    }
17679                }
17680            }
17681        }
17682
17683        void sendSystemPackageAppearedBroadcasts() {
17684            final int packageCount = (appearedChildPackages != null)
17685                    ? appearedChildPackages.size() : 0;
17686            for (int i = 0; i < packageCount; i++) {
17687                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17688                sendPackageAddedForNewUsers(installedInfo.name, true,
17689                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17690            }
17691        }
17692
17693        private void sendSystemPackageUpdatedBroadcastsInternal() {
17694            Bundle extras = new Bundle(2);
17695            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17696            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17697            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
17698                    extras, 0, null, null, null);
17699            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
17700                    extras, 0, null, null, null);
17701            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
17702                    null, 0, removedPackage, null, null);
17703        }
17704
17705        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17706            // Don't send static shared library removal broadcasts as these
17707            // libs are visible only the the apps that depend on them an one
17708            // cannot remove the library if it has a dependency.
17709            if (isStaticSharedLib) {
17710                return;
17711            }
17712            Bundle extras = new Bundle(2);
17713            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17714            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17715            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17716            if (isUpdate || isRemovedPackageSystemUpdate) {
17717                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17718            }
17719            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17720            if (removedPackage != null) {
17721                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
17722                        extras, 0, null, null, removedUsers);
17723                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17724                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17725                            removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17726                            null, null, removedUsers);
17727                }
17728            }
17729            if (removedAppId >= 0) {
17730                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
17731                        removedUsers);
17732            }
17733        }
17734    }
17735
17736    /*
17737     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17738     * flag is not set, the data directory is removed as well.
17739     * make sure this flag is set for partially installed apps. If not its meaningless to
17740     * delete a partially installed application.
17741     */
17742    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17743            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17744        String packageName = ps.name;
17745        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17746        // Retrieve object to delete permissions for shared user later on
17747        final PackageParser.Package deletedPkg;
17748        final PackageSetting deletedPs;
17749        // reader
17750        synchronized (mPackages) {
17751            deletedPkg = mPackages.get(packageName);
17752            deletedPs = mSettings.mPackages.get(packageName);
17753            if (outInfo != null) {
17754                outInfo.removedPackage = packageName;
17755                outInfo.isStaticSharedLib = deletedPkg != null
17756                        && deletedPkg.staticSharedLibName != null;
17757                outInfo.removedUsers = deletedPs != null
17758                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
17759                        : null;
17760            }
17761        }
17762
17763        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
17764
17765        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17766            final PackageParser.Package resolvedPkg;
17767            if (deletedPkg != null) {
17768                resolvedPkg = deletedPkg;
17769            } else {
17770                // We don't have a parsed package when it lives on an ejected
17771                // adopted storage device, so fake something together
17772                resolvedPkg = new PackageParser.Package(ps.name);
17773                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17774            }
17775            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17776                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17777            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17778            if (outInfo != null) {
17779                outInfo.dataRemoved = true;
17780            }
17781            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17782        }
17783
17784        int removedAppId = -1;
17785
17786        // writer
17787        synchronized (mPackages) {
17788            boolean installedStateChanged = false;
17789            if (deletedPs != null) {
17790                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17791                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17792                    clearDefaultBrowserIfNeeded(packageName);
17793                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17794                    removedAppId = mSettings.removePackageLPw(packageName);
17795                    if (outInfo != null) {
17796                        outInfo.removedAppId = removedAppId;
17797                    }
17798                    updatePermissionsLPw(deletedPs.name, null, 0);
17799                    if (deletedPs.sharedUser != null) {
17800                        // Remove permissions associated with package. Since runtime
17801                        // permissions are per user we have to kill the removed package
17802                        // or packages running under the shared user of the removed
17803                        // package if revoking the permissions requested only by the removed
17804                        // package is successful and this causes a change in gids.
17805                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17806                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17807                                    userId);
17808                            if (userIdToKill == UserHandle.USER_ALL
17809                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17810                                // If gids changed for this user, kill all affected packages.
17811                                mHandler.post(new Runnable() {
17812                                    @Override
17813                                    public void run() {
17814                                        // This has to happen with no lock held.
17815                                        killApplication(deletedPs.name, deletedPs.appId,
17816                                                KILL_APP_REASON_GIDS_CHANGED);
17817                                    }
17818                                });
17819                                break;
17820                            }
17821                        }
17822                    }
17823                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17824                }
17825                // make sure to preserve per-user disabled state if this removal was just
17826                // a downgrade of a system app to the factory package
17827                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17828                    if (DEBUG_REMOVE) {
17829                        Slog.d(TAG, "Propagating install state across downgrade");
17830                    }
17831                    for (int userId : allUserHandles) {
17832                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17833                        if (DEBUG_REMOVE) {
17834                            Slog.d(TAG, "    user " + userId + " => " + installed);
17835                        }
17836                        if (installed != ps.getInstalled(userId)) {
17837                            installedStateChanged = true;
17838                        }
17839                        ps.setInstalled(installed, userId);
17840                    }
17841                }
17842            }
17843            // can downgrade to reader
17844            if (writeSettings) {
17845                // Save settings now
17846                mSettings.writeLPr();
17847            }
17848            if (installedStateChanged) {
17849                mSettings.writeKernelMappingLPr(ps);
17850            }
17851        }
17852        if (removedAppId != -1) {
17853            // A user ID was deleted here. Go through all users and remove it
17854            // from KeyStore.
17855            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17856        }
17857    }
17858
17859    static boolean locationIsPrivileged(File path) {
17860        try {
17861            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
17862                    .getCanonicalPath();
17863            return path.getCanonicalPath().startsWith(privilegedAppDir);
17864        } catch (IOException e) {
17865            Slog.e(TAG, "Unable to access code path " + path);
17866        }
17867        return false;
17868    }
17869
17870    /*
17871     * Tries to delete system package.
17872     */
17873    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17874            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17875            boolean writeSettings) {
17876        if (deletedPs.parentPackageName != null) {
17877            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17878            return false;
17879        }
17880
17881        final boolean applyUserRestrictions
17882                = (allUserHandles != null) && (outInfo.origUsers != null);
17883        final PackageSetting disabledPs;
17884        // Confirm if the system package has been updated
17885        // An updated system app can be deleted. This will also have to restore
17886        // the system pkg from system partition
17887        // reader
17888        synchronized (mPackages) {
17889            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17890        }
17891
17892        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17893                + " disabledPs=" + disabledPs);
17894
17895        if (disabledPs == null) {
17896            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17897            return false;
17898        } else if (DEBUG_REMOVE) {
17899            Slog.d(TAG, "Deleting system pkg from data partition");
17900        }
17901
17902        if (DEBUG_REMOVE) {
17903            if (applyUserRestrictions) {
17904                Slog.d(TAG, "Remembering install states:");
17905                for (int userId : allUserHandles) {
17906                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17907                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17908                }
17909            }
17910        }
17911
17912        // Delete the updated package
17913        outInfo.isRemovedPackageSystemUpdate = true;
17914        if (outInfo.removedChildPackages != null) {
17915            final int childCount = (deletedPs.childPackageNames != null)
17916                    ? deletedPs.childPackageNames.size() : 0;
17917            for (int i = 0; i < childCount; i++) {
17918                String childPackageName = deletedPs.childPackageNames.get(i);
17919                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17920                        .contains(childPackageName)) {
17921                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17922                            childPackageName);
17923                    if (childInfo != null) {
17924                        childInfo.isRemovedPackageSystemUpdate = true;
17925                    }
17926                }
17927            }
17928        }
17929
17930        if (disabledPs.versionCode < deletedPs.versionCode) {
17931            // Delete data for downgrades
17932            flags &= ~PackageManager.DELETE_KEEP_DATA;
17933        } else {
17934            // Preserve data by setting flag
17935            flags |= PackageManager.DELETE_KEEP_DATA;
17936        }
17937
17938        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17939                outInfo, writeSettings, disabledPs.pkg);
17940        if (!ret) {
17941            return false;
17942        }
17943
17944        // writer
17945        synchronized (mPackages) {
17946            // Reinstate the old system package
17947            enableSystemPackageLPw(disabledPs.pkg);
17948            // Remove any native libraries from the upgraded package.
17949            removeNativeBinariesLI(deletedPs);
17950        }
17951
17952        // Install the system package
17953        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17954        int parseFlags = mDefParseFlags
17955                | PackageParser.PARSE_MUST_BE_APK
17956                | PackageParser.PARSE_IS_SYSTEM
17957                | PackageParser.PARSE_IS_SYSTEM_DIR;
17958        if (locationIsPrivileged(disabledPs.codePath)) {
17959            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
17960        }
17961
17962        final PackageParser.Package newPkg;
17963        try {
17964            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
17965                0 /* currentTime */, null);
17966        } catch (PackageManagerException e) {
17967            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17968                    + e.getMessage());
17969            return false;
17970        }
17971
17972        try {
17973            // update shared libraries for the newly re-installed system package
17974            updateSharedLibrariesLPr(newPkg, null);
17975        } catch (PackageManagerException e) {
17976            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17977        }
17978
17979        prepareAppDataAfterInstallLIF(newPkg);
17980
17981        // writer
17982        synchronized (mPackages) {
17983            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
17984
17985            // Propagate the permissions state as we do not want to drop on the floor
17986            // runtime permissions. The update permissions method below will take
17987            // care of removing obsolete permissions and grant install permissions.
17988            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
17989            updatePermissionsLPw(newPkg.packageName, newPkg,
17990                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
17991
17992            if (applyUserRestrictions) {
17993                boolean installedStateChanged = false;
17994                if (DEBUG_REMOVE) {
17995                    Slog.d(TAG, "Propagating install state across reinstall");
17996                }
17997                for (int userId : allUserHandles) {
17998                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17999                    if (DEBUG_REMOVE) {
18000                        Slog.d(TAG, "    user " + userId + " => " + installed);
18001                    }
18002                    if (installed != ps.getInstalled(userId)) {
18003                        installedStateChanged = true;
18004                    }
18005                    ps.setInstalled(installed, userId);
18006
18007                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18008                }
18009                // Regardless of writeSettings we need to ensure that this restriction
18010                // state propagation is persisted
18011                mSettings.writeAllUsersPackageRestrictionsLPr();
18012                if (installedStateChanged) {
18013                    mSettings.writeKernelMappingLPr(ps);
18014                }
18015            }
18016            // can downgrade to reader here
18017            if (writeSettings) {
18018                mSettings.writeLPr();
18019            }
18020        }
18021        return true;
18022    }
18023
18024    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18025            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18026            PackageRemovedInfo outInfo, boolean writeSettings,
18027            PackageParser.Package replacingPackage) {
18028        synchronized (mPackages) {
18029            if (outInfo != null) {
18030                outInfo.uid = ps.appId;
18031            }
18032
18033            if (outInfo != null && outInfo.removedChildPackages != null) {
18034                final int childCount = (ps.childPackageNames != null)
18035                        ? ps.childPackageNames.size() : 0;
18036                for (int i = 0; i < childCount; i++) {
18037                    String childPackageName = ps.childPackageNames.get(i);
18038                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18039                    if (childPs == null) {
18040                        return false;
18041                    }
18042                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18043                            childPackageName);
18044                    if (childInfo != null) {
18045                        childInfo.uid = childPs.appId;
18046                    }
18047                }
18048            }
18049        }
18050
18051        // Delete package data from internal structures and also remove data if flag is set
18052        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18053
18054        // Delete the child packages data
18055        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18056        for (int i = 0; i < childCount; i++) {
18057            PackageSetting childPs;
18058            synchronized (mPackages) {
18059                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18060            }
18061            if (childPs != null) {
18062                PackageRemovedInfo childOutInfo = (outInfo != null
18063                        && outInfo.removedChildPackages != null)
18064                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18065                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18066                        && (replacingPackage != null
18067                        && !replacingPackage.hasChildPackage(childPs.name))
18068                        ? flags & ~DELETE_KEEP_DATA : flags;
18069                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18070                        deleteFlags, writeSettings);
18071            }
18072        }
18073
18074        // Delete application code and resources only for parent packages
18075        if (ps.parentPackageName == null) {
18076            if (deleteCodeAndResources && (outInfo != null)) {
18077                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18078                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18079                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18080            }
18081        }
18082
18083        return true;
18084    }
18085
18086    @Override
18087    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18088            int userId) {
18089        mContext.enforceCallingOrSelfPermission(
18090                android.Manifest.permission.DELETE_PACKAGES, null);
18091        synchronized (mPackages) {
18092            PackageSetting ps = mSettings.mPackages.get(packageName);
18093            if (ps == null) {
18094                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
18095                return false;
18096            }
18097            // Cannot block uninstall of static shared libs as they are
18098            // considered a part of the using app (emulating static linking).
18099            // Also static libs are installed always on internal storage.
18100            PackageParser.Package pkg = mPackages.get(packageName);
18101            if (pkg != null && pkg.staticSharedLibName != null) {
18102                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18103                        + " providing static shared library: " + pkg.staticSharedLibName);
18104                return false;
18105            }
18106            if (!ps.getInstalled(userId)) {
18107                // Can't block uninstall for an app that is not installed or enabled.
18108                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
18109                return false;
18110            }
18111            ps.setBlockUninstall(blockUninstall, userId);
18112            mSettings.writePackageRestrictionsLPr(userId);
18113        }
18114        return true;
18115    }
18116
18117    @Override
18118    public boolean getBlockUninstallForUser(String packageName, int userId) {
18119        synchronized (mPackages) {
18120            PackageSetting ps = mSettings.mPackages.get(packageName);
18121            if (ps == null) {
18122                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
18123                return false;
18124            }
18125            return ps.getBlockUninstall(userId);
18126        }
18127    }
18128
18129    @Override
18130    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18131        int callingUid = Binder.getCallingUid();
18132        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
18133            throw new SecurityException(
18134                    "setRequiredForSystemUser can only be run by the system or root");
18135        }
18136        synchronized (mPackages) {
18137            PackageSetting ps = mSettings.mPackages.get(packageName);
18138            if (ps == null) {
18139                Log.w(TAG, "Package doesn't exist: " + packageName);
18140                return false;
18141            }
18142            if (systemUserApp) {
18143                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18144            } else {
18145                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18146            }
18147            mSettings.writeLPr();
18148        }
18149        return true;
18150    }
18151
18152    /*
18153     * This method handles package deletion in general
18154     */
18155    private boolean deletePackageLIF(String packageName, UserHandle user,
18156            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18157            PackageRemovedInfo outInfo, boolean writeSettings,
18158            PackageParser.Package replacingPackage) {
18159        if (packageName == null) {
18160            Slog.w(TAG, "Attempt to delete null packageName.");
18161            return false;
18162        }
18163
18164        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18165
18166        PackageSetting ps;
18167        synchronized (mPackages) {
18168            ps = mSettings.mPackages.get(packageName);
18169            if (ps == null) {
18170                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18171                return false;
18172            }
18173
18174            if (ps.parentPackageName != null && (!isSystemApp(ps)
18175                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18176                if (DEBUG_REMOVE) {
18177                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18178                            + ((user == null) ? UserHandle.USER_ALL : user));
18179                }
18180                final int removedUserId = (user != null) ? user.getIdentifier()
18181                        : UserHandle.USER_ALL;
18182                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18183                    return false;
18184                }
18185                markPackageUninstalledForUserLPw(ps, user);
18186                scheduleWritePackageRestrictionsLocked(user);
18187                return true;
18188            }
18189        }
18190
18191        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18192                && user.getIdentifier() != UserHandle.USER_ALL)) {
18193            // The caller is asking that the package only be deleted for a single
18194            // user.  To do this, we just mark its uninstalled state and delete
18195            // its data. If this is a system app, we only allow this to happen if
18196            // they have set the special DELETE_SYSTEM_APP which requests different
18197            // semantics than normal for uninstalling system apps.
18198            markPackageUninstalledForUserLPw(ps, user);
18199
18200            if (!isSystemApp(ps)) {
18201                // Do not uninstall the APK if an app should be cached
18202                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18203                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18204                    // Other user still have this package installed, so all
18205                    // we need to do is clear this user's data and save that
18206                    // it is uninstalled.
18207                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18208                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18209                        return false;
18210                    }
18211                    scheduleWritePackageRestrictionsLocked(user);
18212                    return true;
18213                } else {
18214                    // We need to set it back to 'installed' so the uninstall
18215                    // broadcasts will be sent correctly.
18216                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18217                    ps.setInstalled(true, user.getIdentifier());
18218                    mSettings.writeKernelMappingLPr(ps);
18219                }
18220            } else {
18221                // This is a system app, so we assume that the
18222                // other users still have this package installed, so all
18223                // we need to do is clear this user's data and save that
18224                // it is uninstalled.
18225                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18226                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18227                    return false;
18228                }
18229                scheduleWritePackageRestrictionsLocked(user);
18230                return true;
18231            }
18232        }
18233
18234        // If we are deleting a composite package for all users, keep track
18235        // of result for each child.
18236        if (ps.childPackageNames != null && outInfo != null) {
18237            synchronized (mPackages) {
18238                final int childCount = ps.childPackageNames.size();
18239                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18240                for (int i = 0; i < childCount; i++) {
18241                    String childPackageName = ps.childPackageNames.get(i);
18242                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
18243                    childInfo.removedPackage = childPackageName;
18244                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18245                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18246                    if (childPs != null) {
18247                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18248                    }
18249                }
18250            }
18251        }
18252
18253        boolean ret = false;
18254        if (isSystemApp(ps)) {
18255            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18256            // When an updated system application is deleted we delete the existing resources
18257            // as well and fall back to existing code in system partition
18258            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18259        } else {
18260            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18261            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18262                    outInfo, writeSettings, replacingPackage);
18263        }
18264
18265        // Take a note whether we deleted the package for all users
18266        if (outInfo != null) {
18267            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18268            if (outInfo.removedChildPackages != null) {
18269                synchronized (mPackages) {
18270                    final int childCount = outInfo.removedChildPackages.size();
18271                    for (int i = 0; i < childCount; i++) {
18272                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18273                        if (childInfo != null) {
18274                            childInfo.removedForAllUsers = mPackages.get(
18275                                    childInfo.removedPackage) == null;
18276                        }
18277                    }
18278                }
18279            }
18280            // If we uninstalled an update to a system app there may be some
18281            // child packages that appeared as they are declared in the system
18282            // app but were not declared in the update.
18283            if (isSystemApp(ps)) {
18284                synchronized (mPackages) {
18285                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18286                    final int childCount = (updatedPs.childPackageNames != null)
18287                            ? updatedPs.childPackageNames.size() : 0;
18288                    for (int i = 0; i < childCount; i++) {
18289                        String childPackageName = updatedPs.childPackageNames.get(i);
18290                        if (outInfo.removedChildPackages == null
18291                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18292                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18293                            if (childPs == null) {
18294                                continue;
18295                            }
18296                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18297                            installRes.name = childPackageName;
18298                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18299                            installRes.pkg = mPackages.get(childPackageName);
18300                            installRes.uid = childPs.pkg.applicationInfo.uid;
18301                            if (outInfo.appearedChildPackages == null) {
18302                                outInfo.appearedChildPackages = new ArrayMap<>();
18303                            }
18304                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18305                        }
18306                    }
18307                }
18308            }
18309        }
18310
18311        return ret;
18312    }
18313
18314    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18315        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18316                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18317        for (int nextUserId : userIds) {
18318            if (DEBUG_REMOVE) {
18319                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18320            }
18321            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18322                    false /*installed*/,
18323                    true /*stopped*/,
18324                    true /*notLaunched*/,
18325                    false /*hidden*/,
18326                    false /*suspended*/,
18327                    false /*instantApp*/,
18328                    null /*lastDisableAppCaller*/,
18329                    null /*enabledComponents*/,
18330                    null /*disabledComponents*/,
18331                    false /*blockUninstall*/,
18332                    ps.readUserState(nextUserId).domainVerificationStatus,
18333                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18334        }
18335        mSettings.writeKernelMappingLPr(ps);
18336    }
18337
18338    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18339            PackageRemovedInfo outInfo) {
18340        final PackageParser.Package pkg;
18341        synchronized (mPackages) {
18342            pkg = mPackages.get(ps.name);
18343        }
18344
18345        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18346                : new int[] {userId};
18347        for (int nextUserId : userIds) {
18348            if (DEBUG_REMOVE) {
18349                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18350                        + nextUserId);
18351            }
18352
18353            destroyAppDataLIF(pkg, userId,
18354                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18355            destroyAppProfilesLIF(pkg, userId);
18356            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18357            schedulePackageCleaning(ps.name, nextUserId, false);
18358            synchronized (mPackages) {
18359                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18360                    scheduleWritePackageRestrictionsLocked(nextUserId);
18361                }
18362                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18363            }
18364        }
18365
18366        if (outInfo != null) {
18367            outInfo.removedPackage = ps.name;
18368            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18369            outInfo.removedAppId = ps.appId;
18370            outInfo.removedUsers = userIds;
18371        }
18372
18373        return true;
18374    }
18375
18376    private final class ClearStorageConnection implements ServiceConnection {
18377        IMediaContainerService mContainerService;
18378
18379        @Override
18380        public void onServiceConnected(ComponentName name, IBinder service) {
18381            synchronized (this) {
18382                mContainerService = IMediaContainerService.Stub
18383                        .asInterface(Binder.allowBlocking(service));
18384                notifyAll();
18385            }
18386        }
18387
18388        @Override
18389        public void onServiceDisconnected(ComponentName name) {
18390        }
18391    }
18392
18393    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18394        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18395
18396        final boolean mounted;
18397        if (Environment.isExternalStorageEmulated()) {
18398            mounted = true;
18399        } else {
18400            final String status = Environment.getExternalStorageState();
18401
18402            mounted = status.equals(Environment.MEDIA_MOUNTED)
18403                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18404        }
18405
18406        if (!mounted) {
18407            return;
18408        }
18409
18410        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18411        int[] users;
18412        if (userId == UserHandle.USER_ALL) {
18413            users = sUserManager.getUserIds();
18414        } else {
18415            users = new int[] { userId };
18416        }
18417        final ClearStorageConnection conn = new ClearStorageConnection();
18418        if (mContext.bindServiceAsUser(
18419                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18420            try {
18421                for (int curUser : users) {
18422                    long timeout = SystemClock.uptimeMillis() + 5000;
18423                    synchronized (conn) {
18424                        long now;
18425                        while (conn.mContainerService == null &&
18426                                (now = SystemClock.uptimeMillis()) < timeout) {
18427                            try {
18428                                conn.wait(timeout - now);
18429                            } catch (InterruptedException e) {
18430                            }
18431                        }
18432                    }
18433                    if (conn.mContainerService == null) {
18434                        return;
18435                    }
18436
18437                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18438                    clearDirectory(conn.mContainerService,
18439                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18440                    if (allData) {
18441                        clearDirectory(conn.mContainerService,
18442                                userEnv.buildExternalStorageAppDataDirs(packageName));
18443                        clearDirectory(conn.mContainerService,
18444                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18445                    }
18446                }
18447            } finally {
18448                mContext.unbindService(conn);
18449            }
18450        }
18451    }
18452
18453    @Override
18454    public void clearApplicationProfileData(String packageName) {
18455        enforceSystemOrRoot("Only the system can clear all profile data");
18456
18457        final PackageParser.Package pkg;
18458        synchronized (mPackages) {
18459            pkg = mPackages.get(packageName);
18460        }
18461
18462        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18463            synchronized (mInstallLock) {
18464                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18465            }
18466        }
18467    }
18468
18469    @Override
18470    public void clearApplicationUserData(final String packageName,
18471            final IPackageDataObserver observer, final int userId) {
18472        mContext.enforceCallingOrSelfPermission(
18473                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18474
18475        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18476                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18477
18478        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18479            throw new SecurityException("Cannot clear data for a protected package: "
18480                    + packageName);
18481        }
18482        // Queue up an async operation since the package deletion may take a little while.
18483        mHandler.post(new Runnable() {
18484            public void run() {
18485                mHandler.removeCallbacks(this);
18486                final boolean succeeded;
18487                try (PackageFreezer freezer = freezePackage(packageName,
18488                        "clearApplicationUserData")) {
18489                    synchronized (mInstallLock) {
18490                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18491                    }
18492                    clearExternalStorageDataSync(packageName, userId, true);
18493                    synchronized (mPackages) {
18494                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18495                                packageName, userId);
18496                    }
18497                }
18498                if (succeeded) {
18499                    // invoke DeviceStorageMonitor's update method to clear any notifications
18500                    DeviceStorageMonitorInternal dsm = LocalServices
18501                            .getService(DeviceStorageMonitorInternal.class);
18502                    if (dsm != null) {
18503                        dsm.checkMemory();
18504                    }
18505                }
18506                if(observer != null) {
18507                    try {
18508                        observer.onRemoveCompleted(packageName, succeeded);
18509                    } catch (RemoteException e) {
18510                        Log.i(TAG, "Observer no longer exists.");
18511                    }
18512                } //end if observer
18513            } //end run
18514        });
18515    }
18516
18517    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18518        if (packageName == null) {
18519            Slog.w(TAG, "Attempt to delete null packageName.");
18520            return false;
18521        }
18522
18523        // Try finding details about the requested package
18524        PackageParser.Package pkg;
18525        synchronized (mPackages) {
18526            pkg = mPackages.get(packageName);
18527            if (pkg == null) {
18528                final PackageSetting ps = mSettings.mPackages.get(packageName);
18529                if (ps != null) {
18530                    pkg = ps.pkg;
18531                }
18532            }
18533
18534            if (pkg == null) {
18535                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18536                return false;
18537            }
18538
18539            PackageSetting ps = (PackageSetting) pkg.mExtras;
18540            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18541        }
18542
18543        clearAppDataLIF(pkg, userId,
18544                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18545
18546        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18547        removeKeystoreDataIfNeeded(userId, appId);
18548
18549        UserManagerInternal umInternal = getUserManagerInternal();
18550        final int flags;
18551        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18552            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18553        } else if (umInternal.isUserRunning(userId)) {
18554            flags = StorageManager.FLAG_STORAGE_DE;
18555        } else {
18556            flags = 0;
18557        }
18558        prepareAppDataContentsLIF(pkg, userId, flags);
18559
18560        return true;
18561    }
18562
18563    /**
18564     * Reverts user permission state changes (permissions and flags) in
18565     * all packages for a given user.
18566     *
18567     * @param userId The device user for which to do a reset.
18568     */
18569    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18570        final int packageCount = mPackages.size();
18571        for (int i = 0; i < packageCount; i++) {
18572            PackageParser.Package pkg = mPackages.valueAt(i);
18573            PackageSetting ps = (PackageSetting) pkg.mExtras;
18574            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18575        }
18576    }
18577
18578    private void resetNetworkPolicies(int userId) {
18579        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18580    }
18581
18582    /**
18583     * Reverts user permission state changes (permissions and flags).
18584     *
18585     * @param ps The package for which to reset.
18586     * @param userId The device user for which to do a reset.
18587     */
18588    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18589            final PackageSetting ps, final int userId) {
18590        if (ps.pkg == null) {
18591            return;
18592        }
18593
18594        // These are flags that can change base on user actions.
18595        final int userSettableMask = FLAG_PERMISSION_USER_SET
18596                | FLAG_PERMISSION_USER_FIXED
18597                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18598                | FLAG_PERMISSION_REVIEW_REQUIRED;
18599
18600        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18601                | FLAG_PERMISSION_POLICY_FIXED;
18602
18603        boolean writeInstallPermissions = false;
18604        boolean writeRuntimePermissions = false;
18605
18606        final int permissionCount = ps.pkg.requestedPermissions.size();
18607        for (int i = 0; i < permissionCount; i++) {
18608            String permission = ps.pkg.requestedPermissions.get(i);
18609
18610            BasePermission bp = mSettings.mPermissions.get(permission);
18611            if (bp == null) {
18612                continue;
18613            }
18614
18615            // If shared user we just reset the state to which only this app contributed.
18616            if (ps.sharedUser != null) {
18617                boolean used = false;
18618                final int packageCount = ps.sharedUser.packages.size();
18619                for (int j = 0; j < packageCount; j++) {
18620                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18621                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18622                            && pkg.pkg.requestedPermissions.contains(permission)) {
18623                        used = true;
18624                        break;
18625                    }
18626                }
18627                if (used) {
18628                    continue;
18629                }
18630            }
18631
18632            PermissionsState permissionsState = ps.getPermissionsState();
18633
18634            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
18635
18636            // Always clear the user settable flags.
18637            final boolean hasInstallState = permissionsState.getInstallPermissionState(
18638                    bp.name) != null;
18639            // If permission review is enabled and this is a legacy app, mark the
18640            // permission as requiring a review as this is the initial state.
18641            int flags = 0;
18642            if (mPermissionReviewRequired
18643                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18644                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18645            }
18646            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18647                if (hasInstallState) {
18648                    writeInstallPermissions = true;
18649                } else {
18650                    writeRuntimePermissions = true;
18651                }
18652            }
18653
18654            // Below is only runtime permission handling.
18655            if (!bp.isRuntime()) {
18656                continue;
18657            }
18658
18659            // Never clobber system or policy.
18660            if ((oldFlags & policyOrSystemFlags) != 0) {
18661                continue;
18662            }
18663
18664            // If this permission was granted by default, make sure it is.
18665            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18666                if (permissionsState.grantRuntimePermission(bp, userId)
18667                        != PERMISSION_OPERATION_FAILURE) {
18668                    writeRuntimePermissions = true;
18669                }
18670            // If permission review is enabled the permissions for a legacy apps
18671            // are represented as constantly granted runtime ones, so don't revoke.
18672            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18673                // Otherwise, reset the permission.
18674                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18675                switch (revokeResult) {
18676                    case PERMISSION_OPERATION_SUCCESS:
18677                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18678                        writeRuntimePermissions = true;
18679                        final int appId = ps.appId;
18680                        mHandler.post(new Runnable() {
18681                            @Override
18682                            public void run() {
18683                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18684                            }
18685                        });
18686                    } break;
18687                }
18688            }
18689        }
18690
18691        // Synchronously write as we are taking permissions away.
18692        if (writeRuntimePermissions) {
18693            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18694        }
18695
18696        // Synchronously write as we are taking permissions away.
18697        if (writeInstallPermissions) {
18698            mSettings.writeLPr();
18699        }
18700    }
18701
18702    /**
18703     * Remove entries from the keystore daemon. Will only remove it if the
18704     * {@code appId} is valid.
18705     */
18706    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18707        if (appId < 0) {
18708            return;
18709        }
18710
18711        final KeyStore keyStore = KeyStore.getInstance();
18712        if (keyStore != null) {
18713            if (userId == UserHandle.USER_ALL) {
18714                for (final int individual : sUserManager.getUserIds()) {
18715                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18716                }
18717            } else {
18718                keyStore.clearUid(UserHandle.getUid(userId, appId));
18719            }
18720        } else {
18721            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18722        }
18723    }
18724
18725    @Override
18726    public void deleteApplicationCacheFiles(final String packageName,
18727            final IPackageDataObserver observer) {
18728        final int userId = UserHandle.getCallingUserId();
18729        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18730    }
18731
18732    @Override
18733    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18734            final IPackageDataObserver observer) {
18735        mContext.enforceCallingOrSelfPermission(
18736                android.Manifest.permission.DELETE_CACHE_FILES, null);
18737        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18738                /* requireFullPermission= */ true, /* checkShell= */ false,
18739                "delete application cache files");
18740
18741        final PackageParser.Package pkg;
18742        synchronized (mPackages) {
18743            pkg = mPackages.get(packageName);
18744        }
18745
18746        // Queue up an async operation since the package deletion may take a little while.
18747        mHandler.post(new Runnable() {
18748            public void run() {
18749                synchronized (mInstallLock) {
18750                    final int flags = StorageManager.FLAG_STORAGE_DE
18751                            | StorageManager.FLAG_STORAGE_CE;
18752                    // We're only clearing cache files, so we don't care if the
18753                    // app is unfrozen and still able to run
18754                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18755                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18756                }
18757                clearExternalStorageDataSync(packageName, userId, false);
18758                if (observer != null) {
18759                    try {
18760                        observer.onRemoveCompleted(packageName, true);
18761                    } catch (RemoteException e) {
18762                        Log.i(TAG, "Observer no longer exists.");
18763                    }
18764                }
18765            }
18766        });
18767    }
18768
18769    @Override
18770    public void getPackageSizeInfo(final String packageName, int userHandle,
18771            final IPackageStatsObserver observer) {
18772        throw new UnsupportedOperationException(
18773                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
18774    }
18775
18776    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18777        final PackageSetting ps;
18778        synchronized (mPackages) {
18779            ps = mSettings.mPackages.get(packageName);
18780            if (ps == null) {
18781                Slog.w(TAG, "Failed to find settings for " + packageName);
18782                return false;
18783            }
18784        }
18785
18786        final String[] packageNames = { packageName };
18787        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18788        final String[] codePaths = { ps.codePathString };
18789
18790        try {
18791            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18792                    ps.appId, ceDataInodes, codePaths, stats);
18793
18794            // For now, ignore code size of packages on system partition
18795            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18796                stats.codeSize = 0;
18797            }
18798
18799            // External clients expect these to be tracked separately
18800            stats.dataSize -= stats.cacheSize;
18801
18802        } catch (InstallerException e) {
18803            Slog.w(TAG, String.valueOf(e));
18804            return false;
18805        }
18806
18807        return true;
18808    }
18809
18810    private int getUidTargetSdkVersionLockedLPr(int uid) {
18811        Object obj = mSettings.getUserIdLPr(uid);
18812        if (obj instanceof SharedUserSetting) {
18813            final SharedUserSetting sus = (SharedUserSetting) obj;
18814            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18815            final Iterator<PackageSetting> it = sus.packages.iterator();
18816            while (it.hasNext()) {
18817                final PackageSetting ps = it.next();
18818                if (ps.pkg != null) {
18819                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18820                    if (v < vers) vers = v;
18821                }
18822            }
18823            return vers;
18824        } else if (obj instanceof PackageSetting) {
18825            final PackageSetting ps = (PackageSetting) obj;
18826            if (ps.pkg != null) {
18827                return ps.pkg.applicationInfo.targetSdkVersion;
18828            }
18829        }
18830        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18831    }
18832
18833    @Override
18834    public void addPreferredActivity(IntentFilter filter, int match,
18835            ComponentName[] set, ComponentName activity, int userId) {
18836        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18837                "Adding preferred");
18838    }
18839
18840    private void addPreferredActivityInternal(IntentFilter filter, int match,
18841            ComponentName[] set, ComponentName activity, boolean always, int userId,
18842            String opname) {
18843        // writer
18844        int callingUid = Binder.getCallingUid();
18845        enforceCrossUserPermission(callingUid, userId,
18846                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18847        if (filter.countActions() == 0) {
18848            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18849            return;
18850        }
18851        synchronized (mPackages) {
18852            if (mContext.checkCallingOrSelfPermission(
18853                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18854                    != PackageManager.PERMISSION_GRANTED) {
18855                if (getUidTargetSdkVersionLockedLPr(callingUid)
18856                        < Build.VERSION_CODES.FROYO) {
18857                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18858                            + callingUid);
18859                    return;
18860                }
18861                mContext.enforceCallingOrSelfPermission(
18862                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18863            }
18864
18865            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18866            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18867                    + userId + ":");
18868            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18869            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18870            scheduleWritePackageRestrictionsLocked(userId);
18871            postPreferredActivityChangedBroadcast(userId);
18872        }
18873    }
18874
18875    private void postPreferredActivityChangedBroadcast(int userId) {
18876        mHandler.post(() -> {
18877            final IActivityManager am = ActivityManager.getService();
18878            if (am == null) {
18879                return;
18880            }
18881
18882            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18883            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18884            try {
18885                am.broadcastIntent(null, intent, null, null,
18886                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18887                        null, false, false, userId);
18888            } catch (RemoteException e) {
18889            }
18890        });
18891    }
18892
18893    @Override
18894    public void replacePreferredActivity(IntentFilter filter, int match,
18895            ComponentName[] set, ComponentName activity, int userId) {
18896        if (filter.countActions() != 1) {
18897            throw new IllegalArgumentException(
18898                    "replacePreferredActivity expects filter to have only 1 action.");
18899        }
18900        if (filter.countDataAuthorities() != 0
18901                || filter.countDataPaths() != 0
18902                || filter.countDataSchemes() > 1
18903                || filter.countDataTypes() != 0) {
18904            throw new IllegalArgumentException(
18905                    "replacePreferredActivity expects filter to have no data authorities, " +
18906                    "paths, or types; and at most one scheme.");
18907        }
18908
18909        final int callingUid = Binder.getCallingUid();
18910        enforceCrossUserPermission(callingUid, userId,
18911                true /* requireFullPermission */, false /* checkShell */,
18912                "replace preferred activity");
18913        synchronized (mPackages) {
18914            if (mContext.checkCallingOrSelfPermission(
18915                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18916                    != PackageManager.PERMISSION_GRANTED) {
18917                if (getUidTargetSdkVersionLockedLPr(callingUid)
18918                        < Build.VERSION_CODES.FROYO) {
18919                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18920                            + Binder.getCallingUid());
18921                    return;
18922                }
18923                mContext.enforceCallingOrSelfPermission(
18924                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18925            }
18926
18927            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18928            if (pir != null) {
18929                // Get all of the existing entries that exactly match this filter.
18930                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18931                if (existing != null && existing.size() == 1) {
18932                    PreferredActivity cur = existing.get(0);
18933                    if (DEBUG_PREFERRED) {
18934                        Slog.i(TAG, "Checking replace of preferred:");
18935                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18936                        if (!cur.mPref.mAlways) {
18937                            Slog.i(TAG, "  -- CUR; not mAlways!");
18938                        } else {
18939                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18940                            Slog.i(TAG, "  -- CUR: mSet="
18941                                    + Arrays.toString(cur.mPref.mSetComponents));
18942                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18943                            Slog.i(TAG, "  -- NEW: mMatch="
18944                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18945                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18946                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18947                        }
18948                    }
18949                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18950                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18951                            && cur.mPref.sameSet(set)) {
18952                        // Setting the preferred activity to what it happens to be already
18953                        if (DEBUG_PREFERRED) {
18954                            Slog.i(TAG, "Replacing with same preferred activity "
18955                                    + cur.mPref.mShortComponent + " for user "
18956                                    + userId + ":");
18957                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18958                        }
18959                        return;
18960                    }
18961                }
18962
18963                if (existing != null) {
18964                    if (DEBUG_PREFERRED) {
18965                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
18966                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18967                    }
18968                    for (int i = 0; i < existing.size(); i++) {
18969                        PreferredActivity pa = existing.get(i);
18970                        if (DEBUG_PREFERRED) {
18971                            Slog.i(TAG, "Removing existing preferred activity "
18972                                    + pa.mPref.mComponent + ":");
18973                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
18974                        }
18975                        pir.removeFilter(pa);
18976                    }
18977                }
18978            }
18979            addPreferredActivityInternal(filter, match, set, activity, true, userId,
18980                    "Replacing preferred");
18981        }
18982    }
18983
18984    @Override
18985    public void clearPackagePreferredActivities(String packageName) {
18986        final int uid = Binder.getCallingUid();
18987        // writer
18988        synchronized (mPackages) {
18989            PackageParser.Package pkg = mPackages.get(packageName);
18990            if (pkg == null || pkg.applicationInfo.uid != uid) {
18991                if (mContext.checkCallingOrSelfPermission(
18992                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18993                        != PackageManager.PERMISSION_GRANTED) {
18994                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
18995                            < Build.VERSION_CODES.FROYO) {
18996                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
18997                                + Binder.getCallingUid());
18998                        return;
18999                    }
19000                    mContext.enforceCallingOrSelfPermission(
19001                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19002                }
19003            }
19004
19005            int user = UserHandle.getCallingUserId();
19006            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19007                scheduleWritePackageRestrictionsLocked(user);
19008            }
19009        }
19010    }
19011
19012    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19013    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19014        ArrayList<PreferredActivity> removed = null;
19015        boolean changed = false;
19016        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19017            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19018            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19019            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19020                continue;
19021            }
19022            Iterator<PreferredActivity> it = pir.filterIterator();
19023            while (it.hasNext()) {
19024                PreferredActivity pa = it.next();
19025                // Mark entry for removal only if it matches the package name
19026                // and the entry is of type "always".
19027                if (packageName == null ||
19028                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19029                                && pa.mPref.mAlways)) {
19030                    if (removed == null) {
19031                        removed = new ArrayList<PreferredActivity>();
19032                    }
19033                    removed.add(pa);
19034                }
19035            }
19036            if (removed != null) {
19037                for (int j=0; j<removed.size(); j++) {
19038                    PreferredActivity pa = removed.get(j);
19039                    pir.removeFilter(pa);
19040                }
19041                changed = true;
19042            }
19043        }
19044        if (changed) {
19045            postPreferredActivityChangedBroadcast(userId);
19046        }
19047        return changed;
19048    }
19049
19050    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19051    private void clearIntentFilterVerificationsLPw(int userId) {
19052        final int packageCount = mPackages.size();
19053        for (int i = 0; i < packageCount; i++) {
19054            PackageParser.Package pkg = mPackages.valueAt(i);
19055            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19056        }
19057    }
19058
19059    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19060    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19061        if (userId == UserHandle.USER_ALL) {
19062            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19063                    sUserManager.getUserIds())) {
19064                for (int oneUserId : sUserManager.getUserIds()) {
19065                    scheduleWritePackageRestrictionsLocked(oneUserId);
19066                }
19067            }
19068        } else {
19069            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19070                scheduleWritePackageRestrictionsLocked(userId);
19071            }
19072        }
19073    }
19074
19075    void clearDefaultBrowserIfNeeded(String packageName) {
19076        for (int oneUserId : sUserManager.getUserIds()) {
19077            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
19078            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
19079            if (packageName.equals(defaultBrowserPackageName)) {
19080                setDefaultBrowserPackageName(null, oneUserId);
19081            }
19082        }
19083    }
19084
19085    @Override
19086    public void resetApplicationPreferences(int userId) {
19087        mContext.enforceCallingOrSelfPermission(
19088                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19089        final long identity = Binder.clearCallingIdentity();
19090        // writer
19091        try {
19092            synchronized (mPackages) {
19093                clearPackagePreferredActivitiesLPw(null, userId);
19094                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19095                // TODO: We have to reset the default SMS and Phone. This requires
19096                // significant refactoring to keep all default apps in the package
19097                // manager (cleaner but more work) or have the services provide
19098                // callbacks to the package manager to request a default app reset.
19099                applyFactoryDefaultBrowserLPw(userId);
19100                clearIntentFilterVerificationsLPw(userId);
19101                primeDomainVerificationsLPw(userId);
19102                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19103                scheduleWritePackageRestrictionsLocked(userId);
19104            }
19105            resetNetworkPolicies(userId);
19106        } finally {
19107            Binder.restoreCallingIdentity(identity);
19108        }
19109    }
19110
19111    @Override
19112    public int getPreferredActivities(List<IntentFilter> outFilters,
19113            List<ComponentName> outActivities, String packageName) {
19114
19115        int num = 0;
19116        final int userId = UserHandle.getCallingUserId();
19117        // reader
19118        synchronized (mPackages) {
19119            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19120            if (pir != null) {
19121                final Iterator<PreferredActivity> it = pir.filterIterator();
19122                while (it.hasNext()) {
19123                    final PreferredActivity pa = it.next();
19124                    if (packageName == null
19125                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19126                                    && pa.mPref.mAlways)) {
19127                        if (outFilters != null) {
19128                            outFilters.add(new IntentFilter(pa));
19129                        }
19130                        if (outActivities != null) {
19131                            outActivities.add(pa.mPref.mComponent);
19132                        }
19133                    }
19134                }
19135            }
19136        }
19137
19138        return num;
19139    }
19140
19141    @Override
19142    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19143            int userId) {
19144        int callingUid = Binder.getCallingUid();
19145        if (callingUid != Process.SYSTEM_UID) {
19146            throw new SecurityException(
19147                    "addPersistentPreferredActivity can only be run by the system");
19148        }
19149        if (filter.countActions() == 0) {
19150            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19151            return;
19152        }
19153        synchronized (mPackages) {
19154            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19155                    ":");
19156            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19157            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19158                    new PersistentPreferredActivity(filter, activity));
19159            scheduleWritePackageRestrictionsLocked(userId);
19160            postPreferredActivityChangedBroadcast(userId);
19161        }
19162    }
19163
19164    @Override
19165    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19166        int callingUid = Binder.getCallingUid();
19167        if (callingUid != Process.SYSTEM_UID) {
19168            throw new SecurityException(
19169                    "clearPackagePersistentPreferredActivities can only be run by the system");
19170        }
19171        ArrayList<PersistentPreferredActivity> removed = null;
19172        boolean changed = false;
19173        synchronized (mPackages) {
19174            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19175                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19176                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19177                        .valueAt(i);
19178                if (userId != thisUserId) {
19179                    continue;
19180                }
19181                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19182                while (it.hasNext()) {
19183                    PersistentPreferredActivity ppa = it.next();
19184                    // Mark entry for removal only if it matches the package name.
19185                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19186                        if (removed == null) {
19187                            removed = new ArrayList<PersistentPreferredActivity>();
19188                        }
19189                        removed.add(ppa);
19190                    }
19191                }
19192                if (removed != null) {
19193                    for (int j=0; j<removed.size(); j++) {
19194                        PersistentPreferredActivity ppa = removed.get(j);
19195                        ppir.removeFilter(ppa);
19196                    }
19197                    changed = true;
19198                }
19199            }
19200
19201            if (changed) {
19202                scheduleWritePackageRestrictionsLocked(userId);
19203                postPreferredActivityChangedBroadcast(userId);
19204            }
19205        }
19206    }
19207
19208    /**
19209     * Common machinery for picking apart a restored XML blob and passing
19210     * it to a caller-supplied functor to be applied to the running system.
19211     */
19212    private void restoreFromXml(XmlPullParser parser, int userId,
19213            String expectedStartTag, BlobXmlRestorer functor)
19214            throws IOException, XmlPullParserException {
19215        int type;
19216        while ((type = parser.next()) != XmlPullParser.START_TAG
19217                && type != XmlPullParser.END_DOCUMENT) {
19218        }
19219        if (type != XmlPullParser.START_TAG) {
19220            // oops didn't find a start tag?!
19221            if (DEBUG_BACKUP) {
19222                Slog.e(TAG, "Didn't find start tag during restore");
19223            }
19224            return;
19225        }
19226Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19227        // this is supposed to be TAG_PREFERRED_BACKUP
19228        if (!expectedStartTag.equals(parser.getName())) {
19229            if (DEBUG_BACKUP) {
19230                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19231            }
19232            return;
19233        }
19234
19235        // skip interfering stuff, then we're aligned with the backing implementation
19236        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19237Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19238        functor.apply(parser, userId);
19239    }
19240
19241    private interface BlobXmlRestorer {
19242        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19243    }
19244
19245    /**
19246     * Non-Binder method, support for the backup/restore mechanism: write the
19247     * full set of preferred activities in its canonical XML format.  Returns the
19248     * XML output as a byte array, or null if there is none.
19249     */
19250    @Override
19251    public byte[] getPreferredActivityBackup(int userId) {
19252        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19253            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19254        }
19255
19256        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19257        try {
19258            final XmlSerializer serializer = new FastXmlSerializer();
19259            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19260            serializer.startDocument(null, true);
19261            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19262
19263            synchronized (mPackages) {
19264                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19265            }
19266
19267            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19268            serializer.endDocument();
19269            serializer.flush();
19270        } catch (Exception e) {
19271            if (DEBUG_BACKUP) {
19272                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19273            }
19274            return null;
19275        }
19276
19277        return dataStream.toByteArray();
19278    }
19279
19280    @Override
19281    public void restorePreferredActivities(byte[] backup, int userId) {
19282        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19283            throw new SecurityException("Only the system may call restorePreferredActivities()");
19284        }
19285
19286        try {
19287            final XmlPullParser parser = Xml.newPullParser();
19288            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19289            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19290                    new BlobXmlRestorer() {
19291                        @Override
19292                        public void apply(XmlPullParser parser, int userId)
19293                                throws XmlPullParserException, IOException {
19294                            synchronized (mPackages) {
19295                                mSettings.readPreferredActivitiesLPw(parser, userId);
19296                            }
19297                        }
19298                    } );
19299        } catch (Exception e) {
19300            if (DEBUG_BACKUP) {
19301                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19302            }
19303        }
19304    }
19305
19306    /**
19307     * Non-Binder method, support for the backup/restore mechanism: write the
19308     * default browser (etc) settings in its canonical XML format.  Returns the default
19309     * browser XML representation as a byte array, or null if there is none.
19310     */
19311    @Override
19312    public byte[] getDefaultAppsBackup(int userId) {
19313        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19314            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19315        }
19316
19317        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19318        try {
19319            final XmlSerializer serializer = new FastXmlSerializer();
19320            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19321            serializer.startDocument(null, true);
19322            serializer.startTag(null, TAG_DEFAULT_APPS);
19323
19324            synchronized (mPackages) {
19325                mSettings.writeDefaultAppsLPr(serializer, userId);
19326            }
19327
19328            serializer.endTag(null, TAG_DEFAULT_APPS);
19329            serializer.endDocument();
19330            serializer.flush();
19331        } catch (Exception e) {
19332            if (DEBUG_BACKUP) {
19333                Slog.e(TAG, "Unable to write default apps for backup", e);
19334            }
19335            return null;
19336        }
19337
19338        return dataStream.toByteArray();
19339    }
19340
19341    @Override
19342    public void restoreDefaultApps(byte[] backup, int userId) {
19343        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19344            throw new SecurityException("Only the system may call restoreDefaultApps()");
19345        }
19346
19347        try {
19348            final XmlPullParser parser = Xml.newPullParser();
19349            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19350            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19351                    new BlobXmlRestorer() {
19352                        @Override
19353                        public void apply(XmlPullParser parser, int userId)
19354                                throws XmlPullParserException, IOException {
19355                            synchronized (mPackages) {
19356                                mSettings.readDefaultAppsLPw(parser, userId);
19357                            }
19358                        }
19359                    } );
19360        } catch (Exception e) {
19361            if (DEBUG_BACKUP) {
19362                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19363            }
19364        }
19365    }
19366
19367    @Override
19368    public byte[] getIntentFilterVerificationBackup(int userId) {
19369        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19370            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19371        }
19372
19373        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19374        try {
19375            final XmlSerializer serializer = new FastXmlSerializer();
19376            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19377            serializer.startDocument(null, true);
19378            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19379
19380            synchronized (mPackages) {
19381                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19382            }
19383
19384            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19385            serializer.endDocument();
19386            serializer.flush();
19387        } catch (Exception e) {
19388            if (DEBUG_BACKUP) {
19389                Slog.e(TAG, "Unable to write default apps for backup", e);
19390            }
19391            return null;
19392        }
19393
19394        return dataStream.toByteArray();
19395    }
19396
19397    @Override
19398    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19399        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19400            throw new SecurityException("Only the system may call restorePreferredActivities()");
19401        }
19402
19403        try {
19404            final XmlPullParser parser = Xml.newPullParser();
19405            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19406            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19407                    new BlobXmlRestorer() {
19408                        @Override
19409                        public void apply(XmlPullParser parser, int userId)
19410                                throws XmlPullParserException, IOException {
19411                            synchronized (mPackages) {
19412                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19413                                mSettings.writeLPr();
19414                            }
19415                        }
19416                    } );
19417        } catch (Exception e) {
19418            if (DEBUG_BACKUP) {
19419                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19420            }
19421        }
19422    }
19423
19424    @Override
19425    public byte[] getPermissionGrantBackup(int userId) {
19426        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19427            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19428        }
19429
19430        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19431        try {
19432            final XmlSerializer serializer = new FastXmlSerializer();
19433            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19434            serializer.startDocument(null, true);
19435            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19436
19437            synchronized (mPackages) {
19438                serializeRuntimePermissionGrantsLPr(serializer, userId);
19439            }
19440
19441            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19442            serializer.endDocument();
19443            serializer.flush();
19444        } catch (Exception e) {
19445            if (DEBUG_BACKUP) {
19446                Slog.e(TAG, "Unable to write default apps for backup", e);
19447            }
19448            return null;
19449        }
19450
19451        return dataStream.toByteArray();
19452    }
19453
19454    @Override
19455    public void restorePermissionGrants(byte[] backup, int userId) {
19456        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19457            throw new SecurityException("Only the system may call restorePermissionGrants()");
19458        }
19459
19460        try {
19461            final XmlPullParser parser = Xml.newPullParser();
19462            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19463            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19464                    new BlobXmlRestorer() {
19465                        @Override
19466                        public void apply(XmlPullParser parser, int userId)
19467                                throws XmlPullParserException, IOException {
19468                            synchronized (mPackages) {
19469                                processRestoredPermissionGrantsLPr(parser, userId);
19470                            }
19471                        }
19472                    } );
19473        } catch (Exception e) {
19474            if (DEBUG_BACKUP) {
19475                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19476            }
19477        }
19478    }
19479
19480    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19481            throws IOException {
19482        serializer.startTag(null, TAG_ALL_GRANTS);
19483
19484        final int N = mSettings.mPackages.size();
19485        for (int i = 0; i < N; i++) {
19486            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19487            boolean pkgGrantsKnown = false;
19488
19489            PermissionsState packagePerms = ps.getPermissionsState();
19490
19491            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19492                final int grantFlags = state.getFlags();
19493                // only look at grants that are not system/policy fixed
19494                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19495                    final boolean isGranted = state.isGranted();
19496                    // And only back up the user-twiddled state bits
19497                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19498                        final String packageName = mSettings.mPackages.keyAt(i);
19499                        if (!pkgGrantsKnown) {
19500                            serializer.startTag(null, TAG_GRANT);
19501                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19502                            pkgGrantsKnown = true;
19503                        }
19504
19505                        final boolean userSet =
19506                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19507                        final boolean userFixed =
19508                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19509                        final boolean revoke =
19510                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19511
19512                        serializer.startTag(null, TAG_PERMISSION);
19513                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19514                        if (isGranted) {
19515                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19516                        }
19517                        if (userSet) {
19518                            serializer.attribute(null, ATTR_USER_SET, "true");
19519                        }
19520                        if (userFixed) {
19521                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19522                        }
19523                        if (revoke) {
19524                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19525                        }
19526                        serializer.endTag(null, TAG_PERMISSION);
19527                    }
19528                }
19529            }
19530
19531            if (pkgGrantsKnown) {
19532                serializer.endTag(null, TAG_GRANT);
19533            }
19534        }
19535
19536        serializer.endTag(null, TAG_ALL_GRANTS);
19537    }
19538
19539    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19540            throws XmlPullParserException, IOException {
19541        String pkgName = null;
19542        int outerDepth = parser.getDepth();
19543        int type;
19544        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19545                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19546            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19547                continue;
19548            }
19549
19550            final String tagName = parser.getName();
19551            if (tagName.equals(TAG_GRANT)) {
19552                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19553                if (DEBUG_BACKUP) {
19554                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19555                }
19556            } else if (tagName.equals(TAG_PERMISSION)) {
19557
19558                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19559                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19560
19561                int newFlagSet = 0;
19562                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19563                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19564                }
19565                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19566                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19567                }
19568                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19569                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19570                }
19571                if (DEBUG_BACKUP) {
19572                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
19573                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
19574                }
19575                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19576                if (ps != null) {
19577                    // Already installed so we apply the grant immediately
19578                    if (DEBUG_BACKUP) {
19579                        Slog.v(TAG, "        + already installed; applying");
19580                    }
19581                    PermissionsState perms = ps.getPermissionsState();
19582                    BasePermission bp = mSettings.mPermissions.get(permName);
19583                    if (bp != null) {
19584                        if (isGranted) {
19585                            perms.grantRuntimePermission(bp, userId);
19586                        }
19587                        if (newFlagSet != 0) {
19588                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19589                        }
19590                    }
19591                } else {
19592                    // Need to wait for post-restore install to apply the grant
19593                    if (DEBUG_BACKUP) {
19594                        Slog.v(TAG, "        - not yet installed; saving for later");
19595                    }
19596                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19597                            isGranted, newFlagSet, userId);
19598                }
19599            } else {
19600                PackageManagerService.reportSettingsProblem(Log.WARN,
19601                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19602                XmlUtils.skipCurrentTag(parser);
19603            }
19604        }
19605
19606        scheduleWriteSettingsLocked();
19607        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19608    }
19609
19610    @Override
19611    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19612            int sourceUserId, int targetUserId, int flags) {
19613        mContext.enforceCallingOrSelfPermission(
19614                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19615        int callingUid = Binder.getCallingUid();
19616        enforceOwnerRights(ownerPackage, callingUid);
19617        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19618        if (intentFilter.countActions() == 0) {
19619            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19620            return;
19621        }
19622        synchronized (mPackages) {
19623            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19624                    ownerPackage, targetUserId, flags);
19625            CrossProfileIntentResolver resolver =
19626                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19627            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19628            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19629            if (existing != null) {
19630                int size = existing.size();
19631                for (int i = 0; i < size; i++) {
19632                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19633                        return;
19634                    }
19635                }
19636            }
19637            resolver.addFilter(newFilter);
19638            scheduleWritePackageRestrictionsLocked(sourceUserId);
19639        }
19640    }
19641
19642    @Override
19643    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19644        mContext.enforceCallingOrSelfPermission(
19645                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19646        int callingUid = Binder.getCallingUid();
19647        enforceOwnerRights(ownerPackage, callingUid);
19648        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19649        synchronized (mPackages) {
19650            CrossProfileIntentResolver resolver =
19651                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19652            ArraySet<CrossProfileIntentFilter> set =
19653                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19654            for (CrossProfileIntentFilter filter : set) {
19655                if (filter.getOwnerPackage().equals(ownerPackage)) {
19656                    resolver.removeFilter(filter);
19657                }
19658            }
19659            scheduleWritePackageRestrictionsLocked(sourceUserId);
19660        }
19661    }
19662
19663    // Enforcing that callingUid is owning pkg on userId
19664    private void enforceOwnerRights(String pkg, int callingUid) {
19665        // The system owns everything.
19666        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19667            return;
19668        }
19669        int callingUserId = UserHandle.getUserId(callingUid);
19670        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19671        if (pi == null) {
19672            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19673                    + callingUserId);
19674        }
19675        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19676            throw new SecurityException("Calling uid " + callingUid
19677                    + " does not own package " + pkg);
19678        }
19679    }
19680
19681    @Override
19682    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19683        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19684    }
19685
19686    /**
19687     * Report the 'Home' activity which is currently set as "always use this one". If non is set
19688     * then reports the most likely home activity or null if there are more than one.
19689     */
19690    public ComponentName getDefaultHomeActivity(int userId) {
19691        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
19692        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
19693        if (cn != null) {
19694            return cn;
19695        }
19696
19697        // Find the launcher with the highest priority and return that component if there are no
19698        // other home activity with the same priority.
19699        int lastPriority = Integer.MIN_VALUE;
19700        ComponentName lastComponent = null;
19701        final int size = allHomeCandidates.size();
19702        for (int i = 0; i < size; i++) {
19703            final ResolveInfo ri = allHomeCandidates.get(i);
19704            if (ri.priority > lastPriority) {
19705                lastComponent = ri.activityInfo.getComponentName();
19706                lastPriority = ri.priority;
19707            } else if (ri.priority == lastPriority) {
19708                // Two components found with same priority.
19709                lastComponent = null;
19710            }
19711        }
19712        return lastComponent;
19713    }
19714
19715    private Intent getHomeIntent() {
19716        Intent intent = new Intent(Intent.ACTION_MAIN);
19717        intent.addCategory(Intent.CATEGORY_HOME);
19718        intent.addCategory(Intent.CATEGORY_DEFAULT);
19719        return intent;
19720    }
19721
19722    private IntentFilter getHomeFilter() {
19723        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19724        filter.addCategory(Intent.CATEGORY_HOME);
19725        filter.addCategory(Intent.CATEGORY_DEFAULT);
19726        return filter;
19727    }
19728
19729    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19730            int userId) {
19731        Intent intent  = getHomeIntent();
19732        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19733                PackageManager.GET_META_DATA, userId);
19734        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19735                true, false, false, userId);
19736
19737        allHomeCandidates.clear();
19738        if (list != null) {
19739            for (ResolveInfo ri : list) {
19740                allHomeCandidates.add(ri);
19741            }
19742        }
19743        return (preferred == null || preferred.activityInfo == null)
19744                ? null
19745                : new ComponentName(preferred.activityInfo.packageName,
19746                        preferred.activityInfo.name);
19747    }
19748
19749    @Override
19750    public void setHomeActivity(ComponentName comp, int userId) {
19751        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19752        getHomeActivitiesAsUser(homeActivities, userId);
19753
19754        boolean found = false;
19755
19756        final int size = homeActivities.size();
19757        final ComponentName[] set = new ComponentName[size];
19758        for (int i = 0; i < size; i++) {
19759            final ResolveInfo candidate = homeActivities.get(i);
19760            final ActivityInfo info = candidate.activityInfo;
19761            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19762            set[i] = activityName;
19763            if (!found && activityName.equals(comp)) {
19764                found = true;
19765            }
19766        }
19767        if (!found) {
19768            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19769                    + userId);
19770        }
19771        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19772                set, comp, userId);
19773    }
19774
19775    private @Nullable String getSetupWizardPackageName() {
19776        final Intent intent = new Intent(Intent.ACTION_MAIN);
19777        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19778
19779        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19780                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19781                        | MATCH_DISABLED_COMPONENTS,
19782                UserHandle.myUserId());
19783        if (matches.size() == 1) {
19784            return matches.get(0).getComponentInfo().packageName;
19785        } else {
19786            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19787                    + ": matches=" + matches);
19788            return null;
19789        }
19790    }
19791
19792    private @Nullable String getStorageManagerPackageName() {
19793        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19794
19795        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19796                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19797                        | MATCH_DISABLED_COMPONENTS,
19798                UserHandle.myUserId());
19799        if (matches.size() == 1) {
19800            return matches.get(0).getComponentInfo().packageName;
19801        } else {
19802            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19803                    + matches.size() + ": matches=" + matches);
19804            return null;
19805        }
19806    }
19807
19808    @Override
19809    public void setApplicationEnabledSetting(String appPackageName,
19810            int newState, int flags, int userId, String callingPackage) {
19811        if (!sUserManager.exists(userId)) return;
19812        if (callingPackage == null) {
19813            callingPackage = Integer.toString(Binder.getCallingUid());
19814        }
19815        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19816    }
19817
19818    @Override
19819    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
19820        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
19821        synchronized (mPackages) {
19822            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
19823            if (pkgSetting != null) {
19824                pkgSetting.setUpdateAvailable(updateAvailable);
19825            }
19826        }
19827    }
19828
19829    @Override
19830    public void setComponentEnabledSetting(ComponentName componentName,
19831            int newState, int flags, int userId) {
19832        if (!sUserManager.exists(userId)) return;
19833        setEnabledSetting(componentName.getPackageName(),
19834                componentName.getClassName(), newState, flags, userId, null);
19835    }
19836
19837    private void setEnabledSetting(final String packageName, String className, int newState,
19838            final int flags, int userId, String callingPackage) {
19839        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19840              || newState == COMPONENT_ENABLED_STATE_ENABLED
19841              || newState == COMPONENT_ENABLED_STATE_DISABLED
19842              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19843              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19844            throw new IllegalArgumentException("Invalid new component state: "
19845                    + newState);
19846        }
19847        PackageSetting pkgSetting;
19848        final int uid = Binder.getCallingUid();
19849        final int permission;
19850        if (uid == Process.SYSTEM_UID) {
19851            permission = PackageManager.PERMISSION_GRANTED;
19852        } else {
19853            permission = mContext.checkCallingOrSelfPermission(
19854                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19855        }
19856        enforceCrossUserPermission(uid, userId,
19857                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19858        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19859        boolean sendNow = false;
19860        boolean isApp = (className == null);
19861        String componentName = isApp ? packageName : className;
19862        int packageUid = -1;
19863        ArrayList<String> components;
19864
19865        // writer
19866        synchronized (mPackages) {
19867            pkgSetting = mSettings.mPackages.get(packageName);
19868            if (pkgSetting == null) {
19869                if (className == null) {
19870                    throw new IllegalArgumentException("Unknown package: " + packageName);
19871                }
19872                throw new IllegalArgumentException(
19873                        "Unknown component: " + packageName + "/" + className);
19874            }
19875        }
19876
19877        // Limit who can change which apps
19878        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
19879            // Don't allow apps that don't have permission to modify other apps
19880            if (!allowedByPermission) {
19881                throw new SecurityException(
19882                        "Permission Denial: attempt to change component state from pid="
19883                        + Binder.getCallingPid()
19884                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
19885            }
19886            // Don't allow changing protected packages.
19887            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19888                throw new SecurityException("Cannot disable a protected package: " + packageName);
19889            }
19890        }
19891
19892        synchronized (mPackages) {
19893            if (uid == Process.SHELL_UID
19894                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19895                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19896                // unless it is a test package.
19897                int oldState = pkgSetting.getEnabled(userId);
19898                if (className == null
19899                    &&
19900                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19901                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19902                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19903                    &&
19904                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19905                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
19906                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19907                    // ok
19908                } else {
19909                    throw new SecurityException(
19910                            "Shell cannot change component state for " + packageName + "/"
19911                            + className + " to " + newState);
19912                }
19913            }
19914            if (className == null) {
19915                // We're dealing with an application/package level state change
19916                if (pkgSetting.getEnabled(userId) == newState) {
19917                    // Nothing to do
19918                    return;
19919                }
19920                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19921                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
19922                    // Don't care about who enables an app.
19923                    callingPackage = null;
19924                }
19925                pkgSetting.setEnabled(newState, userId, callingPackage);
19926                // pkgSetting.pkg.mSetEnabled = newState;
19927            } else {
19928                // We're dealing with a component level state change
19929                // First, verify that this is a valid class name.
19930                PackageParser.Package pkg = pkgSetting.pkg;
19931                if (pkg == null || !pkg.hasComponentClassName(className)) {
19932                    if (pkg != null &&
19933                            pkg.applicationInfo.targetSdkVersion >=
19934                                    Build.VERSION_CODES.JELLY_BEAN) {
19935                        throw new IllegalArgumentException("Component class " + className
19936                                + " does not exist in " + packageName);
19937                    } else {
19938                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
19939                                + className + " does not exist in " + packageName);
19940                    }
19941                }
19942                switch (newState) {
19943                case COMPONENT_ENABLED_STATE_ENABLED:
19944                    if (!pkgSetting.enableComponentLPw(className, userId)) {
19945                        return;
19946                    }
19947                    break;
19948                case COMPONENT_ENABLED_STATE_DISABLED:
19949                    if (!pkgSetting.disableComponentLPw(className, userId)) {
19950                        return;
19951                    }
19952                    break;
19953                case COMPONENT_ENABLED_STATE_DEFAULT:
19954                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
19955                        return;
19956                    }
19957                    break;
19958                default:
19959                    Slog.e(TAG, "Invalid new component state: " + newState);
19960                    return;
19961                }
19962            }
19963            scheduleWritePackageRestrictionsLocked(userId);
19964            updateSequenceNumberLP(packageName, new int[] { userId });
19965            final long callingId = Binder.clearCallingIdentity();
19966            try {
19967                updateInstantAppInstallerLocked();
19968            } finally {
19969                Binder.restoreCallingIdentity(callingId);
19970            }
19971            components = mPendingBroadcasts.get(userId, packageName);
19972            final boolean newPackage = components == null;
19973            if (newPackage) {
19974                components = new ArrayList<String>();
19975            }
19976            if (!components.contains(componentName)) {
19977                components.add(componentName);
19978            }
19979            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
19980                sendNow = true;
19981                // Purge entry from pending broadcast list if another one exists already
19982                // since we are sending one right away.
19983                mPendingBroadcasts.remove(userId, packageName);
19984            } else {
19985                if (newPackage) {
19986                    mPendingBroadcasts.put(userId, packageName, components);
19987                }
19988                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
19989                    // Schedule a message
19990                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
19991                }
19992            }
19993        }
19994
19995        long callingId = Binder.clearCallingIdentity();
19996        try {
19997            if (sendNow) {
19998                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
19999                sendPackageChangedBroadcast(packageName,
20000                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20001            }
20002        } finally {
20003            Binder.restoreCallingIdentity(callingId);
20004        }
20005    }
20006
20007    @Override
20008    public void flushPackageRestrictionsAsUser(int userId) {
20009        if (!sUserManager.exists(userId)) {
20010            return;
20011        }
20012        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20013                false /* checkShell */, "flushPackageRestrictions");
20014        synchronized (mPackages) {
20015            mSettings.writePackageRestrictionsLPr(userId);
20016            mDirtyUsers.remove(userId);
20017            if (mDirtyUsers.isEmpty()) {
20018                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20019            }
20020        }
20021    }
20022
20023    private void sendPackageChangedBroadcast(String packageName,
20024            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20025        if (DEBUG_INSTALL)
20026            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20027                    + componentNames);
20028        Bundle extras = new Bundle(4);
20029        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20030        String nameList[] = new String[componentNames.size()];
20031        componentNames.toArray(nameList);
20032        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20033        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20034        extras.putInt(Intent.EXTRA_UID, packageUid);
20035        // If this is not reporting a change of the overall package, then only send it
20036        // to registered receivers.  We don't want to launch a swath of apps for every
20037        // little component state change.
20038        final int flags = !componentNames.contains(packageName)
20039                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20040        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20041                new int[] {UserHandle.getUserId(packageUid)});
20042    }
20043
20044    @Override
20045    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20046        if (!sUserManager.exists(userId)) return;
20047        final int uid = Binder.getCallingUid();
20048        final int permission = mContext.checkCallingOrSelfPermission(
20049                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20050        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20051        enforceCrossUserPermission(uid, userId,
20052                true /* requireFullPermission */, true /* checkShell */, "stop package");
20053        // writer
20054        synchronized (mPackages) {
20055            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20056                    allowedByPermission, uid, userId)) {
20057                scheduleWritePackageRestrictionsLocked(userId);
20058            }
20059        }
20060    }
20061
20062    @Override
20063    public String getInstallerPackageName(String packageName) {
20064        // reader
20065        synchronized (mPackages) {
20066            return mSettings.getInstallerPackageNameLPr(packageName);
20067        }
20068    }
20069
20070    public boolean isOrphaned(String packageName) {
20071        // reader
20072        synchronized (mPackages) {
20073            return mSettings.isOrphaned(packageName);
20074        }
20075    }
20076
20077    @Override
20078    public int getApplicationEnabledSetting(String packageName, int userId) {
20079        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20080        int uid = Binder.getCallingUid();
20081        enforceCrossUserPermission(uid, userId,
20082                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20083        // reader
20084        synchronized (mPackages) {
20085            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20086        }
20087    }
20088
20089    @Override
20090    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
20091        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20092        int uid = Binder.getCallingUid();
20093        enforceCrossUserPermission(uid, userId,
20094                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
20095        // reader
20096        synchronized (mPackages) {
20097            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
20098        }
20099    }
20100
20101    @Override
20102    public void enterSafeMode() {
20103        enforceSystemOrRoot("Only the system can request entering safe mode");
20104
20105        if (!mSystemReady) {
20106            mSafeMode = true;
20107        }
20108    }
20109
20110    @Override
20111    public void systemReady() {
20112        mSystemReady = true;
20113
20114        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20115        // disabled after already being started.
20116        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20117                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20118
20119        // Read the compatibilty setting when the system is ready.
20120        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20121                mContext.getContentResolver(),
20122                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20123        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20124        if (DEBUG_SETTINGS) {
20125            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20126        }
20127
20128        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20129
20130        synchronized (mPackages) {
20131            // Verify that all of the preferred activity components actually
20132            // exist.  It is possible for applications to be updated and at
20133            // that point remove a previously declared activity component that
20134            // had been set as a preferred activity.  We try to clean this up
20135            // the next time we encounter that preferred activity, but it is
20136            // possible for the user flow to never be able to return to that
20137            // situation so here we do a sanity check to make sure we haven't
20138            // left any junk around.
20139            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20140            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20141                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20142                removed.clear();
20143                for (PreferredActivity pa : pir.filterSet()) {
20144                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20145                        removed.add(pa);
20146                    }
20147                }
20148                if (removed.size() > 0) {
20149                    for (int r=0; r<removed.size(); r++) {
20150                        PreferredActivity pa = removed.get(r);
20151                        Slog.w(TAG, "Removing dangling preferred activity: "
20152                                + pa.mPref.mComponent);
20153                        pir.removeFilter(pa);
20154                    }
20155                    mSettings.writePackageRestrictionsLPr(
20156                            mSettings.mPreferredActivities.keyAt(i));
20157                }
20158            }
20159
20160            for (int userId : UserManagerService.getInstance().getUserIds()) {
20161                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20162                    grantPermissionsUserIds = ArrayUtils.appendInt(
20163                            grantPermissionsUserIds, userId);
20164                }
20165            }
20166        }
20167        sUserManager.systemReady();
20168
20169        // If we upgraded grant all default permissions before kicking off.
20170        for (int userId : grantPermissionsUserIds) {
20171            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20172        }
20173
20174        // If we did not grant default permissions, we preload from this the
20175        // default permission exceptions lazily to ensure we don't hit the
20176        // disk on a new user creation.
20177        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20178            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20179        }
20180
20181        // Kick off any messages waiting for system ready
20182        if (mPostSystemReadyMessages != null) {
20183            for (Message msg : mPostSystemReadyMessages) {
20184                msg.sendToTarget();
20185            }
20186            mPostSystemReadyMessages = null;
20187        }
20188
20189        // Watch for external volumes that come and go over time
20190        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20191        storage.registerListener(mStorageListener);
20192
20193        mInstallerService.systemReady();
20194        mPackageDexOptimizer.systemReady();
20195
20196        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20197                StorageManagerInternal.class);
20198        StorageManagerInternal.addExternalStoragePolicy(
20199                new StorageManagerInternal.ExternalStorageMountPolicy() {
20200            @Override
20201            public int getMountMode(int uid, String packageName) {
20202                if (Process.isIsolated(uid)) {
20203                    return Zygote.MOUNT_EXTERNAL_NONE;
20204                }
20205                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20206                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20207                }
20208                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20209                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20210                }
20211                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20212                    return Zygote.MOUNT_EXTERNAL_READ;
20213                }
20214                return Zygote.MOUNT_EXTERNAL_WRITE;
20215            }
20216
20217            @Override
20218            public boolean hasExternalStorage(int uid, String packageName) {
20219                return true;
20220            }
20221        });
20222
20223        // Now that we're mostly running, clean up stale users and apps
20224        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20225        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20226
20227        if (mPrivappPermissionsViolations != null) {
20228            Slog.wtf(TAG,"Signature|privileged permissions not in "
20229                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
20230            mPrivappPermissionsViolations = null;
20231        }
20232    }
20233
20234    public void waitForAppDataPrepared() {
20235        if (mPrepareAppDataFuture == null) {
20236            return;
20237        }
20238        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20239        mPrepareAppDataFuture = null;
20240    }
20241
20242    @Override
20243    public boolean isSafeMode() {
20244        return mSafeMode;
20245    }
20246
20247    @Override
20248    public boolean hasSystemUidErrors() {
20249        return mHasSystemUidErrors;
20250    }
20251
20252    static String arrayToString(int[] array) {
20253        StringBuffer buf = new StringBuffer(128);
20254        buf.append('[');
20255        if (array != null) {
20256            for (int i=0; i<array.length; i++) {
20257                if (i > 0) buf.append(", ");
20258                buf.append(array[i]);
20259            }
20260        }
20261        buf.append(']');
20262        return buf.toString();
20263    }
20264
20265    static class DumpState {
20266        public static final int DUMP_LIBS = 1 << 0;
20267        public static final int DUMP_FEATURES = 1 << 1;
20268        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20269        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20270        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20271        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20272        public static final int DUMP_PERMISSIONS = 1 << 6;
20273        public static final int DUMP_PACKAGES = 1 << 7;
20274        public static final int DUMP_SHARED_USERS = 1 << 8;
20275        public static final int DUMP_MESSAGES = 1 << 9;
20276        public static final int DUMP_PROVIDERS = 1 << 10;
20277        public static final int DUMP_VERIFIERS = 1 << 11;
20278        public static final int DUMP_PREFERRED = 1 << 12;
20279        public static final int DUMP_PREFERRED_XML = 1 << 13;
20280        public static final int DUMP_KEYSETS = 1 << 14;
20281        public static final int DUMP_VERSION = 1 << 15;
20282        public static final int DUMP_INSTALLS = 1 << 16;
20283        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20284        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20285        public static final int DUMP_FROZEN = 1 << 19;
20286        public static final int DUMP_DEXOPT = 1 << 20;
20287        public static final int DUMP_COMPILER_STATS = 1 << 21;
20288        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
20289
20290        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20291
20292        private int mTypes;
20293
20294        private int mOptions;
20295
20296        private boolean mTitlePrinted;
20297
20298        private SharedUserSetting mSharedUser;
20299
20300        public boolean isDumping(int type) {
20301            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20302                return true;
20303            }
20304
20305            return (mTypes & type) != 0;
20306        }
20307
20308        public void setDump(int type) {
20309            mTypes |= type;
20310        }
20311
20312        public boolean isOptionEnabled(int option) {
20313            return (mOptions & option) != 0;
20314        }
20315
20316        public void setOptionEnabled(int option) {
20317            mOptions |= option;
20318        }
20319
20320        public boolean onTitlePrinted() {
20321            final boolean printed = mTitlePrinted;
20322            mTitlePrinted = true;
20323            return printed;
20324        }
20325
20326        public boolean getTitlePrinted() {
20327            return mTitlePrinted;
20328        }
20329
20330        public void setTitlePrinted(boolean enabled) {
20331            mTitlePrinted = enabled;
20332        }
20333
20334        public SharedUserSetting getSharedUser() {
20335            return mSharedUser;
20336        }
20337
20338        public void setSharedUser(SharedUserSetting user) {
20339            mSharedUser = user;
20340        }
20341    }
20342
20343    @Override
20344    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20345            FileDescriptor err, String[] args, ShellCallback callback,
20346            ResultReceiver resultReceiver) {
20347        (new PackageManagerShellCommand(this)).exec(
20348                this, in, out, err, args, callback, resultReceiver);
20349    }
20350
20351    @Override
20352    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20353        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20354
20355        DumpState dumpState = new DumpState();
20356        boolean fullPreferred = false;
20357        boolean checkin = false;
20358
20359        String packageName = null;
20360        ArraySet<String> permissionNames = null;
20361
20362        int opti = 0;
20363        while (opti < args.length) {
20364            String opt = args[opti];
20365            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20366                break;
20367            }
20368            opti++;
20369
20370            if ("-a".equals(opt)) {
20371                // Right now we only know how to print all.
20372            } else if ("-h".equals(opt)) {
20373                pw.println("Package manager dump options:");
20374                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20375                pw.println("    --checkin: dump for a checkin");
20376                pw.println("    -f: print details of intent filters");
20377                pw.println("    -h: print this help");
20378                pw.println("  cmd may be one of:");
20379                pw.println("    l[ibraries]: list known shared libraries");
20380                pw.println("    f[eatures]: list device features");
20381                pw.println("    k[eysets]: print known keysets");
20382                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20383                pw.println("    perm[issions]: dump permissions");
20384                pw.println("    permission [name ...]: dump declaration and use of given permission");
20385                pw.println("    pref[erred]: print preferred package settings");
20386                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20387                pw.println("    prov[iders]: dump content providers");
20388                pw.println("    p[ackages]: dump installed packages");
20389                pw.println("    s[hared-users]: dump shared user IDs");
20390                pw.println("    m[essages]: print collected runtime messages");
20391                pw.println("    v[erifiers]: print package verifier info");
20392                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20393                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20394                pw.println("    version: print database version info");
20395                pw.println("    write: write current settings now");
20396                pw.println("    installs: details about install sessions");
20397                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20398                pw.println("    dexopt: dump dexopt state");
20399                pw.println("    compiler-stats: dump compiler statistics");
20400                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20401                pw.println("    <package.name>: info about given package");
20402                return;
20403            } else if ("--checkin".equals(opt)) {
20404                checkin = true;
20405            } else if ("-f".equals(opt)) {
20406                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20407            } else if ("--proto".equals(opt)) {
20408                dumpProto(fd);
20409                return;
20410            } else {
20411                pw.println("Unknown argument: " + opt + "; use -h for help");
20412            }
20413        }
20414
20415        // Is the caller requesting to dump a particular piece of data?
20416        if (opti < args.length) {
20417            String cmd = args[opti];
20418            opti++;
20419            // Is this a package name?
20420            if ("android".equals(cmd) || cmd.contains(".")) {
20421                packageName = cmd;
20422                // When dumping a single package, we always dump all of its
20423                // filter information since the amount of data will be reasonable.
20424                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20425            } else if ("check-permission".equals(cmd)) {
20426                if (opti >= args.length) {
20427                    pw.println("Error: check-permission missing permission argument");
20428                    return;
20429                }
20430                String perm = args[opti];
20431                opti++;
20432                if (opti >= args.length) {
20433                    pw.println("Error: check-permission missing package argument");
20434                    return;
20435                }
20436
20437                String pkg = args[opti];
20438                opti++;
20439                int user = UserHandle.getUserId(Binder.getCallingUid());
20440                if (opti < args.length) {
20441                    try {
20442                        user = Integer.parseInt(args[opti]);
20443                    } catch (NumberFormatException e) {
20444                        pw.println("Error: check-permission user argument is not a number: "
20445                                + args[opti]);
20446                        return;
20447                    }
20448                }
20449
20450                // Normalize package name to handle renamed packages and static libs
20451                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20452
20453                pw.println(checkPermission(perm, pkg, user));
20454                return;
20455            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20456                dumpState.setDump(DumpState.DUMP_LIBS);
20457            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20458                dumpState.setDump(DumpState.DUMP_FEATURES);
20459            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20460                if (opti >= args.length) {
20461                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20462                            | DumpState.DUMP_SERVICE_RESOLVERS
20463                            | DumpState.DUMP_RECEIVER_RESOLVERS
20464                            | DumpState.DUMP_CONTENT_RESOLVERS);
20465                } else {
20466                    while (opti < args.length) {
20467                        String name = args[opti];
20468                        if ("a".equals(name) || "activity".equals(name)) {
20469                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20470                        } else if ("s".equals(name) || "service".equals(name)) {
20471                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20472                        } else if ("r".equals(name) || "receiver".equals(name)) {
20473                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20474                        } else if ("c".equals(name) || "content".equals(name)) {
20475                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20476                        } else {
20477                            pw.println("Error: unknown resolver table type: " + name);
20478                            return;
20479                        }
20480                        opti++;
20481                    }
20482                }
20483            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20484                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20485            } else if ("permission".equals(cmd)) {
20486                if (opti >= args.length) {
20487                    pw.println("Error: permission requires permission name");
20488                    return;
20489                }
20490                permissionNames = new ArraySet<>();
20491                while (opti < args.length) {
20492                    permissionNames.add(args[opti]);
20493                    opti++;
20494                }
20495                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20496                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20497            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20498                dumpState.setDump(DumpState.DUMP_PREFERRED);
20499            } else if ("preferred-xml".equals(cmd)) {
20500                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20501                if (opti < args.length && "--full".equals(args[opti])) {
20502                    fullPreferred = true;
20503                    opti++;
20504                }
20505            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20506                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20507            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20508                dumpState.setDump(DumpState.DUMP_PACKAGES);
20509            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20510                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20511            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20512                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20513            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20514                dumpState.setDump(DumpState.DUMP_MESSAGES);
20515            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20516                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20517            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20518                    || "intent-filter-verifiers".equals(cmd)) {
20519                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20520            } else if ("version".equals(cmd)) {
20521                dumpState.setDump(DumpState.DUMP_VERSION);
20522            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20523                dumpState.setDump(DumpState.DUMP_KEYSETS);
20524            } else if ("installs".equals(cmd)) {
20525                dumpState.setDump(DumpState.DUMP_INSTALLS);
20526            } else if ("frozen".equals(cmd)) {
20527                dumpState.setDump(DumpState.DUMP_FROZEN);
20528            } else if ("dexopt".equals(cmd)) {
20529                dumpState.setDump(DumpState.DUMP_DEXOPT);
20530            } else if ("compiler-stats".equals(cmd)) {
20531                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20532            } else if ("enabled-overlays".equals(cmd)) {
20533                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
20534            } else if ("write".equals(cmd)) {
20535                synchronized (mPackages) {
20536                    mSettings.writeLPr();
20537                    pw.println("Settings written.");
20538                    return;
20539                }
20540            }
20541        }
20542
20543        if (checkin) {
20544            pw.println("vers,1");
20545        }
20546
20547        // reader
20548        synchronized (mPackages) {
20549            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20550                if (!checkin) {
20551                    if (dumpState.onTitlePrinted())
20552                        pw.println();
20553                    pw.println("Database versions:");
20554                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20555                }
20556            }
20557
20558            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20559                if (!checkin) {
20560                    if (dumpState.onTitlePrinted())
20561                        pw.println();
20562                    pw.println("Verifiers:");
20563                    pw.print("  Required: ");
20564                    pw.print(mRequiredVerifierPackage);
20565                    pw.print(" (uid=");
20566                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20567                            UserHandle.USER_SYSTEM));
20568                    pw.println(")");
20569                } else if (mRequiredVerifierPackage != null) {
20570                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20571                    pw.print(",");
20572                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20573                            UserHandle.USER_SYSTEM));
20574                }
20575            }
20576
20577            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20578                    packageName == null) {
20579                if (mIntentFilterVerifierComponent != null) {
20580                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20581                    if (!checkin) {
20582                        if (dumpState.onTitlePrinted())
20583                            pw.println();
20584                        pw.println("Intent Filter Verifier:");
20585                        pw.print("  Using: ");
20586                        pw.print(verifierPackageName);
20587                        pw.print(" (uid=");
20588                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20589                                UserHandle.USER_SYSTEM));
20590                        pw.println(")");
20591                    } else if (verifierPackageName != null) {
20592                        pw.print("ifv,"); pw.print(verifierPackageName);
20593                        pw.print(",");
20594                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20595                                UserHandle.USER_SYSTEM));
20596                    }
20597                } else {
20598                    pw.println();
20599                    pw.println("No Intent Filter Verifier available!");
20600                }
20601            }
20602
20603            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20604                boolean printedHeader = false;
20605                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20606                while (it.hasNext()) {
20607                    String libName = it.next();
20608                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20609                    if (versionedLib == null) {
20610                        continue;
20611                    }
20612                    final int versionCount = versionedLib.size();
20613                    for (int i = 0; i < versionCount; i++) {
20614                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20615                        if (!checkin) {
20616                            if (!printedHeader) {
20617                                if (dumpState.onTitlePrinted())
20618                                    pw.println();
20619                                pw.println("Libraries:");
20620                                printedHeader = true;
20621                            }
20622                            pw.print("  ");
20623                        } else {
20624                            pw.print("lib,");
20625                        }
20626                        pw.print(libEntry.info.getName());
20627                        if (libEntry.info.isStatic()) {
20628                            pw.print(" version=" + libEntry.info.getVersion());
20629                        }
20630                        if (!checkin) {
20631                            pw.print(" -> ");
20632                        }
20633                        if (libEntry.path != null) {
20634                            pw.print(" (jar) ");
20635                            pw.print(libEntry.path);
20636                        } else {
20637                            pw.print(" (apk) ");
20638                            pw.print(libEntry.apk);
20639                        }
20640                        pw.println();
20641                    }
20642                }
20643            }
20644
20645            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20646                if (dumpState.onTitlePrinted())
20647                    pw.println();
20648                if (!checkin) {
20649                    pw.println("Features:");
20650                }
20651
20652                synchronized (mAvailableFeatures) {
20653                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20654                        if (checkin) {
20655                            pw.print("feat,");
20656                            pw.print(feat.name);
20657                            pw.print(",");
20658                            pw.println(feat.version);
20659                        } else {
20660                            pw.print("  ");
20661                            pw.print(feat.name);
20662                            if (feat.version > 0) {
20663                                pw.print(" version=");
20664                                pw.print(feat.version);
20665                            }
20666                            pw.println();
20667                        }
20668                    }
20669                }
20670            }
20671
20672            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20673                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20674                        : "Activity Resolver Table:", "  ", packageName,
20675                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20676                    dumpState.setTitlePrinted(true);
20677                }
20678            }
20679            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20680                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20681                        : "Receiver Resolver Table:", "  ", packageName,
20682                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20683                    dumpState.setTitlePrinted(true);
20684                }
20685            }
20686            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20687                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20688                        : "Service Resolver Table:", "  ", packageName,
20689                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20690                    dumpState.setTitlePrinted(true);
20691                }
20692            }
20693            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20694                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20695                        : "Provider Resolver Table:", "  ", packageName,
20696                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20697                    dumpState.setTitlePrinted(true);
20698                }
20699            }
20700
20701            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20702                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20703                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20704                    int user = mSettings.mPreferredActivities.keyAt(i);
20705                    if (pir.dump(pw,
20706                            dumpState.getTitlePrinted()
20707                                ? "\nPreferred Activities User " + user + ":"
20708                                : "Preferred Activities User " + user + ":", "  ",
20709                            packageName, true, false)) {
20710                        dumpState.setTitlePrinted(true);
20711                    }
20712                }
20713            }
20714
20715            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20716                pw.flush();
20717                FileOutputStream fout = new FileOutputStream(fd);
20718                BufferedOutputStream str = new BufferedOutputStream(fout);
20719                XmlSerializer serializer = new FastXmlSerializer();
20720                try {
20721                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20722                    serializer.startDocument(null, true);
20723                    serializer.setFeature(
20724                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20725                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20726                    serializer.endDocument();
20727                    serializer.flush();
20728                } catch (IllegalArgumentException e) {
20729                    pw.println("Failed writing: " + e);
20730                } catch (IllegalStateException e) {
20731                    pw.println("Failed writing: " + e);
20732                } catch (IOException e) {
20733                    pw.println("Failed writing: " + e);
20734                }
20735            }
20736
20737            if (!checkin
20738                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20739                    && packageName == null) {
20740                pw.println();
20741                int count = mSettings.mPackages.size();
20742                if (count == 0) {
20743                    pw.println("No applications!");
20744                    pw.println();
20745                } else {
20746                    final String prefix = "  ";
20747                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20748                    if (allPackageSettings.size() == 0) {
20749                        pw.println("No domain preferred apps!");
20750                        pw.println();
20751                    } else {
20752                        pw.println("App verification status:");
20753                        pw.println();
20754                        count = 0;
20755                        for (PackageSetting ps : allPackageSettings) {
20756                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20757                            if (ivi == null || ivi.getPackageName() == null) continue;
20758                            pw.println(prefix + "Package: " + ivi.getPackageName());
20759                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20760                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20761                            pw.println();
20762                            count++;
20763                        }
20764                        if (count == 0) {
20765                            pw.println(prefix + "No app verification established.");
20766                            pw.println();
20767                        }
20768                        for (int userId : sUserManager.getUserIds()) {
20769                            pw.println("App linkages for user " + userId + ":");
20770                            pw.println();
20771                            count = 0;
20772                            for (PackageSetting ps : allPackageSettings) {
20773                                final long status = ps.getDomainVerificationStatusForUser(userId);
20774                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20775                                        && !DEBUG_DOMAIN_VERIFICATION) {
20776                                    continue;
20777                                }
20778                                pw.println(prefix + "Package: " + ps.name);
20779                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20780                                String statusStr = IntentFilterVerificationInfo.
20781                                        getStatusStringFromValue(status);
20782                                pw.println(prefix + "Status:  " + statusStr);
20783                                pw.println();
20784                                count++;
20785                            }
20786                            if (count == 0) {
20787                                pw.println(prefix + "No configured app linkages.");
20788                                pw.println();
20789                            }
20790                        }
20791                    }
20792                }
20793            }
20794
20795            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20796                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20797                if (packageName == null && permissionNames == null) {
20798                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
20799                        if (iperm == 0) {
20800                            if (dumpState.onTitlePrinted())
20801                                pw.println();
20802                            pw.println("AppOp Permissions:");
20803                        }
20804                        pw.print("  AppOp Permission ");
20805                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
20806                        pw.println(":");
20807                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
20808                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
20809                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
20810                        }
20811                    }
20812                }
20813            }
20814
20815            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20816                boolean printedSomething = false;
20817                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20818                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20819                        continue;
20820                    }
20821                    if (!printedSomething) {
20822                        if (dumpState.onTitlePrinted())
20823                            pw.println();
20824                        pw.println("Registered ContentProviders:");
20825                        printedSomething = true;
20826                    }
20827                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20828                    pw.print("    "); pw.println(p.toString());
20829                }
20830                printedSomething = false;
20831                for (Map.Entry<String, PackageParser.Provider> entry :
20832                        mProvidersByAuthority.entrySet()) {
20833                    PackageParser.Provider p = entry.getValue();
20834                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20835                        continue;
20836                    }
20837                    if (!printedSomething) {
20838                        if (dumpState.onTitlePrinted())
20839                            pw.println();
20840                        pw.println("ContentProvider Authorities:");
20841                        printedSomething = true;
20842                    }
20843                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20844                    pw.print("    "); pw.println(p.toString());
20845                    if (p.info != null && p.info.applicationInfo != null) {
20846                        final String appInfo = p.info.applicationInfo.toString();
20847                        pw.print("      applicationInfo="); pw.println(appInfo);
20848                    }
20849                }
20850            }
20851
20852            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20853                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20854            }
20855
20856            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20857                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20858            }
20859
20860            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20861                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20862            }
20863
20864            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20865                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20866            }
20867
20868            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
20869                // XXX should handle packageName != null by dumping only install data that
20870                // the given package is involved with.
20871                if (dumpState.onTitlePrinted()) pw.println();
20872                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
20873            }
20874
20875            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20876                // XXX should handle packageName != null by dumping only install data that
20877                // the given package is involved with.
20878                if (dumpState.onTitlePrinted()) pw.println();
20879
20880                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20881                ipw.println();
20882                ipw.println("Frozen packages:");
20883                ipw.increaseIndent();
20884                if (mFrozenPackages.size() == 0) {
20885                    ipw.println("(none)");
20886                } else {
20887                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20888                        ipw.println(mFrozenPackages.valueAt(i));
20889                    }
20890                }
20891                ipw.decreaseIndent();
20892            }
20893
20894            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20895                if (dumpState.onTitlePrinted()) pw.println();
20896                dumpDexoptStateLPr(pw, packageName);
20897            }
20898
20899            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20900                if (dumpState.onTitlePrinted()) pw.println();
20901                dumpCompilerStatsLPr(pw, packageName);
20902            }
20903
20904            if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) {
20905                if (dumpState.onTitlePrinted()) pw.println();
20906                dumpEnabledOverlaysLPr(pw);
20907            }
20908
20909            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20910                if (dumpState.onTitlePrinted()) pw.println();
20911                mSettings.dumpReadMessagesLPr(pw, dumpState);
20912
20913                pw.println();
20914                pw.println("Package warning messages:");
20915                BufferedReader in = null;
20916                String line = null;
20917                try {
20918                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20919                    while ((line = in.readLine()) != null) {
20920                        if (line.contains("ignored: updated version")) continue;
20921                        pw.println(line);
20922                    }
20923                } catch (IOException ignored) {
20924                } finally {
20925                    IoUtils.closeQuietly(in);
20926                }
20927            }
20928
20929            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
20930                BufferedReader in = null;
20931                String line = null;
20932                try {
20933                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20934                    while ((line = in.readLine()) != null) {
20935                        if (line.contains("ignored: updated version")) continue;
20936                        pw.print("msg,");
20937                        pw.println(line);
20938                    }
20939                } catch (IOException ignored) {
20940                } finally {
20941                    IoUtils.closeQuietly(in);
20942                }
20943            }
20944        }
20945    }
20946
20947    private void dumpProto(FileDescriptor fd) {
20948        final ProtoOutputStream proto = new ProtoOutputStream(fd);
20949
20950        synchronized (mPackages) {
20951            final long requiredVerifierPackageToken =
20952                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
20953            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
20954            proto.write(
20955                    PackageServiceDumpProto.PackageShortProto.UID,
20956                    getPackageUid(
20957                            mRequiredVerifierPackage,
20958                            MATCH_DEBUG_TRIAGED_MISSING,
20959                            UserHandle.USER_SYSTEM));
20960            proto.end(requiredVerifierPackageToken);
20961
20962            if (mIntentFilterVerifierComponent != null) {
20963                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20964                final long verifierPackageToken =
20965                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
20966                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
20967                proto.write(
20968                        PackageServiceDumpProto.PackageShortProto.UID,
20969                        getPackageUid(
20970                                verifierPackageName,
20971                                MATCH_DEBUG_TRIAGED_MISSING,
20972                                UserHandle.USER_SYSTEM));
20973                proto.end(verifierPackageToken);
20974            }
20975
20976            dumpSharedLibrariesProto(proto);
20977            dumpFeaturesProto(proto);
20978            mSettings.dumpPackagesProto(proto);
20979            mSettings.dumpSharedUsersProto(proto);
20980            dumpMessagesProto(proto);
20981        }
20982        proto.flush();
20983    }
20984
20985    private void dumpMessagesProto(ProtoOutputStream proto) {
20986        BufferedReader in = null;
20987        String line = null;
20988        try {
20989            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20990            while ((line = in.readLine()) != null) {
20991                if (line.contains("ignored: updated version")) continue;
20992                proto.write(PackageServiceDumpProto.MESSAGES, line);
20993            }
20994        } catch (IOException ignored) {
20995        } finally {
20996            IoUtils.closeQuietly(in);
20997        }
20998    }
20999
21000    private void dumpFeaturesProto(ProtoOutputStream proto) {
21001        synchronized (mAvailableFeatures) {
21002            final int count = mAvailableFeatures.size();
21003            for (int i = 0; i < count; i++) {
21004                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
21005                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
21006                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
21007                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
21008                proto.end(featureToken);
21009            }
21010        }
21011    }
21012
21013    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21014        final int count = mSharedLibraries.size();
21015        for (int i = 0; i < count; i++) {
21016            final String libName = mSharedLibraries.keyAt(i);
21017            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21018            if (versionedLib == null) {
21019                continue;
21020            }
21021            final int versionCount = versionedLib.size();
21022            for (int j = 0; j < versionCount; j++) {
21023                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21024                final long sharedLibraryToken =
21025                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21026                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21027                final boolean isJar = (libEntry.path != null);
21028                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21029                if (isJar) {
21030                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21031                } else {
21032                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21033                }
21034                proto.end(sharedLibraryToken);
21035            }
21036        }
21037    }
21038
21039    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21040        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21041        ipw.println();
21042        ipw.println("Dexopt state:");
21043        ipw.increaseIndent();
21044        Collection<PackageParser.Package> packages = null;
21045        if (packageName != null) {
21046            PackageParser.Package targetPackage = mPackages.get(packageName);
21047            if (targetPackage != null) {
21048                packages = Collections.singletonList(targetPackage);
21049            } else {
21050                ipw.println("Unable to find package: " + packageName);
21051                return;
21052            }
21053        } else {
21054            packages = mPackages.values();
21055        }
21056
21057        for (PackageParser.Package pkg : packages) {
21058            ipw.println("[" + pkg.packageName + "]");
21059            ipw.increaseIndent();
21060            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
21061            ipw.decreaseIndent();
21062        }
21063    }
21064
21065    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21066        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
21067        ipw.println();
21068        ipw.println("Compiler stats:");
21069        ipw.increaseIndent();
21070        Collection<PackageParser.Package> packages = null;
21071        if (packageName != null) {
21072            PackageParser.Package targetPackage = mPackages.get(packageName);
21073            if (targetPackage != null) {
21074                packages = Collections.singletonList(targetPackage);
21075            } else {
21076                ipw.println("Unable to find package: " + packageName);
21077                return;
21078            }
21079        } else {
21080            packages = mPackages.values();
21081        }
21082
21083        for (PackageParser.Package pkg : packages) {
21084            ipw.println("[" + pkg.packageName + "]");
21085            ipw.increaseIndent();
21086
21087            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21088            if (stats == null) {
21089                ipw.println("(No recorded stats)");
21090            } else {
21091                stats.dump(ipw);
21092            }
21093            ipw.decreaseIndent();
21094        }
21095    }
21096
21097    private void dumpEnabledOverlaysLPr(PrintWriter pw) {
21098        pw.println("Enabled overlay paths:");
21099        final int N = mEnabledOverlayPaths.size();
21100        for (int i = 0; i < N; i++) {
21101            final int userId = mEnabledOverlayPaths.keyAt(i);
21102            pw.println(String.format("    User %d:", userId));
21103            final ArrayMap<String, ArrayList<String>> userSpecificOverlays =
21104                mEnabledOverlayPaths.valueAt(i);
21105            final int M = userSpecificOverlays.size();
21106            for (int j = 0; j < M; j++) {
21107                final String targetPackageName = userSpecificOverlays.keyAt(j);
21108                final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j);
21109                pw.println(String.format("        %s: %s", targetPackageName, overlayPackagePaths));
21110            }
21111        }
21112    }
21113
21114    private String dumpDomainString(String packageName) {
21115        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21116                .getList();
21117        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21118
21119        ArraySet<String> result = new ArraySet<>();
21120        if (iviList.size() > 0) {
21121            for (IntentFilterVerificationInfo ivi : iviList) {
21122                for (String host : ivi.getDomains()) {
21123                    result.add(host);
21124                }
21125            }
21126        }
21127        if (filters != null && filters.size() > 0) {
21128            for (IntentFilter filter : filters) {
21129                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21130                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21131                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21132                    result.addAll(filter.getHostsList());
21133                }
21134            }
21135        }
21136
21137        StringBuilder sb = new StringBuilder(result.size() * 16);
21138        for (String domain : result) {
21139            if (sb.length() > 0) sb.append(" ");
21140            sb.append(domain);
21141        }
21142        return sb.toString();
21143    }
21144
21145    // ------- apps on sdcard specific code -------
21146    static final boolean DEBUG_SD_INSTALL = false;
21147
21148    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21149
21150    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21151
21152    private boolean mMediaMounted = false;
21153
21154    static String getEncryptKey() {
21155        try {
21156            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21157                    SD_ENCRYPTION_KEYSTORE_NAME);
21158            if (sdEncKey == null) {
21159                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21160                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21161                if (sdEncKey == null) {
21162                    Slog.e(TAG, "Failed to create encryption keys");
21163                    return null;
21164                }
21165            }
21166            return sdEncKey;
21167        } catch (NoSuchAlgorithmException nsae) {
21168            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21169            return null;
21170        } catch (IOException ioe) {
21171            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21172            return null;
21173        }
21174    }
21175
21176    /*
21177     * Update media status on PackageManager.
21178     */
21179    @Override
21180    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
21181        int callingUid = Binder.getCallingUid();
21182        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
21183            throw new SecurityException("Media status can only be updated by the system");
21184        }
21185        // reader; this apparently protects mMediaMounted, but should probably
21186        // be a different lock in that case.
21187        synchronized (mPackages) {
21188            Log.i(TAG, "Updating external media status from "
21189                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
21190                    + (mediaStatus ? "mounted" : "unmounted"));
21191            if (DEBUG_SD_INSTALL)
21192                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
21193                        + ", mMediaMounted=" + mMediaMounted);
21194            if (mediaStatus == mMediaMounted) {
21195                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
21196                        : 0, -1);
21197                mHandler.sendMessage(msg);
21198                return;
21199            }
21200            mMediaMounted = mediaStatus;
21201        }
21202        // Queue up an async operation since the package installation may take a
21203        // little while.
21204        mHandler.post(new Runnable() {
21205            public void run() {
21206                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
21207            }
21208        });
21209    }
21210
21211    /**
21212     * Called by StorageManagerService when the initial ASECs to scan are available.
21213     * Should block until all the ASEC containers are finished being scanned.
21214     */
21215    public void scanAvailableAsecs() {
21216        updateExternalMediaStatusInner(true, false, false);
21217    }
21218
21219    /*
21220     * Collect information of applications on external media, map them against
21221     * existing containers and update information based on current mount status.
21222     * Please note that we always have to report status if reportStatus has been
21223     * set to true especially when unloading packages.
21224     */
21225    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
21226            boolean externalStorage) {
21227        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
21228        int[] uidArr = EmptyArray.INT;
21229
21230        final String[] list = PackageHelper.getSecureContainerList();
21231        if (ArrayUtils.isEmpty(list)) {
21232            Log.i(TAG, "No secure containers found");
21233        } else {
21234            // Process list of secure containers and categorize them
21235            // as active or stale based on their package internal state.
21236
21237            // reader
21238            synchronized (mPackages) {
21239                for (String cid : list) {
21240                    // Leave stages untouched for now; installer service owns them
21241                    if (PackageInstallerService.isStageName(cid)) continue;
21242
21243                    if (DEBUG_SD_INSTALL)
21244                        Log.i(TAG, "Processing container " + cid);
21245                    String pkgName = getAsecPackageName(cid);
21246                    if (pkgName == null) {
21247                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
21248                        continue;
21249                    }
21250                    if (DEBUG_SD_INSTALL)
21251                        Log.i(TAG, "Looking for pkg : " + pkgName);
21252
21253                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
21254                    if (ps == null) {
21255                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
21256                        continue;
21257                    }
21258
21259                    /*
21260                     * Skip packages that are not external if we're unmounting
21261                     * external storage.
21262                     */
21263                    if (externalStorage && !isMounted && !isExternal(ps)) {
21264                        continue;
21265                    }
21266
21267                    final AsecInstallArgs args = new AsecInstallArgs(cid,
21268                            getAppDexInstructionSets(ps), ps.isForwardLocked());
21269                    // The package status is changed only if the code path
21270                    // matches between settings and the container id.
21271                    if (ps.codePathString != null
21272                            && ps.codePathString.startsWith(args.getCodePath())) {
21273                        if (DEBUG_SD_INSTALL) {
21274                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
21275                                    + " at code path: " + ps.codePathString);
21276                        }
21277
21278                        // We do have a valid package installed on sdcard
21279                        processCids.put(args, ps.codePathString);
21280                        final int uid = ps.appId;
21281                        if (uid != -1) {
21282                            uidArr = ArrayUtils.appendInt(uidArr, uid);
21283                        }
21284                    } else {
21285                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
21286                                + ps.codePathString);
21287                    }
21288                }
21289            }
21290
21291            Arrays.sort(uidArr);
21292        }
21293
21294        // Process packages with valid entries.
21295        if (isMounted) {
21296            if (DEBUG_SD_INSTALL)
21297                Log.i(TAG, "Loading packages");
21298            loadMediaPackages(processCids, uidArr, externalStorage);
21299            startCleaningPackages();
21300            mInstallerService.onSecureContainersAvailable();
21301        } else {
21302            if (DEBUG_SD_INSTALL)
21303                Log.i(TAG, "Unloading packages");
21304            unloadMediaPackages(processCids, uidArr, reportStatus);
21305        }
21306    }
21307
21308    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21309            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21310        final int size = infos.size();
21311        final String[] packageNames = new String[size];
21312        final int[] packageUids = new int[size];
21313        for (int i = 0; i < size; i++) {
21314            final ApplicationInfo info = infos.get(i);
21315            packageNames[i] = info.packageName;
21316            packageUids[i] = info.uid;
21317        }
21318        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21319                finishedReceiver);
21320    }
21321
21322    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21323            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21324        sendResourcesChangedBroadcast(mediaStatus, replacing,
21325                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21326    }
21327
21328    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21329            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21330        int size = pkgList.length;
21331        if (size > 0) {
21332            // Send broadcasts here
21333            Bundle extras = new Bundle();
21334            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21335            if (uidArr != null) {
21336                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21337            }
21338            if (replacing) {
21339                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21340            }
21341            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21342                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21343            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21344        }
21345    }
21346
21347   /*
21348     * Look at potentially valid container ids from processCids If package
21349     * information doesn't match the one on record or package scanning fails,
21350     * the cid is added to list of removeCids. We currently don't delete stale
21351     * containers.
21352     */
21353    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
21354            boolean externalStorage) {
21355        ArrayList<String> pkgList = new ArrayList<String>();
21356        Set<AsecInstallArgs> keys = processCids.keySet();
21357
21358        for (AsecInstallArgs args : keys) {
21359            String codePath = processCids.get(args);
21360            if (DEBUG_SD_INSTALL)
21361                Log.i(TAG, "Loading container : " + args.cid);
21362            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
21363            try {
21364                // Make sure there are no container errors first.
21365                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
21366                    Slog.e(TAG, "Failed to mount cid : " + args.cid
21367                            + " when installing from sdcard");
21368                    continue;
21369                }
21370                // Check code path here.
21371                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
21372                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
21373                            + " does not match one in settings " + codePath);
21374                    continue;
21375                }
21376                // Parse package
21377                int parseFlags = mDefParseFlags;
21378                if (args.isExternalAsec()) {
21379                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21380                }
21381                if (args.isFwdLocked()) {
21382                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21383                }
21384
21385                synchronized (mInstallLock) {
21386                    PackageParser.Package pkg = null;
21387                    try {
21388                        // Sadly we don't know the package name yet to freeze it
21389                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21390                                SCAN_IGNORE_FROZEN, 0, null);
21391                    } catch (PackageManagerException e) {
21392                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21393                    }
21394                    // Scan the package
21395                    if (pkg != null) {
21396                        /*
21397                         * TODO why is the lock being held? doPostInstall is
21398                         * called in other places without the lock. This needs
21399                         * to be straightened out.
21400                         */
21401                        // writer
21402                        synchronized (mPackages) {
21403                            retCode = PackageManager.INSTALL_SUCCEEDED;
21404                            pkgList.add(pkg.packageName);
21405                            // Post process args
21406                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21407                                    pkg.applicationInfo.uid);
21408                        }
21409                    } else {
21410                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21411                    }
21412                }
21413
21414            } finally {
21415                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21416                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21417                }
21418            }
21419        }
21420        // writer
21421        synchronized (mPackages) {
21422            // If the platform SDK has changed since the last time we booted,
21423            // we need to re-grant app permission to catch any new ones that
21424            // appear. This is really a hack, and means that apps can in some
21425            // cases get permissions that the user didn't initially explicitly
21426            // allow... it would be nice to have some better way to handle
21427            // this situation.
21428            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21429                    : mSettings.getInternalVersion();
21430            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21431                    : StorageManager.UUID_PRIVATE_INTERNAL;
21432
21433            int updateFlags = UPDATE_PERMISSIONS_ALL;
21434            if (ver.sdkVersion != mSdkVersion) {
21435                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21436                        + mSdkVersion + "; regranting permissions for external");
21437                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21438            }
21439            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21440
21441            // Yay, everything is now upgraded
21442            ver.forceCurrent();
21443
21444            // can downgrade to reader
21445            // Persist settings
21446            mSettings.writeLPr();
21447        }
21448        // Send a broadcast to let everyone know we are done processing
21449        if (pkgList.size() > 0) {
21450            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21451        }
21452    }
21453
21454   /*
21455     * Utility method to unload a list of specified containers
21456     */
21457    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21458        // Just unmount all valid containers.
21459        for (AsecInstallArgs arg : cidArgs) {
21460            synchronized (mInstallLock) {
21461                arg.doPostDeleteLI(false);
21462           }
21463       }
21464   }
21465
21466    /*
21467     * Unload packages mounted on external media. This involves deleting package
21468     * data from internal structures, sending broadcasts about disabled packages,
21469     * gc'ing to free up references, unmounting all secure containers
21470     * corresponding to packages on external media, and posting a
21471     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21472     * that we always have to post this message if status has been requested no
21473     * matter what.
21474     */
21475    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21476            final boolean reportStatus) {
21477        if (DEBUG_SD_INSTALL)
21478            Log.i(TAG, "unloading media packages");
21479        ArrayList<String> pkgList = new ArrayList<String>();
21480        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21481        final Set<AsecInstallArgs> keys = processCids.keySet();
21482        for (AsecInstallArgs args : keys) {
21483            String pkgName = args.getPackageName();
21484            if (DEBUG_SD_INSTALL)
21485                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21486            // Delete package internally
21487            PackageRemovedInfo outInfo = new PackageRemovedInfo();
21488            synchronized (mInstallLock) {
21489                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21490                final boolean res;
21491                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21492                        "unloadMediaPackages")) {
21493                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21494                            null);
21495                }
21496                if (res) {
21497                    pkgList.add(pkgName);
21498                } else {
21499                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21500                    failedList.add(args);
21501                }
21502            }
21503        }
21504
21505        // reader
21506        synchronized (mPackages) {
21507            // We didn't update the settings after removing each package;
21508            // write them now for all packages.
21509            mSettings.writeLPr();
21510        }
21511
21512        // We have to absolutely send UPDATED_MEDIA_STATUS only
21513        // after confirming that all the receivers processed the ordered
21514        // broadcast when packages get disabled, force a gc to clean things up.
21515        // and unload all the containers.
21516        if (pkgList.size() > 0) {
21517            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21518                    new IIntentReceiver.Stub() {
21519                public void performReceive(Intent intent, int resultCode, String data,
21520                        Bundle extras, boolean ordered, boolean sticky,
21521                        int sendingUser) throws RemoteException {
21522                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21523                            reportStatus ? 1 : 0, 1, keys);
21524                    mHandler.sendMessage(msg);
21525                }
21526            });
21527        } else {
21528            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
21529                    keys);
21530            mHandler.sendMessage(msg);
21531        }
21532    }
21533
21534    private void loadPrivatePackages(final VolumeInfo vol) {
21535        mHandler.post(new Runnable() {
21536            @Override
21537            public void run() {
21538                loadPrivatePackagesInner(vol);
21539            }
21540        });
21541    }
21542
21543    private void loadPrivatePackagesInner(VolumeInfo vol) {
21544        final String volumeUuid = vol.fsUuid;
21545        if (TextUtils.isEmpty(volumeUuid)) {
21546            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21547            return;
21548        }
21549
21550        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21551        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21552        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21553
21554        final VersionInfo ver;
21555        final List<PackageSetting> packages;
21556        synchronized (mPackages) {
21557            ver = mSettings.findOrCreateVersion(volumeUuid);
21558            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21559        }
21560
21561        for (PackageSetting ps : packages) {
21562            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21563            synchronized (mInstallLock) {
21564                final PackageParser.Package pkg;
21565                try {
21566                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21567                    loaded.add(pkg.applicationInfo);
21568
21569                } catch (PackageManagerException e) {
21570                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21571                }
21572
21573                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21574                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21575                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21576                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21577                }
21578            }
21579        }
21580
21581        // Reconcile app data for all started/unlocked users
21582        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21583        final UserManager um = mContext.getSystemService(UserManager.class);
21584        UserManagerInternal umInternal = getUserManagerInternal();
21585        for (UserInfo user : um.getUsers()) {
21586            final int flags;
21587            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21588                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21589            } else if (umInternal.isUserRunning(user.id)) {
21590                flags = StorageManager.FLAG_STORAGE_DE;
21591            } else {
21592                continue;
21593            }
21594
21595            try {
21596                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21597                synchronized (mInstallLock) {
21598                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21599                }
21600            } catch (IllegalStateException e) {
21601                // Device was probably ejected, and we'll process that event momentarily
21602                Slog.w(TAG, "Failed to prepare storage: " + e);
21603            }
21604        }
21605
21606        synchronized (mPackages) {
21607            int updateFlags = UPDATE_PERMISSIONS_ALL;
21608            if (ver.sdkVersion != mSdkVersion) {
21609                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21610                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21611                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21612            }
21613            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21614
21615            // Yay, everything is now upgraded
21616            ver.forceCurrent();
21617
21618            mSettings.writeLPr();
21619        }
21620
21621        for (PackageFreezer freezer : freezers) {
21622            freezer.close();
21623        }
21624
21625        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21626        sendResourcesChangedBroadcast(true, false, loaded, null);
21627    }
21628
21629    private void unloadPrivatePackages(final VolumeInfo vol) {
21630        mHandler.post(new Runnable() {
21631            @Override
21632            public void run() {
21633                unloadPrivatePackagesInner(vol);
21634            }
21635        });
21636    }
21637
21638    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21639        final String volumeUuid = vol.fsUuid;
21640        if (TextUtils.isEmpty(volumeUuid)) {
21641            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21642            return;
21643        }
21644
21645        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21646        synchronized (mInstallLock) {
21647        synchronized (mPackages) {
21648            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21649            for (PackageSetting ps : packages) {
21650                if (ps.pkg == null) continue;
21651
21652                final ApplicationInfo info = ps.pkg.applicationInfo;
21653                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21654                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
21655
21656                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21657                        "unloadPrivatePackagesInner")) {
21658                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21659                            false, null)) {
21660                        unloaded.add(info);
21661                    } else {
21662                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21663                    }
21664                }
21665
21666                // Try very hard to release any references to this package
21667                // so we don't risk the system server being killed due to
21668                // open FDs
21669                AttributeCache.instance().removePackage(ps.name);
21670            }
21671
21672            mSettings.writeLPr();
21673        }
21674        }
21675
21676        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21677        sendResourcesChangedBroadcast(false, false, unloaded, null);
21678
21679        // Try very hard to release any references to this path so we don't risk
21680        // the system server being killed due to open FDs
21681        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21682
21683        for (int i = 0; i < 3; i++) {
21684            System.gc();
21685            System.runFinalization();
21686        }
21687    }
21688
21689    private void assertPackageKnown(String volumeUuid, String packageName)
21690            throws PackageManagerException {
21691        synchronized (mPackages) {
21692            // Normalize package name to handle renamed packages
21693            packageName = normalizePackageNameLPr(packageName);
21694
21695            final PackageSetting ps = mSettings.mPackages.get(packageName);
21696            if (ps == null) {
21697                throw new PackageManagerException("Package " + packageName + " is unknown");
21698            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21699                throw new PackageManagerException(
21700                        "Package " + packageName + " found on unknown volume " + volumeUuid
21701                                + "; expected volume " + ps.volumeUuid);
21702            }
21703        }
21704    }
21705
21706    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21707            throws PackageManagerException {
21708        synchronized (mPackages) {
21709            // Normalize package name to handle renamed packages
21710            packageName = normalizePackageNameLPr(packageName);
21711
21712            final PackageSetting ps = mSettings.mPackages.get(packageName);
21713            if (ps == null) {
21714                throw new PackageManagerException("Package " + packageName + " is unknown");
21715            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21716                throw new PackageManagerException(
21717                        "Package " + packageName + " found on unknown volume " + volumeUuid
21718                                + "; expected volume " + ps.volumeUuid);
21719            } else if (!ps.getInstalled(userId)) {
21720                throw new PackageManagerException(
21721                        "Package " + packageName + " not installed for user " + userId);
21722            }
21723        }
21724    }
21725
21726    private List<String> collectAbsoluteCodePaths() {
21727        synchronized (mPackages) {
21728            List<String> codePaths = new ArrayList<>();
21729            final int packageCount = mSettings.mPackages.size();
21730            for (int i = 0; i < packageCount; i++) {
21731                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21732                codePaths.add(ps.codePath.getAbsolutePath());
21733            }
21734            return codePaths;
21735        }
21736    }
21737
21738    /**
21739     * Examine all apps present on given mounted volume, and destroy apps that
21740     * aren't expected, either due to uninstallation or reinstallation on
21741     * another volume.
21742     */
21743    private void reconcileApps(String volumeUuid) {
21744        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21745        List<File> filesToDelete = null;
21746
21747        final File[] files = FileUtils.listFilesOrEmpty(
21748                Environment.getDataAppDirectory(volumeUuid));
21749        for (File file : files) {
21750            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21751                    && !PackageInstallerService.isStageName(file.getName());
21752            if (!isPackage) {
21753                // Ignore entries which are not packages
21754                continue;
21755            }
21756
21757            String absolutePath = file.getAbsolutePath();
21758
21759            boolean pathValid = false;
21760            final int absoluteCodePathCount = absoluteCodePaths.size();
21761            for (int i = 0; i < absoluteCodePathCount; i++) {
21762                String absoluteCodePath = absoluteCodePaths.get(i);
21763                if (absolutePath.startsWith(absoluteCodePath)) {
21764                    pathValid = true;
21765                    break;
21766                }
21767            }
21768
21769            if (!pathValid) {
21770                if (filesToDelete == null) {
21771                    filesToDelete = new ArrayList<>();
21772                }
21773                filesToDelete.add(file);
21774            }
21775        }
21776
21777        if (filesToDelete != null) {
21778            final int fileToDeleteCount = filesToDelete.size();
21779            for (int i = 0; i < fileToDeleteCount; i++) {
21780                File fileToDelete = filesToDelete.get(i);
21781                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21782                synchronized (mInstallLock) {
21783                    removeCodePathLI(fileToDelete);
21784                }
21785            }
21786        }
21787    }
21788
21789    /**
21790     * Reconcile all app data for the given user.
21791     * <p>
21792     * Verifies that directories exist and that ownership and labeling is
21793     * correct for all installed apps on all mounted volumes.
21794     */
21795    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21796        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21797        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21798            final String volumeUuid = vol.getFsUuid();
21799            synchronized (mInstallLock) {
21800                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21801            }
21802        }
21803    }
21804
21805    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21806            boolean migrateAppData) {
21807        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
21808    }
21809
21810    /**
21811     * Reconcile all app data on given mounted volume.
21812     * <p>
21813     * Destroys app data that isn't expected, either due to uninstallation or
21814     * reinstallation on another volume.
21815     * <p>
21816     * Verifies that directories exist and that ownership and labeling is
21817     * correct for all installed apps.
21818     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
21819     */
21820    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21821            boolean migrateAppData, boolean onlyCoreApps) {
21822        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21823                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21824        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
21825
21826        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21827        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21828
21829        // First look for stale data that doesn't belong, and check if things
21830        // have changed since we did our last restorecon
21831        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21832            if (StorageManager.isFileEncryptedNativeOrEmulated()
21833                    && !StorageManager.isUserKeyUnlocked(userId)) {
21834                throw new RuntimeException(
21835                        "Yikes, someone asked us to reconcile CE storage while " + userId
21836                                + " was still locked; this would have caused massive data loss!");
21837            }
21838
21839            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21840            for (File file : files) {
21841                final String packageName = file.getName();
21842                try {
21843                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21844                } catch (PackageManagerException e) {
21845                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21846                    try {
21847                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21848                                StorageManager.FLAG_STORAGE_CE, 0);
21849                    } catch (InstallerException e2) {
21850                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21851                    }
21852                }
21853            }
21854        }
21855        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21856            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21857            for (File file : files) {
21858                final String packageName = file.getName();
21859                try {
21860                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21861                } catch (PackageManagerException e) {
21862                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21863                    try {
21864                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21865                                StorageManager.FLAG_STORAGE_DE, 0);
21866                    } catch (InstallerException e2) {
21867                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21868                    }
21869                }
21870            }
21871        }
21872
21873        // Ensure that data directories are ready to roll for all packages
21874        // installed for this volume and user
21875        final List<PackageSetting> packages;
21876        synchronized (mPackages) {
21877            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21878        }
21879        int preparedCount = 0;
21880        for (PackageSetting ps : packages) {
21881            final String packageName = ps.name;
21882            if (ps.pkg == null) {
21883                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21884                // TODO: might be due to legacy ASEC apps; we should circle back
21885                // and reconcile again once they're scanned
21886                continue;
21887            }
21888            // Skip non-core apps if requested
21889            if (onlyCoreApps && !ps.pkg.coreApp) {
21890                result.add(packageName);
21891                continue;
21892            }
21893
21894            if (ps.getInstalled(userId)) {
21895                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
21896                preparedCount++;
21897            }
21898        }
21899
21900        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21901        return result;
21902    }
21903
21904    /**
21905     * Prepare app data for the given app just after it was installed or
21906     * upgraded. This method carefully only touches users that it's installed
21907     * for, and it forces a restorecon to handle any seinfo changes.
21908     * <p>
21909     * Verifies that directories exist and that ownership and labeling is
21910     * correct for all installed apps. If there is an ownership mismatch, it
21911     * will try recovering system apps by wiping data; third-party app data is
21912     * left intact.
21913     * <p>
21914     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21915     */
21916    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21917        final PackageSetting ps;
21918        synchronized (mPackages) {
21919            ps = mSettings.mPackages.get(pkg.packageName);
21920            mSettings.writeKernelMappingLPr(ps);
21921        }
21922
21923        final UserManager um = mContext.getSystemService(UserManager.class);
21924        UserManagerInternal umInternal = getUserManagerInternal();
21925        for (UserInfo user : um.getUsers()) {
21926            final int flags;
21927            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21928                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21929            } else if (umInternal.isUserRunning(user.id)) {
21930                flags = StorageManager.FLAG_STORAGE_DE;
21931            } else {
21932                continue;
21933            }
21934
21935            if (ps.getInstalled(user.id)) {
21936                // TODO: when user data is locked, mark that we're still dirty
21937                prepareAppDataLIF(pkg, user.id, flags);
21938            }
21939        }
21940    }
21941
21942    /**
21943     * Prepare app data for the given app.
21944     * <p>
21945     * Verifies that directories exist and that ownership and labeling is
21946     * correct for all installed apps. If there is an ownership mismatch, this
21947     * will try recovering system apps by wiping data; third-party app data is
21948     * left intact.
21949     */
21950    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21951        if (pkg == null) {
21952            Slog.wtf(TAG, "Package was null!", new Throwable());
21953            return;
21954        }
21955        prepareAppDataLeafLIF(pkg, userId, flags);
21956        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21957        for (int i = 0; i < childCount; i++) {
21958            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21959        }
21960    }
21961
21962    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
21963            boolean maybeMigrateAppData) {
21964        prepareAppDataLIF(pkg, userId, flags);
21965
21966        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
21967            // We may have just shuffled around app data directories, so
21968            // prepare them one more time
21969            prepareAppDataLIF(pkg, userId, flags);
21970        }
21971    }
21972
21973    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21974        if (DEBUG_APP_DATA) {
21975            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21976                    + Integer.toHexString(flags));
21977        }
21978
21979        final String volumeUuid = pkg.volumeUuid;
21980        final String packageName = pkg.packageName;
21981        final ApplicationInfo app = pkg.applicationInfo;
21982        final int appId = UserHandle.getAppId(app.uid);
21983
21984        Preconditions.checkNotNull(app.seInfo);
21985
21986        long ceDataInode = -1;
21987        try {
21988            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21989                    appId, app.seInfo, app.targetSdkVersion);
21990        } catch (InstallerException e) {
21991            if (app.isSystemApp()) {
21992                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21993                        + ", but trying to recover: " + e);
21994                destroyAppDataLeafLIF(pkg, userId, flags);
21995                try {
21996                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21997                            appId, app.seInfo, app.targetSdkVersion);
21998                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21999                } catch (InstallerException e2) {
22000                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22001                }
22002            } else {
22003                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22004            }
22005        }
22006
22007        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22008            // TODO: mark this structure as dirty so we persist it!
22009            synchronized (mPackages) {
22010                final PackageSetting ps = mSettings.mPackages.get(packageName);
22011                if (ps != null) {
22012                    ps.setCeDataInode(ceDataInode, userId);
22013                }
22014            }
22015        }
22016
22017        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22018    }
22019
22020    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22021        if (pkg == null) {
22022            Slog.wtf(TAG, "Package was null!", new Throwable());
22023            return;
22024        }
22025        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22026        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22027        for (int i = 0; i < childCount; i++) {
22028            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22029        }
22030    }
22031
22032    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22033        final String volumeUuid = pkg.volumeUuid;
22034        final String packageName = pkg.packageName;
22035        final ApplicationInfo app = pkg.applicationInfo;
22036
22037        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22038            // Create a native library symlink only if we have native libraries
22039            // and if the native libraries are 32 bit libraries. We do not provide
22040            // this symlink for 64 bit libraries.
22041            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22042                final String nativeLibPath = app.nativeLibraryDir;
22043                try {
22044                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22045                            nativeLibPath, userId);
22046                } catch (InstallerException e) {
22047                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22048                }
22049            }
22050        }
22051    }
22052
22053    /**
22054     * For system apps on non-FBE devices, this method migrates any existing
22055     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22056     * requested by the app.
22057     */
22058    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22059        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
22060                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22061            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22062                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22063            try {
22064                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22065                        storageTarget);
22066            } catch (InstallerException e) {
22067                logCriticalInfo(Log.WARN,
22068                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22069            }
22070            return true;
22071        } else {
22072            return false;
22073        }
22074    }
22075
22076    public PackageFreezer freezePackage(String packageName, String killReason) {
22077        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22078    }
22079
22080    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22081        return new PackageFreezer(packageName, userId, killReason);
22082    }
22083
22084    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22085            String killReason) {
22086        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22087    }
22088
22089    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22090            String killReason) {
22091        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22092            return new PackageFreezer();
22093        } else {
22094            return freezePackage(packageName, userId, killReason);
22095        }
22096    }
22097
22098    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22099            String killReason) {
22100        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22101    }
22102
22103    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22104            String killReason) {
22105        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22106            return new PackageFreezer();
22107        } else {
22108            return freezePackage(packageName, userId, killReason);
22109        }
22110    }
22111
22112    /**
22113     * Class that freezes and kills the given package upon creation, and
22114     * unfreezes it upon closing. This is typically used when doing surgery on
22115     * app code/data to prevent the app from running while you're working.
22116     */
22117    private class PackageFreezer implements AutoCloseable {
22118        private final String mPackageName;
22119        private final PackageFreezer[] mChildren;
22120
22121        private final boolean mWeFroze;
22122
22123        private final AtomicBoolean mClosed = new AtomicBoolean();
22124        private final CloseGuard mCloseGuard = CloseGuard.get();
22125
22126        /**
22127         * Create and return a stub freezer that doesn't actually do anything,
22128         * typically used when someone requested
22129         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22130         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22131         */
22132        public PackageFreezer() {
22133            mPackageName = null;
22134            mChildren = null;
22135            mWeFroze = false;
22136            mCloseGuard.open("close");
22137        }
22138
22139        public PackageFreezer(String packageName, int userId, String killReason) {
22140            synchronized (mPackages) {
22141                mPackageName = packageName;
22142                mWeFroze = mFrozenPackages.add(mPackageName);
22143
22144                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22145                if (ps != null) {
22146                    killApplication(ps.name, ps.appId, userId, killReason);
22147                }
22148
22149                final PackageParser.Package p = mPackages.get(packageName);
22150                if (p != null && p.childPackages != null) {
22151                    final int N = p.childPackages.size();
22152                    mChildren = new PackageFreezer[N];
22153                    for (int i = 0; i < N; i++) {
22154                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22155                                userId, killReason);
22156                    }
22157                } else {
22158                    mChildren = null;
22159                }
22160            }
22161            mCloseGuard.open("close");
22162        }
22163
22164        @Override
22165        protected void finalize() throws Throwable {
22166            try {
22167                mCloseGuard.warnIfOpen();
22168                close();
22169            } finally {
22170                super.finalize();
22171            }
22172        }
22173
22174        @Override
22175        public void close() {
22176            mCloseGuard.close();
22177            if (mClosed.compareAndSet(false, true)) {
22178                synchronized (mPackages) {
22179                    if (mWeFroze) {
22180                        mFrozenPackages.remove(mPackageName);
22181                    }
22182
22183                    if (mChildren != null) {
22184                        for (PackageFreezer freezer : mChildren) {
22185                            freezer.close();
22186                        }
22187                    }
22188                }
22189            }
22190        }
22191    }
22192
22193    /**
22194     * Verify that given package is currently frozen.
22195     */
22196    private void checkPackageFrozen(String packageName) {
22197        synchronized (mPackages) {
22198            if (!mFrozenPackages.contains(packageName)) {
22199                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22200            }
22201        }
22202    }
22203
22204    @Override
22205    public int movePackage(final String packageName, final String volumeUuid) {
22206        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22207
22208        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
22209        final int moveId = mNextMoveId.getAndIncrement();
22210        mHandler.post(new Runnable() {
22211            @Override
22212            public void run() {
22213                try {
22214                    movePackageInternal(packageName, volumeUuid, moveId, user);
22215                } catch (PackageManagerException e) {
22216                    Slog.w(TAG, "Failed to move " + packageName, e);
22217                    mMoveCallbacks.notifyStatusChanged(moveId,
22218                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22219                }
22220            }
22221        });
22222        return moveId;
22223    }
22224
22225    private void movePackageInternal(final String packageName, final String volumeUuid,
22226            final int moveId, UserHandle user) throws PackageManagerException {
22227        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22228        final PackageManager pm = mContext.getPackageManager();
22229
22230        final boolean currentAsec;
22231        final String currentVolumeUuid;
22232        final File codeFile;
22233        final String installerPackageName;
22234        final String packageAbiOverride;
22235        final int appId;
22236        final String seinfo;
22237        final String label;
22238        final int targetSdkVersion;
22239        final PackageFreezer freezer;
22240        final int[] installedUserIds;
22241
22242        // reader
22243        synchronized (mPackages) {
22244            final PackageParser.Package pkg = mPackages.get(packageName);
22245            final PackageSetting ps = mSettings.mPackages.get(packageName);
22246            if (pkg == null || ps == null) {
22247                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22248            }
22249
22250            if (pkg.applicationInfo.isSystemApp()) {
22251                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22252                        "Cannot move system application");
22253            }
22254
22255            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22256            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22257                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22258            if (isInternalStorage && !allow3rdPartyOnInternal) {
22259                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22260                        "3rd party apps are not allowed on internal storage");
22261            }
22262
22263            if (pkg.applicationInfo.isExternalAsec()) {
22264                currentAsec = true;
22265                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22266            } else if (pkg.applicationInfo.isForwardLocked()) {
22267                currentAsec = true;
22268                currentVolumeUuid = "forward_locked";
22269            } else {
22270                currentAsec = false;
22271                currentVolumeUuid = ps.volumeUuid;
22272
22273                final File probe = new File(pkg.codePath);
22274                final File probeOat = new File(probe, "oat");
22275                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22276                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22277                            "Move only supported for modern cluster style installs");
22278                }
22279            }
22280
22281            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22282                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22283                        "Package already moved to " + volumeUuid);
22284            }
22285            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22286                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22287                        "Device admin cannot be moved");
22288            }
22289
22290            if (mFrozenPackages.contains(packageName)) {
22291                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22292                        "Failed to move already frozen package");
22293            }
22294
22295            codeFile = new File(pkg.codePath);
22296            installerPackageName = ps.installerPackageName;
22297            packageAbiOverride = ps.cpuAbiOverrideString;
22298            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22299            seinfo = pkg.applicationInfo.seInfo;
22300            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22301            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22302            freezer = freezePackage(packageName, "movePackageInternal");
22303            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22304        }
22305
22306        final Bundle extras = new Bundle();
22307        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22308        extras.putString(Intent.EXTRA_TITLE, label);
22309        mMoveCallbacks.notifyCreated(moveId, extras);
22310
22311        int installFlags;
22312        final boolean moveCompleteApp;
22313        final File measurePath;
22314
22315        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22316            installFlags = INSTALL_INTERNAL;
22317            moveCompleteApp = !currentAsec;
22318            measurePath = Environment.getDataAppDirectory(volumeUuid);
22319        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22320            installFlags = INSTALL_EXTERNAL;
22321            moveCompleteApp = false;
22322            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22323        } else {
22324            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22325            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22326                    || !volume.isMountedWritable()) {
22327                freezer.close();
22328                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22329                        "Move location not mounted private volume");
22330            }
22331
22332            Preconditions.checkState(!currentAsec);
22333
22334            installFlags = INSTALL_INTERNAL;
22335            moveCompleteApp = true;
22336            measurePath = Environment.getDataAppDirectory(volumeUuid);
22337        }
22338
22339        final PackageStats stats = new PackageStats(null, -1);
22340        synchronized (mInstaller) {
22341            for (int userId : installedUserIds) {
22342                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22343                    freezer.close();
22344                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22345                            "Failed to measure package size");
22346                }
22347            }
22348        }
22349
22350        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22351                + stats.dataSize);
22352
22353        final long startFreeBytes = measurePath.getUsableSpace();
22354        final long sizeBytes;
22355        if (moveCompleteApp) {
22356            sizeBytes = stats.codeSize + stats.dataSize;
22357        } else {
22358            sizeBytes = stats.codeSize;
22359        }
22360
22361        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22362            freezer.close();
22363            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22364                    "Not enough free space to move");
22365        }
22366
22367        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22368
22369        final CountDownLatch installedLatch = new CountDownLatch(1);
22370        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22371            @Override
22372            public void onUserActionRequired(Intent intent) throws RemoteException {
22373                throw new IllegalStateException();
22374            }
22375
22376            @Override
22377            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22378                    Bundle extras) throws RemoteException {
22379                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22380                        + PackageManager.installStatusToString(returnCode, msg));
22381
22382                installedLatch.countDown();
22383                freezer.close();
22384
22385                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22386                switch (status) {
22387                    case PackageInstaller.STATUS_SUCCESS:
22388                        mMoveCallbacks.notifyStatusChanged(moveId,
22389                                PackageManager.MOVE_SUCCEEDED);
22390                        break;
22391                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22392                        mMoveCallbacks.notifyStatusChanged(moveId,
22393                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22394                        break;
22395                    default:
22396                        mMoveCallbacks.notifyStatusChanged(moveId,
22397                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22398                        break;
22399                }
22400            }
22401        };
22402
22403        final MoveInfo move;
22404        if (moveCompleteApp) {
22405            // Kick off a thread to report progress estimates
22406            new Thread() {
22407                @Override
22408                public void run() {
22409                    while (true) {
22410                        try {
22411                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22412                                break;
22413                            }
22414                        } catch (InterruptedException ignored) {
22415                        }
22416
22417                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22418                        final int progress = 10 + (int) MathUtils.constrain(
22419                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22420                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22421                    }
22422                }
22423            }.start();
22424
22425            final String dataAppName = codeFile.getName();
22426            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22427                    dataAppName, appId, seinfo, targetSdkVersion);
22428        } else {
22429            move = null;
22430        }
22431
22432        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22433
22434        final Message msg = mHandler.obtainMessage(INIT_COPY);
22435        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22436        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22437                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22438                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22439                PackageManager.INSTALL_REASON_UNKNOWN);
22440        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22441        msg.obj = params;
22442
22443        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22444                System.identityHashCode(msg.obj));
22445        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22446                System.identityHashCode(msg.obj));
22447
22448        mHandler.sendMessage(msg);
22449    }
22450
22451    @Override
22452    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22453        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22454
22455        final int realMoveId = mNextMoveId.getAndIncrement();
22456        final Bundle extras = new Bundle();
22457        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22458        mMoveCallbacks.notifyCreated(realMoveId, extras);
22459
22460        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22461            @Override
22462            public void onCreated(int moveId, Bundle extras) {
22463                // Ignored
22464            }
22465
22466            @Override
22467            public void onStatusChanged(int moveId, int status, long estMillis) {
22468                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22469            }
22470        };
22471
22472        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22473        storage.setPrimaryStorageUuid(volumeUuid, callback);
22474        return realMoveId;
22475    }
22476
22477    @Override
22478    public int getMoveStatus(int moveId) {
22479        mContext.enforceCallingOrSelfPermission(
22480                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22481        return mMoveCallbacks.mLastStatus.get(moveId);
22482    }
22483
22484    @Override
22485    public void registerMoveCallback(IPackageMoveObserver callback) {
22486        mContext.enforceCallingOrSelfPermission(
22487                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22488        mMoveCallbacks.register(callback);
22489    }
22490
22491    @Override
22492    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22493        mContext.enforceCallingOrSelfPermission(
22494                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22495        mMoveCallbacks.unregister(callback);
22496    }
22497
22498    @Override
22499    public boolean setInstallLocation(int loc) {
22500        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22501                null);
22502        if (getInstallLocation() == loc) {
22503            return true;
22504        }
22505        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22506                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22507            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22508                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22509            return true;
22510        }
22511        return false;
22512   }
22513
22514    @Override
22515    public int getInstallLocation() {
22516        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22517                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22518                PackageHelper.APP_INSTALL_AUTO);
22519    }
22520
22521    /** Called by UserManagerService */
22522    void cleanUpUser(UserManagerService userManager, int userHandle) {
22523        synchronized (mPackages) {
22524            mDirtyUsers.remove(userHandle);
22525            mUserNeedsBadging.delete(userHandle);
22526            mSettings.removeUserLPw(userHandle);
22527            mPendingBroadcasts.remove(userHandle);
22528            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22529            removeUnusedPackagesLPw(userManager, userHandle);
22530        }
22531    }
22532
22533    /**
22534     * We're removing userHandle and would like to remove any downloaded packages
22535     * that are no longer in use by any other user.
22536     * @param userHandle the user being removed
22537     */
22538    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22539        final boolean DEBUG_CLEAN_APKS = false;
22540        int [] users = userManager.getUserIds();
22541        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22542        while (psit.hasNext()) {
22543            PackageSetting ps = psit.next();
22544            if (ps.pkg == null) {
22545                continue;
22546            }
22547            final String packageName = ps.pkg.packageName;
22548            // Skip over if system app
22549            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22550                continue;
22551            }
22552            if (DEBUG_CLEAN_APKS) {
22553                Slog.i(TAG, "Checking package " + packageName);
22554            }
22555            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22556            if (keep) {
22557                if (DEBUG_CLEAN_APKS) {
22558                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22559                }
22560            } else {
22561                for (int i = 0; i < users.length; i++) {
22562                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22563                        keep = true;
22564                        if (DEBUG_CLEAN_APKS) {
22565                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22566                                    + users[i]);
22567                        }
22568                        break;
22569                    }
22570                }
22571            }
22572            if (!keep) {
22573                if (DEBUG_CLEAN_APKS) {
22574                    Slog.i(TAG, "  Removing package " + packageName);
22575                }
22576                mHandler.post(new Runnable() {
22577                    public void run() {
22578                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22579                                userHandle, 0);
22580                    } //end run
22581                });
22582            }
22583        }
22584    }
22585
22586    /** Called by UserManagerService */
22587    void createNewUser(int userId, String[] disallowedPackages) {
22588        synchronized (mInstallLock) {
22589            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22590        }
22591        synchronized (mPackages) {
22592            scheduleWritePackageRestrictionsLocked(userId);
22593            scheduleWritePackageListLocked(userId);
22594            applyFactoryDefaultBrowserLPw(userId);
22595            primeDomainVerificationsLPw(userId);
22596        }
22597    }
22598
22599    void onNewUserCreated(final int userId) {
22600        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22601        // If permission review for legacy apps is required, we represent
22602        // dagerous permissions for such apps as always granted runtime
22603        // permissions to keep per user flag state whether review is needed.
22604        // Hence, if a new user is added we have to propagate dangerous
22605        // permission grants for these legacy apps.
22606        if (mPermissionReviewRequired) {
22607            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
22608                    | UPDATE_PERMISSIONS_REPLACE_ALL);
22609        }
22610    }
22611
22612    @Override
22613    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22614        mContext.enforceCallingOrSelfPermission(
22615                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22616                "Only package verification agents can read the verifier device identity");
22617
22618        synchronized (mPackages) {
22619            return mSettings.getVerifierDeviceIdentityLPw();
22620        }
22621    }
22622
22623    @Override
22624    public void setPermissionEnforced(String permission, boolean enforced) {
22625        // TODO: Now that we no longer change GID for storage, this should to away.
22626        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22627                "setPermissionEnforced");
22628        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22629            synchronized (mPackages) {
22630                if (mSettings.mReadExternalStorageEnforced == null
22631                        || mSettings.mReadExternalStorageEnforced != enforced) {
22632                    mSettings.mReadExternalStorageEnforced = enforced;
22633                    mSettings.writeLPr();
22634                }
22635            }
22636            // kill any non-foreground processes so we restart them and
22637            // grant/revoke the GID.
22638            final IActivityManager am = ActivityManager.getService();
22639            if (am != null) {
22640                final long token = Binder.clearCallingIdentity();
22641                try {
22642                    am.killProcessesBelowForeground("setPermissionEnforcement");
22643                } catch (RemoteException e) {
22644                } finally {
22645                    Binder.restoreCallingIdentity(token);
22646                }
22647            }
22648        } else {
22649            throw new IllegalArgumentException("No selective enforcement for " + permission);
22650        }
22651    }
22652
22653    @Override
22654    @Deprecated
22655    public boolean isPermissionEnforced(String permission) {
22656        return true;
22657    }
22658
22659    @Override
22660    public boolean isStorageLow() {
22661        final long token = Binder.clearCallingIdentity();
22662        try {
22663            final DeviceStorageMonitorInternal
22664                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22665            if (dsm != null) {
22666                return dsm.isMemoryLow();
22667            } else {
22668                return false;
22669            }
22670        } finally {
22671            Binder.restoreCallingIdentity(token);
22672        }
22673    }
22674
22675    @Override
22676    public IPackageInstaller getPackageInstaller() {
22677        return mInstallerService;
22678    }
22679
22680    private boolean userNeedsBadging(int userId) {
22681        int index = mUserNeedsBadging.indexOfKey(userId);
22682        if (index < 0) {
22683            final UserInfo userInfo;
22684            final long token = Binder.clearCallingIdentity();
22685            try {
22686                userInfo = sUserManager.getUserInfo(userId);
22687            } finally {
22688                Binder.restoreCallingIdentity(token);
22689            }
22690            final boolean b;
22691            if (userInfo != null && userInfo.isManagedProfile()) {
22692                b = true;
22693            } else {
22694                b = false;
22695            }
22696            mUserNeedsBadging.put(userId, b);
22697            return b;
22698        }
22699        return mUserNeedsBadging.valueAt(index);
22700    }
22701
22702    @Override
22703    public KeySet getKeySetByAlias(String packageName, String alias) {
22704        if (packageName == null || alias == null) {
22705            return null;
22706        }
22707        synchronized(mPackages) {
22708            final PackageParser.Package pkg = mPackages.get(packageName);
22709            if (pkg == null) {
22710                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22711                throw new IllegalArgumentException("Unknown package: " + packageName);
22712            }
22713            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22714            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22715        }
22716    }
22717
22718    @Override
22719    public KeySet getSigningKeySet(String packageName) {
22720        if (packageName == null) {
22721            return null;
22722        }
22723        synchronized(mPackages) {
22724            final PackageParser.Package pkg = mPackages.get(packageName);
22725            if (pkg == null) {
22726                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22727                throw new IllegalArgumentException("Unknown package: " + packageName);
22728            }
22729            if (pkg.applicationInfo.uid != Binder.getCallingUid()
22730                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
22731                throw new SecurityException("May not access signing KeySet of other apps.");
22732            }
22733            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22734            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22735        }
22736    }
22737
22738    @Override
22739    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22740        if (packageName == null || ks == null) {
22741            return false;
22742        }
22743        synchronized(mPackages) {
22744            final PackageParser.Package pkg = mPackages.get(packageName);
22745            if (pkg == null) {
22746                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22747                throw new IllegalArgumentException("Unknown package: " + packageName);
22748            }
22749            IBinder ksh = ks.getToken();
22750            if (ksh instanceof KeySetHandle) {
22751                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22752                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22753            }
22754            return false;
22755        }
22756    }
22757
22758    @Override
22759    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22760        if (packageName == null || ks == null) {
22761            return false;
22762        }
22763        synchronized(mPackages) {
22764            final PackageParser.Package pkg = mPackages.get(packageName);
22765            if (pkg == null) {
22766                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22767                throw new IllegalArgumentException("Unknown package: " + packageName);
22768            }
22769            IBinder ksh = ks.getToken();
22770            if (ksh instanceof KeySetHandle) {
22771                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22772                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22773            }
22774            return false;
22775        }
22776    }
22777
22778    private void deletePackageIfUnusedLPr(final String packageName) {
22779        PackageSetting ps = mSettings.mPackages.get(packageName);
22780        if (ps == null) {
22781            return;
22782        }
22783        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22784            // TODO Implement atomic delete if package is unused
22785            // It is currently possible that the package will be deleted even if it is installed
22786            // after this method returns.
22787            mHandler.post(new Runnable() {
22788                public void run() {
22789                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22790                            0, PackageManager.DELETE_ALL_USERS);
22791                }
22792            });
22793        }
22794    }
22795
22796    /**
22797     * Check and throw if the given before/after packages would be considered a
22798     * downgrade.
22799     */
22800    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22801            throws PackageManagerException {
22802        if (after.versionCode < before.mVersionCode) {
22803            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22804                    "Update version code " + after.versionCode + " is older than current "
22805                    + before.mVersionCode);
22806        } else if (after.versionCode == before.mVersionCode) {
22807            if (after.baseRevisionCode < before.baseRevisionCode) {
22808                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22809                        "Update base revision code " + after.baseRevisionCode
22810                        + " is older than current " + before.baseRevisionCode);
22811            }
22812
22813            if (!ArrayUtils.isEmpty(after.splitNames)) {
22814                for (int i = 0; i < after.splitNames.length; i++) {
22815                    final String splitName = after.splitNames[i];
22816                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22817                    if (j != -1) {
22818                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22819                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22820                                    "Update split " + splitName + " revision code "
22821                                    + after.splitRevisionCodes[i] + " is older than current "
22822                                    + before.splitRevisionCodes[j]);
22823                        }
22824                    }
22825                }
22826            }
22827        }
22828    }
22829
22830    private static class MoveCallbacks extends Handler {
22831        private static final int MSG_CREATED = 1;
22832        private static final int MSG_STATUS_CHANGED = 2;
22833
22834        private final RemoteCallbackList<IPackageMoveObserver>
22835                mCallbacks = new RemoteCallbackList<>();
22836
22837        private final SparseIntArray mLastStatus = new SparseIntArray();
22838
22839        public MoveCallbacks(Looper looper) {
22840            super(looper);
22841        }
22842
22843        public void register(IPackageMoveObserver callback) {
22844            mCallbacks.register(callback);
22845        }
22846
22847        public void unregister(IPackageMoveObserver callback) {
22848            mCallbacks.unregister(callback);
22849        }
22850
22851        @Override
22852        public void handleMessage(Message msg) {
22853            final SomeArgs args = (SomeArgs) msg.obj;
22854            final int n = mCallbacks.beginBroadcast();
22855            for (int i = 0; i < n; i++) {
22856                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22857                try {
22858                    invokeCallback(callback, msg.what, args);
22859                } catch (RemoteException ignored) {
22860                }
22861            }
22862            mCallbacks.finishBroadcast();
22863            args.recycle();
22864        }
22865
22866        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22867                throws RemoteException {
22868            switch (what) {
22869                case MSG_CREATED: {
22870                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22871                    break;
22872                }
22873                case MSG_STATUS_CHANGED: {
22874                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22875                    break;
22876                }
22877            }
22878        }
22879
22880        private void notifyCreated(int moveId, Bundle extras) {
22881            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22882
22883            final SomeArgs args = SomeArgs.obtain();
22884            args.argi1 = moveId;
22885            args.arg2 = extras;
22886            obtainMessage(MSG_CREATED, args).sendToTarget();
22887        }
22888
22889        private void notifyStatusChanged(int moveId, int status) {
22890            notifyStatusChanged(moveId, status, -1);
22891        }
22892
22893        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22894            Slog.v(TAG, "Move " + moveId + " status " + status);
22895
22896            final SomeArgs args = SomeArgs.obtain();
22897            args.argi1 = moveId;
22898            args.argi2 = status;
22899            args.arg3 = estMillis;
22900            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22901
22902            synchronized (mLastStatus) {
22903                mLastStatus.put(moveId, status);
22904            }
22905        }
22906    }
22907
22908    private final static class OnPermissionChangeListeners extends Handler {
22909        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22910
22911        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22912                new RemoteCallbackList<>();
22913
22914        public OnPermissionChangeListeners(Looper looper) {
22915            super(looper);
22916        }
22917
22918        @Override
22919        public void handleMessage(Message msg) {
22920            switch (msg.what) {
22921                case MSG_ON_PERMISSIONS_CHANGED: {
22922                    final int uid = msg.arg1;
22923                    handleOnPermissionsChanged(uid);
22924                } break;
22925            }
22926        }
22927
22928        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22929            mPermissionListeners.register(listener);
22930
22931        }
22932
22933        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22934            mPermissionListeners.unregister(listener);
22935        }
22936
22937        public void onPermissionsChanged(int uid) {
22938            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22939                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22940            }
22941        }
22942
22943        private void handleOnPermissionsChanged(int uid) {
22944            final int count = mPermissionListeners.beginBroadcast();
22945            try {
22946                for (int i = 0; i < count; i++) {
22947                    IOnPermissionsChangeListener callback = mPermissionListeners
22948                            .getBroadcastItem(i);
22949                    try {
22950                        callback.onPermissionsChanged(uid);
22951                    } catch (RemoteException e) {
22952                        Log.e(TAG, "Permission listener is dead", e);
22953                    }
22954                }
22955            } finally {
22956                mPermissionListeners.finishBroadcast();
22957            }
22958        }
22959    }
22960
22961    private class PackageManagerInternalImpl extends PackageManagerInternal {
22962        @Override
22963        public void setLocationPackagesProvider(PackagesProvider provider) {
22964            synchronized (mPackages) {
22965                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
22966            }
22967        }
22968
22969        @Override
22970        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22971            synchronized (mPackages) {
22972                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
22973            }
22974        }
22975
22976        @Override
22977        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22978            synchronized (mPackages) {
22979                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
22980            }
22981        }
22982
22983        @Override
22984        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22985            synchronized (mPackages) {
22986                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
22987            }
22988        }
22989
22990        @Override
22991        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22992            synchronized (mPackages) {
22993                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
22994            }
22995        }
22996
22997        @Override
22998        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22999            synchronized (mPackages) {
23000                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
23001            }
23002        }
23003
23004        @Override
23005        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23006            synchronized (mPackages) {
23007                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
23008                        packageName, userId);
23009            }
23010        }
23011
23012        @Override
23013        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23014            synchronized (mPackages) {
23015                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23016                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
23017                        packageName, userId);
23018            }
23019        }
23020
23021        @Override
23022        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23023            synchronized (mPackages) {
23024                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
23025                        packageName, userId);
23026            }
23027        }
23028
23029        @Override
23030        public void setKeepUninstalledPackages(final List<String> packageList) {
23031            Preconditions.checkNotNull(packageList);
23032            List<String> removedFromList = null;
23033            synchronized (mPackages) {
23034                if (mKeepUninstalledPackages != null) {
23035                    final int packagesCount = mKeepUninstalledPackages.size();
23036                    for (int i = 0; i < packagesCount; i++) {
23037                        String oldPackage = mKeepUninstalledPackages.get(i);
23038                        if (packageList != null && packageList.contains(oldPackage)) {
23039                            continue;
23040                        }
23041                        if (removedFromList == null) {
23042                            removedFromList = new ArrayList<>();
23043                        }
23044                        removedFromList.add(oldPackage);
23045                    }
23046                }
23047                mKeepUninstalledPackages = new ArrayList<>(packageList);
23048                if (removedFromList != null) {
23049                    final int removedCount = removedFromList.size();
23050                    for (int i = 0; i < removedCount; i++) {
23051                        deletePackageIfUnusedLPr(removedFromList.get(i));
23052                    }
23053                }
23054            }
23055        }
23056
23057        @Override
23058        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23059            synchronized (mPackages) {
23060                // If we do not support permission review, done.
23061                if (!mPermissionReviewRequired) {
23062                    return false;
23063                }
23064
23065                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
23066                if (packageSetting == null) {
23067                    return false;
23068                }
23069
23070                // Permission review applies only to apps not supporting the new permission model.
23071                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
23072                    return false;
23073                }
23074
23075                // Legacy apps have the permission and get user consent on launch.
23076                PermissionsState permissionsState = packageSetting.getPermissionsState();
23077                return permissionsState.isPermissionReviewRequired(userId);
23078            }
23079        }
23080
23081        @Override
23082        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
23083            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
23084        }
23085
23086        @Override
23087        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23088                int userId) {
23089            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23090        }
23091
23092        @Override
23093        public void setDeviceAndProfileOwnerPackages(
23094                int deviceOwnerUserId, String deviceOwnerPackage,
23095                SparseArray<String> profileOwnerPackages) {
23096            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23097                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23098        }
23099
23100        @Override
23101        public boolean isPackageDataProtected(int userId, String packageName) {
23102            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23103        }
23104
23105        @Override
23106        public boolean isPackageEphemeral(int userId, String packageName) {
23107            synchronized (mPackages) {
23108                final PackageSetting ps = mSettings.mPackages.get(packageName);
23109                return ps != null ? ps.getInstantApp(userId) : false;
23110            }
23111        }
23112
23113        @Override
23114        public boolean wasPackageEverLaunched(String packageName, int userId) {
23115            synchronized (mPackages) {
23116                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23117            }
23118        }
23119
23120        @Override
23121        public void grantRuntimePermission(String packageName, String name, int userId,
23122                boolean overridePolicy) {
23123            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
23124                    overridePolicy);
23125        }
23126
23127        @Override
23128        public void revokeRuntimePermission(String packageName, String name, int userId,
23129                boolean overridePolicy) {
23130            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
23131                    overridePolicy);
23132        }
23133
23134        @Override
23135        public String getNameForUid(int uid) {
23136            return PackageManagerService.this.getNameForUid(uid);
23137        }
23138
23139        @Override
23140        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23141                Intent origIntent, String resolvedType, String callingPackage, int userId) {
23142            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23143                    responseObj, origIntent, resolvedType, callingPackage, userId);
23144        }
23145
23146        @Override
23147        public void grantEphemeralAccess(int userId, Intent intent,
23148                int targetAppId, int ephemeralAppId) {
23149            synchronized (mPackages) {
23150                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23151                        targetAppId, ephemeralAppId);
23152            }
23153        }
23154
23155        @Override
23156        public boolean isInstantAppInstallerComponent(ComponentName component) {
23157            synchronized (mPackages) {
23158                return component != null && component.equals(mInstantAppInstallerComponent);
23159            }
23160        }
23161
23162        @Override
23163        public void pruneInstantApps() {
23164            synchronized (mPackages) {
23165                mInstantAppRegistry.pruneInstantAppsLPw();
23166            }
23167        }
23168
23169        @Override
23170        public String getSetupWizardPackageName() {
23171            return mSetupWizardPackage;
23172        }
23173
23174        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23175            if (policy != null) {
23176                mExternalSourcesPolicy = policy;
23177            }
23178        }
23179
23180        @Override
23181        public boolean isPackagePersistent(String packageName) {
23182            synchronized (mPackages) {
23183                PackageParser.Package pkg = mPackages.get(packageName);
23184                return pkg != null
23185                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23186                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23187                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23188                        : false;
23189            }
23190        }
23191
23192        @Override
23193        public List<PackageInfo> getOverlayPackages(int userId) {
23194            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23195            synchronized (mPackages) {
23196                for (PackageParser.Package p : mPackages.values()) {
23197                    if (p.mOverlayTarget != null) {
23198                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23199                        if (pkg != null) {
23200                            overlayPackages.add(pkg);
23201                        }
23202                    }
23203                }
23204            }
23205            return overlayPackages;
23206        }
23207
23208        @Override
23209        public List<String> getTargetPackageNames(int userId) {
23210            List<String> targetPackages = new ArrayList<>();
23211            synchronized (mPackages) {
23212                for (PackageParser.Package p : mPackages.values()) {
23213                    if (p.mOverlayTarget == null) {
23214                        targetPackages.add(p.packageName);
23215                    }
23216                }
23217            }
23218            return targetPackages;
23219        }
23220
23221        @Override
23222        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23223                @Nullable List<String> overlayPackageNames) {
23224            synchronized (mPackages) {
23225                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23226                    Slog.e(TAG, "failed to find package " + targetPackageName);
23227                    return false;
23228                }
23229
23230                ArrayList<String> paths = null;
23231                if (overlayPackageNames != null) {
23232                    final int N = overlayPackageNames.size();
23233                    paths = new ArrayList<>(N);
23234                    for (int i = 0; i < N; i++) {
23235                        final String packageName = overlayPackageNames.get(i);
23236                        final PackageParser.Package pkg = mPackages.get(packageName);
23237                        if (pkg == null) {
23238                            Slog.e(TAG, "failed to find package " + packageName);
23239                            return false;
23240                        }
23241                        paths.add(pkg.baseCodePath);
23242                    }
23243                }
23244
23245                ArrayMap<String, ArrayList<String>> userSpecificOverlays =
23246                    mEnabledOverlayPaths.get(userId);
23247                if (userSpecificOverlays == null) {
23248                    userSpecificOverlays = new ArrayMap<>();
23249                    mEnabledOverlayPaths.put(userId, userSpecificOverlays);
23250                }
23251
23252                if (paths != null && paths.size() > 0) {
23253                    userSpecificOverlays.put(targetPackageName, paths);
23254                } else {
23255                    userSpecificOverlays.remove(targetPackageName);
23256                }
23257                return true;
23258            }
23259        }
23260
23261        @Override
23262        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23263                int flags, int userId) {
23264            return resolveIntentInternal(
23265                    intent, resolvedType, flags, userId, true /*includeInstantApps*/);
23266        }
23267
23268        @Override
23269        public ResolveInfo resolveService(Intent intent, String resolvedType,
23270                int flags, int userId, int callingUid) {
23271            return resolveServiceInternal(
23272                    intent, resolvedType, flags, userId, callingUid, true /*includeInstantApps*/);
23273        }
23274
23275
23276        @Override
23277        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23278            synchronized (mPackages) {
23279                mIsolatedOwners.put(isolatedUid, ownerUid);
23280            }
23281        }
23282
23283        @Override
23284        public void removeIsolatedUid(int isolatedUid) {
23285            synchronized (mPackages) {
23286                mIsolatedOwners.delete(isolatedUid);
23287            }
23288        }
23289    }
23290
23291    @Override
23292    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23293        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23294        synchronized (mPackages) {
23295            final long identity = Binder.clearCallingIdentity();
23296            try {
23297                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
23298                        packageNames, userId);
23299            } finally {
23300                Binder.restoreCallingIdentity(identity);
23301            }
23302        }
23303    }
23304
23305    @Override
23306    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23307        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23308        synchronized (mPackages) {
23309            final long identity = Binder.clearCallingIdentity();
23310            try {
23311                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
23312                        packageNames, userId);
23313            } finally {
23314                Binder.restoreCallingIdentity(identity);
23315            }
23316        }
23317    }
23318
23319    private static void enforceSystemOrPhoneCaller(String tag) {
23320        int callingUid = Binder.getCallingUid();
23321        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23322            throw new SecurityException(
23323                    "Cannot call " + tag + " from UID " + callingUid);
23324        }
23325    }
23326
23327    boolean isHistoricalPackageUsageAvailable() {
23328        return mPackageUsage.isHistoricalPackageUsageAvailable();
23329    }
23330
23331    /**
23332     * Return a <b>copy</b> of the collection of packages known to the package manager.
23333     * @return A copy of the values of mPackages.
23334     */
23335    Collection<PackageParser.Package> getPackages() {
23336        synchronized (mPackages) {
23337            return new ArrayList<>(mPackages.values());
23338        }
23339    }
23340
23341    /**
23342     * Logs process start information (including base APK hash) to the security log.
23343     * @hide
23344     */
23345    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23346            String apkFile, int pid) {
23347        if (!SecurityLog.isLoggingEnabled()) {
23348            return;
23349        }
23350        Bundle data = new Bundle();
23351        data.putLong("startTimestamp", System.currentTimeMillis());
23352        data.putString("processName", processName);
23353        data.putInt("uid", uid);
23354        data.putString("seinfo", seinfo);
23355        data.putString("apkFile", apkFile);
23356        data.putInt("pid", pid);
23357        Message msg = mProcessLoggingHandler.obtainMessage(
23358                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23359        msg.setData(data);
23360        mProcessLoggingHandler.sendMessage(msg);
23361    }
23362
23363    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23364        return mCompilerStats.getPackageStats(pkgName);
23365    }
23366
23367    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23368        return getOrCreateCompilerPackageStats(pkg.packageName);
23369    }
23370
23371    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23372        return mCompilerStats.getOrCreatePackageStats(pkgName);
23373    }
23374
23375    public void deleteCompilerPackageStats(String pkgName) {
23376        mCompilerStats.deletePackageStats(pkgName);
23377    }
23378
23379    @Override
23380    public int getInstallReason(String packageName, int userId) {
23381        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23382                true /* requireFullPermission */, false /* checkShell */,
23383                "get install reason");
23384        synchronized (mPackages) {
23385            final PackageSetting ps = mSettings.mPackages.get(packageName);
23386            if (ps != null) {
23387                return ps.getInstallReason(userId);
23388            }
23389        }
23390        return PackageManager.INSTALL_REASON_UNKNOWN;
23391    }
23392
23393    @Override
23394    public boolean canRequestPackageInstalls(String packageName, int userId) {
23395        int callingUid = Binder.getCallingUid();
23396        int uid = getPackageUid(packageName, 0, userId);
23397        if (callingUid != uid && callingUid != Process.ROOT_UID
23398                && callingUid != Process.SYSTEM_UID) {
23399            throw new SecurityException(
23400                    "Caller uid " + callingUid + " does not own package " + packageName);
23401        }
23402        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
23403        if (info == null) {
23404            return false;
23405        }
23406        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23407            throw new UnsupportedOperationException(
23408                    "Operation only supported on apps targeting Android O or higher");
23409        }
23410        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23411        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23412        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23413            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
23414        }
23415        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23416            return false;
23417        }
23418        if (mExternalSourcesPolicy != null) {
23419            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23420            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23421                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23422            }
23423        }
23424        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23425    }
23426
23427    @Override
23428    public ComponentName getInstantAppResolverSettingsComponent() {
23429        return mInstantAppResolverSettingsComponent;
23430    }
23431}
23432