PackageManagerService.java revision 492e9e851cadca62df84eaff1a3c1ba788492fba
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_NUMBER,
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    static final long DEFAULT_CONTAINER_WHITELIST_DURATION = 10 * 60 * 1000;
1186    final private DefaultContainerConnection mDefContainerConn =
1187            new DefaultContainerConnection();
1188    class DefaultContainerConnection implements ServiceConnection {
1189        public void onServiceConnected(ComponentName name, IBinder service) {
1190            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1191            final IMediaContainerService imcs = IMediaContainerService.Stub
1192                    .asInterface(Binder.allowBlocking(service));
1193            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1194        }
1195
1196        public void onServiceDisconnected(ComponentName name) {
1197            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1198        }
1199    }
1200
1201    // Recordkeeping of restore-after-install operations that are currently in flight
1202    // between the Package Manager and the Backup Manager
1203    static class PostInstallData {
1204        public InstallArgs args;
1205        public PackageInstalledInfo res;
1206
1207        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1208            args = _a;
1209            res = _r;
1210        }
1211    }
1212
1213    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1214    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1215
1216    // XML tags for backup/restore of various bits of state
1217    private static final String TAG_PREFERRED_BACKUP = "pa";
1218    private static final String TAG_DEFAULT_APPS = "da";
1219    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1220
1221    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1222    private static final String TAG_ALL_GRANTS = "rt-grants";
1223    private static final String TAG_GRANT = "grant";
1224    private static final String ATTR_PACKAGE_NAME = "pkg";
1225
1226    private static final String TAG_PERMISSION = "perm";
1227    private static final String ATTR_PERMISSION_NAME = "name";
1228    private static final String ATTR_IS_GRANTED = "g";
1229    private static final String ATTR_USER_SET = "set";
1230    private static final String ATTR_USER_FIXED = "fixed";
1231    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1232
1233    // System/policy permission grants are not backed up
1234    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1235            FLAG_PERMISSION_POLICY_FIXED
1236            | FLAG_PERMISSION_SYSTEM_FIXED
1237            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1238
1239    // And we back up these user-adjusted states
1240    private static final int USER_RUNTIME_GRANT_MASK =
1241            FLAG_PERMISSION_USER_SET
1242            | FLAG_PERMISSION_USER_FIXED
1243            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1244
1245    final @Nullable String mRequiredVerifierPackage;
1246    final @NonNull String mRequiredInstallerPackage;
1247    final @NonNull String mRequiredUninstallerPackage;
1248    final @Nullable String mSetupWizardPackage;
1249    final @Nullable String mStorageManagerPackage;
1250    final @NonNull String mServicesSystemSharedLibraryPackageName;
1251    final @NonNull String mSharedSystemSharedLibraryPackageName;
1252
1253    final boolean mPermissionReviewRequired;
1254
1255    private final PackageUsage mPackageUsage = new PackageUsage();
1256    private final CompilerStats mCompilerStats = new CompilerStats();
1257
1258    class PackageHandler extends Handler {
1259        private boolean mBound = false;
1260        final ArrayList<HandlerParams> mPendingInstalls =
1261            new ArrayList<HandlerParams>();
1262
1263        private boolean connectToService() {
1264            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1265                    " DefaultContainerService");
1266            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1267            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1268            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1269                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1270                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1271                mBound = true;
1272                return true;
1273            }
1274            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1275            return false;
1276        }
1277
1278        private void disconnectService() {
1279            mContainerService = null;
1280            mBound = false;
1281            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1282            mContext.unbindService(mDefContainerConn);
1283            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1284        }
1285
1286        PackageHandler(Looper looper) {
1287            super(looper);
1288        }
1289
1290        public void handleMessage(Message msg) {
1291            try {
1292                doHandleMessage(msg);
1293            } finally {
1294                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1295            }
1296        }
1297
1298        void doHandleMessage(Message msg) {
1299            switch (msg.what) {
1300                case INIT_COPY: {
1301                    HandlerParams params = (HandlerParams) msg.obj;
1302                    int idx = mPendingInstalls.size();
1303                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1304                    // If a bind was already initiated we dont really
1305                    // need to do anything. The pending install
1306                    // will be processed later on.
1307                    if (!mBound) {
1308                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1309                                System.identityHashCode(mHandler));
1310                        // If this is the only one pending we might
1311                        // have to bind to the service again.
1312                        if (!connectToService()) {
1313                            Slog.e(TAG, "Failed to bind to media container service");
1314                            params.serviceError();
1315                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1316                                    System.identityHashCode(mHandler));
1317                            if (params.traceMethod != null) {
1318                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1319                                        params.traceCookie);
1320                            }
1321                            return;
1322                        } else {
1323                            // Once we bind to the service, the first
1324                            // pending request will be processed.
1325                            mPendingInstalls.add(idx, params);
1326                        }
1327                    } else {
1328                        mPendingInstalls.add(idx, params);
1329                        // Already bound to the service. Just make
1330                        // sure we trigger off processing the first request.
1331                        if (idx == 0) {
1332                            mHandler.sendEmptyMessage(MCS_BOUND);
1333                        }
1334                    }
1335                    break;
1336                }
1337                case MCS_BOUND: {
1338                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1339                    if (msg.obj != null) {
1340                        mContainerService = (IMediaContainerService) msg.obj;
1341                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1342                                System.identityHashCode(mHandler));
1343                    }
1344                    if (mContainerService == null) {
1345                        if (!mBound) {
1346                            // Something seriously wrong since we are not bound and we are not
1347                            // waiting for connection. Bail out.
1348                            Slog.e(TAG, "Cannot bind to media container service");
1349                            for (HandlerParams params : mPendingInstalls) {
1350                                // Indicate service bind error
1351                                params.serviceError();
1352                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1353                                        System.identityHashCode(params));
1354                                if (params.traceMethod != null) {
1355                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1356                                            params.traceMethod, params.traceCookie);
1357                                }
1358                                return;
1359                            }
1360                            mPendingInstalls.clear();
1361                        } else {
1362                            Slog.w(TAG, "Waiting to connect to media container service");
1363                        }
1364                    } else if (mPendingInstalls.size() > 0) {
1365                        HandlerParams params = mPendingInstalls.get(0);
1366                        if (params != null) {
1367                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1368                                    System.identityHashCode(params));
1369                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1370                            if (params.startCopy()) {
1371                                // We are done...  look for more work or to
1372                                // go idle.
1373                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1374                                        "Checking for more work or unbind...");
1375                                // Delete pending install
1376                                if (mPendingInstalls.size() > 0) {
1377                                    mPendingInstalls.remove(0);
1378                                }
1379                                if (mPendingInstalls.size() == 0) {
1380                                    if (mBound) {
1381                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1382                                                "Posting delayed MCS_UNBIND");
1383                                        removeMessages(MCS_UNBIND);
1384                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1385                                        // Unbind after a little delay, to avoid
1386                                        // continual thrashing.
1387                                        sendMessageDelayed(ubmsg, 10000);
1388                                    }
1389                                } else {
1390                                    // There are more pending requests in queue.
1391                                    // Just post MCS_BOUND message to trigger processing
1392                                    // of next pending install.
1393                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1394                                            "Posting MCS_BOUND for next work");
1395                                    mHandler.sendEmptyMessage(MCS_BOUND);
1396                                }
1397                            }
1398                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1399                        }
1400                    } else {
1401                        // Should never happen ideally.
1402                        Slog.w(TAG, "Empty queue");
1403                    }
1404                    break;
1405                }
1406                case MCS_RECONNECT: {
1407                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1408                    if (mPendingInstalls.size() > 0) {
1409                        if (mBound) {
1410                            disconnectService();
1411                        }
1412                        if (!connectToService()) {
1413                            Slog.e(TAG, "Failed to bind to media container service");
1414                            for (HandlerParams params : mPendingInstalls) {
1415                                // Indicate service bind error
1416                                params.serviceError();
1417                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1418                                        System.identityHashCode(params));
1419                            }
1420                            mPendingInstalls.clear();
1421                        }
1422                    }
1423                    break;
1424                }
1425                case MCS_UNBIND: {
1426                    // If there is no actual work left, then time to unbind.
1427                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1428
1429                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1430                        if (mBound) {
1431                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1432
1433                            disconnectService();
1434                        }
1435                    } else if (mPendingInstalls.size() > 0) {
1436                        // There are more pending requests in queue.
1437                        // Just post MCS_BOUND message to trigger processing
1438                        // of next pending install.
1439                        mHandler.sendEmptyMessage(MCS_BOUND);
1440                    }
1441
1442                    break;
1443                }
1444                case MCS_GIVE_UP: {
1445                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1446                    HandlerParams params = mPendingInstalls.remove(0);
1447                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1448                            System.identityHashCode(params));
1449                    break;
1450                }
1451                case SEND_PENDING_BROADCAST: {
1452                    String packages[];
1453                    ArrayList<String> components[];
1454                    int size = 0;
1455                    int uids[];
1456                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1457                    synchronized (mPackages) {
1458                        if (mPendingBroadcasts == null) {
1459                            return;
1460                        }
1461                        size = mPendingBroadcasts.size();
1462                        if (size <= 0) {
1463                            // Nothing to be done. Just return
1464                            return;
1465                        }
1466                        packages = new String[size];
1467                        components = new ArrayList[size];
1468                        uids = new int[size];
1469                        int i = 0;  // filling out the above arrays
1470
1471                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1472                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1473                            Iterator<Map.Entry<String, ArrayList<String>>> it
1474                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1475                                            .entrySet().iterator();
1476                            while (it.hasNext() && i < size) {
1477                                Map.Entry<String, ArrayList<String>> ent = it.next();
1478                                packages[i] = ent.getKey();
1479                                components[i] = ent.getValue();
1480                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1481                                uids[i] = (ps != null)
1482                                        ? UserHandle.getUid(packageUserId, ps.appId)
1483                                        : -1;
1484                                i++;
1485                            }
1486                        }
1487                        size = i;
1488                        mPendingBroadcasts.clear();
1489                    }
1490                    // Send broadcasts
1491                    for (int i = 0; i < size; i++) {
1492                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1493                    }
1494                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1495                    break;
1496                }
1497                case START_CLEANING_PACKAGE: {
1498                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1499                    final String packageName = (String)msg.obj;
1500                    final int userId = msg.arg1;
1501                    final boolean andCode = msg.arg2 != 0;
1502                    synchronized (mPackages) {
1503                        if (userId == UserHandle.USER_ALL) {
1504                            int[] users = sUserManager.getUserIds();
1505                            for (int user : users) {
1506                                mSettings.addPackageToCleanLPw(
1507                                        new PackageCleanItem(user, packageName, andCode));
1508                            }
1509                        } else {
1510                            mSettings.addPackageToCleanLPw(
1511                                    new PackageCleanItem(userId, packageName, andCode));
1512                        }
1513                    }
1514                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1515                    startCleaningPackages();
1516                } break;
1517                case POST_INSTALL: {
1518                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1519
1520                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1521                    final boolean didRestore = (msg.arg2 != 0);
1522                    mRunningInstalls.delete(msg.arg1);
1523
1524                    if (data != null) {
1525                        InstallArgs args = data.args;
1526                        PackageInstalledInfo parentRes = data.res;
1527
1528                        final boolean grantPermissions = (args.installFlags
1529                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1530                        final boolean killApp = (args.installFlags
1531                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1532                        final String[] grantedPermissions = args.installGrantPermissions;
1533
1534                        // Handle the parent package
1535                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1536                                grantedPermissions, didRestore, args.installerPackageName,
1537                                args.observer);
1538
1539                        // Handle the child packages
1540                        final int childCount = (parentRes.addedChildPackages != null)
1541                                ? parentRes.addedChildPackages.size() : 0;
1542                        for (int i = 0; i < childCount; i++) {
1543                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1544                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1545                                    grantedPermissions, false, args.installerPackageName,
1546                                    args.observer);
1547                        }
1548
1549                        // Log tracing if needed
1550                        if (args.traceMethod != null) {
1551                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1552                                    args.traceCookie);
1553                        }
1554                    } else {
1555                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1556                    }
1557
1558                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1559                } break;
1560                case UPDATED_MEDIA_STATUS: {
1561                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1562                    boolean reportStatus = msg.arg1 == 1;
1563                    boolean doGc = msg.arg2 == 1;
1564                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1565                    if (doGc) {
1566                        // Force a gc to clear up stale containers.
1567                        Runtime.getRuntime().gc();
1568                    }
1569                    if (msg.obj != null) {
1570                        @SuppressWarnings("unchecked")
1571                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1572                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1573                        // Unload containers
1574                        unloadAllContainers(args);
1575                    }
1576                    if (reportStatus) {
1577                        try {
1578                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1579                                    "Invoking StorageManagerService call back");
1580                            PackageHelper.getStorageManager().finishMediaUpdate();
1581                        } catch (RemoteException e) {
1582                            Log.e(TAG, "StorageManagerService not running?");
1583                        }
1584                    }
1585                } break;
1586                case WRITE_SETTINGS: {
1587                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1588                    synchronized (mPackages) {
1589                        removeMessages(WRITE_SETTINGS);
1590                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1591                        mSettings.writeLPr();
1592                        mDirtyUsers.clear();
1593                    }
1594                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1595                } break;
1596                case WRITE_PACKAGE_RESTRICTIONS: {
1597                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1598                    synchronized (mPackages) {
1599                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1600                        for (int userId : mDirtyUsers) {
1601                            mSettings.writePackageRestrictionsLPr(userId);
1602                        }
1603                        mDirtyUsers.clear();
1604                    }
1605                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1606                } break;
1607                case WRITE_PACKAGE_LIST: {
1608                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1609                    synchronized (mPackages) {
1610                        removeMessages(WRITE_PACKAGE_LIST);
1611                        mSettings.writePackageListLPr(msg.arg1);
1612                    }
1613                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1614                } break;
1615                case CHECK_PENDING_VERIFICATION: {
1616                    final int verificationId = msg.arg1;
1617                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1618
1619                    if ((state != null) && !state.timeoutExtended()) {
1620                        final InstallArgs args = state.getInstallArgs();
1621                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1622
1623                        Slog.i(TAG, "Verification timed out for " + originUri);
1624                        mPendingVerification.remove(verificationId);
1625
1626                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1627
1628                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1629                            Slog.i(TAG, "Continuing with installation of " + originUri);
1630                            state.setVerifierResponse(Binder.getCallingUid(),
1631                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1632                            broadcastPackageVerified(verificationId, originUri,
1633                                    PackageManager.VERIFICATION_ALLOW,
1634                                    state.getInstallArgs().getUser());
1635                            try {
1636                                ret = args.copyApk(mContainerService, true);
1637                            } catch (RemoteException e) {
1638                                Slog.e(TAG, "Could not contact the ContainerService");
1639                            }
1640                        } else {
1641                            broadcastPackageVerified(verificationId, originUri,
1642                                    PackageManager.VERIFICATION_REJECT,
1643                                    state.getInstallArgs().getUser());
1644                        }
1645
1646                        Trace.asyncTraceEnd(
1647                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1648
1649                        processPendingInstall(args, ret);
1650                        mHandler.sendEmptyMessage(MCS_UNBIND);
1651                    }
1652                    break;
1653                }
1654                case PACKAGE_VERIFIED: {
1655                    final int verificationId = msg.arg1;
1656
1657                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1658                    if (state == null) {
1659                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1660                        break;
1661                    }
1662
1663                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1664
1665                    state.setVerifierResponse(response.callerUid, response.code);
1666
1667                    if (state.isVerificationComplete()) {
1668                        mPendingVerification.remove(verificationId);
1669
1670                        final InstallArgs args = state.getInstallArgs();
1671                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1672
1673                        int ret;
1674                        if (state.isInstallAllowed()) {
1675                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1676                            broadcastPackageVerified(verificationId, originUri,
1677                                    response.code, state.getInstallArgs().getUser());
1678                            try {
1679                                ret = args.copyApk(mContainerService, true);
1680                            } catch (RemoteException e) {
1681                                Slog.e(TAG, "Could not contact the ContainerService");
1682                            }
1683                        } else {
1684                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1685                        }
1686
1687                        Trace.asyncTraceEnd(
1688                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1689
1690                        processPendingInstall(args, ret);
1691                        mHandler.sendEmptyMessage(MCS_UNBIND);
1692                    }
1693
1694                    break;
1695                }
1696                case START_INTENT_FILTER_VERIFICATIONS: {
1697                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1698                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1699                            params.replacing, params.pkg);
1700                    break;
1701                }
1702                case INTENT_FILTER_VERIFIED: {
1703                    final int verificationId = msg.arg1;
1704
1705                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1706                            verificationId);
1707                    if (state == null) {
1708                        Slog.w(TAG, "Invalid IntentFilter verification token "
1709                                + verificationId + " received");
1710                        break;
1711                    }
1712
1713                    final int userId = state.getUserId();
1714
1715                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1716                            "Processing IntentFilter verification with token:"
1717                            + verificationId + " and userId:" + userId);
1718
1719                    final IntentFilterVerificationResponse response =
1720                            (IntentFilterVerificationResponse) msg.obj;
1721
1722                    state.setVerifierResponse(response.callerUid, response.code);
1723
1724                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1725                            "IntentFilter verification with token:" + verificationId
1726                            + " and userId:" + userId
1727                            + " is settings verifier response with response code:"
1728                            + response.code);
1729
1730                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1731                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1732                                + response.getFailedDomainsString());
1733                    }
1734
1735                    if (state.isVerificationComplete()) {
1736                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1737                    } else {
1738                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1739                                "IntentFilter verification with token:" + verificationId
1740                                + " was not said to be complete");
1741                    }
1742
1743                    break;
1744                }
1745                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1746                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1747                            mInstantAppResolverConnection,
1748                            (InstantAppRequest) msg.obj,
1749                            mInstantAppInstallerActivity,
1750                            mHandler);
1751                }
1752            }
1753        }
1754    }
1755
1756    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1757            boolean killApp, String[] grantedPermissions,
1758            boolean launchedForRestore, String installerPackage,
1759            IPackageInstallObserver2 installObserver) {
1760        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1761            // Send the removed broadcasts
1762            if (res.removedInfo != null) {
1763                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1764            }
1765
1766            // Now that we successfully installed the package, grant runtime
1767            // permissions if requested before broadcasting the install. Also
1768            // for legacy apps in permission review mode we clear the permission
1769            // review flag which is used to emulate runtime permissions for
1770            // legacy apps.
1771            if (grantPermissions) {
1772                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1773            }
1774
1775            final boolean update = res.removedInfo != null
1776                    && res.removedInfo.removedPackage != null;
1777
1778            // If this is the first time we have child packages for a disabled privileged
1779            // app that had no children, we grant requested runtime permissions to the new
1780            // children if the parent on the system image had them already granted.
1781            if (res.pkg.parentPackage != null) {
1782                synchronized (mPackages) {
1783                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1784                }
1785            }
1786
1787            synchronized (mPackages) {
1788                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1789            }
1790
1791            final String packageName = res.pkg.applicationInfo.packageName;
1792
1793            // Determine the set of users who are adding this package for
1794            // the first time vs. those who are seeing an update.
1795            int[] firstUsers = EMPTY_INT_ARRAY;
1796            int[] updateUsers = EMPTY_INT_ARRAY;
1797            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1798            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1799            for (int newUser : res.newUsers) {
1800                if (ps.getInstantApp(newUser)) {
1801                    continue;
1802                }
1803                if (allNewUsers) {
1804                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1805                    continue;
1806                }
1807                boolean isNew = true;
1808                for (int origUser : res.origUsers) {
1809                    if (origUser == newUser) {
1810                        isNew = false;
1811                        break;
1812                    }
1813                }
1814                if (isNew) {
1815                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1816                } else {
1817                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1818                }
1819            }
1820
1821            // Send installed broadcasts if the package is not a static shared lib.
1822            if (res.pkg.staticSharedLibName == null) {
1823                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1824
1825                // Send added for users that see the package for the first time
1826                // sendPackageAddedForNewUsers also deals with system apps
1827                int appId = UserHandle.getAppId(res.uid);
1828                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1829                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1830
1831                // Send added for users that don't see the package for the first time
1832                Bundle extras = new Bundle(1);
1833                extras.putInt(Intent.EXTRA_UID, res.uid);
1834                if (update) {
1835                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1836                }
1837                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1838                        extras, 0 /*flags*/, null /*targetPackage*/,
1839                        null /*finishedReceiver*/, updateUsers);
1840
1841                // Send replaced for users that don't see the package for the first time
1842                if (update) {
1843                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1844                            packageName, extras, 0 /*flags*/,
1845                            null /*targetPackage*/, null /*finishedReceiver*/,
1846                            updateUsers);
1847                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1848                            null /*package*/, null /*extras*/, 0 /*flags*/,
1849                            packageName /*targetPackage*/,
1850                            null /*finishedReceiver*/, updateUsers);
1851                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1852                    // First-install and we did a restore, so we're responsible for the
1853                    // first-launch broadcast.
1854                    if (DEBUG_BACKUP) {
1855                        Slog.i(TAG, "Post-restore of " + packageName
1856                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1857                    }
1858                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1859                }
1860
1861                // Send broadcast package appeared if forward locked/external for all users
1862                // treat asec-hosted packages like removable media on upgrade
1863                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1864                    if (DEBUG_INSTALL) {
1865                        Slog.i(TAG, "upgrading pkg " + res.pkg
1866                                + " is ASEC-hosted -> AVAILABLE");
1867                    }
1868                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1869                    ArrayList<String> pkgList = new ArrayList<>(1);
1870                    pkgList.add(packageName);
1871                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1872                }
1873            }
1874
1875            // Work that needs to happen on first install within each user
1876            if (firstUsers != null && firstUsers.length > 0) {
1877                synchronized (mPackages) {
1878                    for (int userId : firstUsers) {
1879                        // If this app is a browser and it's newly-installed for some
1880                        // users, clear any default-browser state in those users. The
1881                        // app's nature doesn't depend on the user, so we can just check
1882                        // its browser nature in any user and generalize.
1883                        if (packageIsBrowser(packageName, userId)) {
1884                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1885                        }
1886
1887                        // We may also need to apply pending (restored) runtime
1888                        // permission grants within these users.
1889                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1890                    }
1891                }
1892            }
1893
1894            // Log current value of "unknown sources" setting
1895            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1896                    getUnknownSourcesSettings());
1897
1898            // Force a gc to clear up things
1899            Runtime.getRuntime().gc();
1900
1901            // Remove the replaced package's older resources safely now
1902            // We delete after a gc for applications  on sdcard.
1903            if (res.removedInfo != null && res.removedInfo.args != null) {
1904                synchronized (mInstallLock) {
1905                    res.removedInfo.args.doPostDeleteLI(true);
1906                }
1907            }
1908
1909            // Notify DexManager that the package was installed for new users.
1910            // The updated users should already be indexed and the package code paths
1911            // should not change.
1912            // Don't notify the manager for ephemeral apps as they are not expected to
1913            // survive long enough to benefit of background optimizations.
1914            for (int userId : firstUsers) {
1915                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
1916                mDexManager.notifyPackageInstalled(info, userId);
1917            }
1918        }
1919
1920        // If someone is watching installs - notify them
1921        if (installObserver != null) {
1922            try {
1923                Bundle extras = extrasForInstallResult(res);
1924                installObserver.onPackageInstalled(res.name, res.returnCode,
1925                        res.returnMsg, extras);
1926            } catch (RemoteException e) {
1927                Slog.i(TAG, "Observer no longer exists.");
1928            }
1929        }
1930    }
1931
1932    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1933            PackageParser.Package pkg) {
1934        if (pkg.parentPackage == null) {
1935            return;
1936        }
1937        if (pkg.requestedPermissions == null) {
1938            return;
1939        }
1940        final PackageSetting disabledSysParentPs = mSettings
1941                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1942        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1943                || !disabledSysParentPs.isPrivileged()
1944                || (disabledSysParentPs.childPackageNames != null
1945                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1946            return;
1947        }
1948        final int[] allUserIds = sUserManager.getUserIds();
1949        final int permCount = pkg.requestedPermissions.size();
1950        for (int i = 0; i < permCount; i++) {
1951            String permission = pkg.requestedPermissions.get(i);
1952            BasePermission bp = mSettings.mPermissions.get(permission);
1953            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1954                continue;
1955            }
1956            for (int userId : allUserIds) {
1957                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1958                        permission, userId)) {
1959                    grantRuntimePermission(pkg.packageName, permission, userId);
1960                }
1961            }
1962        }
1963    }
1964
1965    private StorageEventListener mStorageListener = new StorageEventListener() {
1966        @Override
1967        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1968            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1969                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1970                    final String volumeUuid = vol.getFsUuid();
1971
1972                    // Clean up any users or apps that were removed or recreated
1973                    // while this volume was missing
1974                    sUserManager.reconcileUsers(volumeUuid);
1975                    reconcileApps(volumeUuid);
1976
1977                    // Clean up any install sessions that expired or were
1978                    // cancelled while this volume was missing
1979                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1980
1981                    loadPrivatePackages(vol);
1982
1983                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1984                    unloadPrivatePackages(vol);
1985                }
1986            }
1987
1988            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1989                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1990                    updateExternalMediaStatus(true, false);
1991                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1992                    updateExternalMediaStatus(false, false);
1993                }
1994            }
1995        }
1996
1997        @Override
1998        public void onVolumeForgotten(String fsUuid) {
1999            if (TextUtils.isEmpty(fsUuid)) {
2000                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2001                return;
2002            }
2003
2004            // Remove any apps installed on the forgotten volume
2005            synchronized (mPackages) {
2006                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2007                for (PackageSetting ps : packages) {
2008                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2009                    deletePackageVersioned(new VersionedPackage(ps.name,
2010                            PackageManager.VERSION_CODE_HIGHEST),
2011                            new LegacyPackageDeleteObserver(null).getBinder(),
2012                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2013                    // Try very hard to release any references to this package
2014                    // so we don't risk the system server being killed due to
2015                    // open FDs
2016                    AttributeCache.instance().removePackage(ps.name);
2017                }
2018
2019                mSettings.onVolumeForgotten(fsUuid);
2020                mSettings.writeLPr();
2021            }
2022        }
2023    };
2024
2025    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2026            String[] grantedPermissions) {
2027        for (int userId : userIds) {
2028            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2029        }
2030    }
2031
2032    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2033            String[] grantedPermissions) {
2034        SettingBase sb = (SettingBase) pkg.mExtras;
2035        if (sb == null) {
2036            return;
2037        }
2038
2039        PermissionsState permissionsState = sb.getPermissionsState();
2040
2041        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2042                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2043
2044        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2045                >= Build.VERSION_CODES.M;
2046
2047        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2048
2049        for (String permission : pkg.requestedPermissions) {
2050            final BasePermission bp;
2051            synchronized (mPackages) {
2052                bp = mSettings.mPermissions.get(permission);
2053            }
2054            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2055                    && (!instantApp || bp.isInstant())
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
2390            // when upgrading from pre-M, promote system app permissions from install to runtime
2391            mPromoteSystemApps =
2392                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2393
2394            // When upgrading from pre-N, we need to handle package extraction like first boot,
2395            // as there is no profiling data available.
2396            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2397
2398            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2399
2400            // save off the names of pre-existing system packages prior to scanning; we don't
2401            // want to automatically grant runtime permissions for new system apps
2402            if (mPromoteSystemApps) {
2403                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2404                while (pkgSettingIter.hasNext()) {
2405                    PackageSetting ps = pkgSettingIter.next();
2406                    if (isSystemApp(ps)) {
2407                        mExistingSystemPackages.add(ps.name);
2408                    }
2409                }
2410            }
2411
2412            mCacheDir = preparePackageParserCache(mIsUpgrade);
2413
2414            // Set flag to monitor and not change apk file paths when
2415            // scanning install directories.
2416            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2417
2418            if (mIsUpgrade || mFirstBoot) {
2419                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2420            }
2421
2422            // Collect vendor overlay packages. (Do this before scanning any apps.)
2423            // For security and version matching reason, only consider
2424            // overlay packages if they reside in the right directory.
2425            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2426                    | PackageParser.PARSE_IS_SYSTEM
2427                    | PackageParser.PARSE_IS_SYSTEM_DIR
2428                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2429
2430            // Find base frameworks (resource packages without code).
2431            scanDirTracedLI(frameworkDir, mDefParseFlags
2432                    | PackageParser.PARSE_IS_SYSTEM
2433                    | PackageParser.PARSE_IS_SYSTEM_DIR
2434                    | PackageParser.PARSE_IS_PRIVILEGED,
2435                    scanFlags | SCAN_NO_DEX, 0);
2436
2437            // Collected privileged system packages.
2438            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2439            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2440                    | PackageParser.PARSE_IS_SYSTEM
2441                    | PackageParser.PARSE_IS_SYSTEM_DIR
2442                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2443
2444            // Collect ordinary system packages.
2445            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2446            scanDirTracedLI(systemAppDir, mDefParseFlags
2447                    | PackageParser.PARSE_IS_SYSTEM
2448                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2449
2450            // Collect all vendor packages.
2451            File vendorAppDir = new File("/vendor/app");
2452            try {
2453                vendorAppDir = vendorAppDir.getCanonicalFile();
2454            } catch (IOException e) {
2455                // failed to look up canonical path, continue with original one
2456            }
2457            scanDirTracedLI(vendorAppDir, mDefParseFlags
2458                    | PackageParser.PARSE_IS_SYSTEM
2459                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2460
2461            // Collect all OEM packages.
2462            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2463            scanDirTracedLI(oemAppDir, mDefParseFlags
2464                    | PackageParser.PARSE_IS_SYSTEM
2465                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2466
2467            // Prune any system packages that no longer exist.
2468            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2469            if (!mOnlyCore) {
2470                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2471                while (psit.hasNext()) {
2472                    PackageSetting ps = psit.next();
2473
2474                    /*
2475                     * If this is not a system app, it can't be a
2476                     * disable system app.
2477                     */
2478                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2479                        continue;
2480                    }
2481
2482                    /*
2483                     * If the package is scanned, it's not erased.
2484                     */
2485                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2486                    if (scannedPkg != null) {
2487                        /*
2488                         * If the system app is both scanned and in the
2489                         * disabled packages list, then it must have been
2490                         * added via OTA. Remove it from the currently
2491                         * scanned package so the previously user-installed
2492                         * application can be scanned.
2493                         */
2494                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2495                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2496                                    + ps.name + "; removing system app.  Last known codePath="
2497                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2498                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2499                                    + scannedPkg.mVersionCode);
2500                            removePackageLI(scannedPkg, true);
2501                            mExpectingBetter.put(ps.name, ps.codePath);
2502                        }
2503
2504                        continue;
2505                    }
2506
2507                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2508                        psit.remove();
2509                        logCriticalInfo(Log.WARN, "System package " + ps.name
2510                                + " no longer exists; it's data will be wiped");
2511                        // Actual deletion of code and data will be handled by later
2512                        // reconciliation step
2513                    } else {
2514                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2515                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2516                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2517                        }
2518                    }
2519                }
2520            }
2521
2522            //look for any incomplete package installations
2523            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2524            for (int i = 0; i < deletePkgsList.size(); i++) {
2525                // Actual deletion of code and data will be handled by later
2526                // reconciliation step
2527                final String packageName = deletePkgsList.get(i).name;
2528                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2529                synchronized (mPackages) {
2530                    mSettings.removePackageLPw(packageName);
2531                }
2532            }
2533
2534            //delete tmp files
2535            deleteTempPackageFiles();
2536
2537            // Remove any shared userIDs that have no associated packages
2538            mSettings.pruneSharedUsersLPw();
2539
2540            if (!mOnlyCore) {
2541                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2542                        SystemClock.uptimeMillis());
2543                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2544
2545                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2546                        | PackageParser.PARSE_FORWARD_LOCK,
2547                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2548
2549                /**
2550                 * Remove disable package settings for any updated system
2551                 * apps that were removed via an OTA. If they're not a
2552                 * previously-updated app, remove them completely.
2553                 * Otherwise, just revoke their system-level permissions.
2554                 */
2555                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2556                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2557                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2558
2559                    String msg;
2560                    if (deletedPkg == null) {
2561                        msg = "Updated system package " + deletedAppName
2562                                + " no longer exists; it's data will be wiped";
2563                        // Actual deletion of code and data will be handled by later
2564                        // reconciliation step
2565                    } else {
2566                        msg = "Updated system app + " + deletedAppName
2567                                + " no longer present; removing system privileges for "
2568                                + deletedAppName;
2569
2570                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2571
2572                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2573                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2574                    }
2575                    logCriticalInfo(Log.WARN, msg);
2576                }
2577
2578                /**
2579                 * Make sure all system apps that we expected to appear on
2580                 * the userdata partition actually showed up. If they never
2581                 * appeared, crawl back and revive the system version.
2582                 */
2583                for (int i = 0; i < mExpectingBetter.size(); i++) {
2584                    final String packageName = mExpectingBetter.keyAt(i);
2585                    if (!mPackages.containsKey(packageName)) {
2586                        final File scanFile = mExpectingBetter.valueAt(i);
2587
2588                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2589                                + " but never showed up; reverting to system");
2590
2591                        int reparseFlags = mDefParseFlags;
2592                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2593                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2594                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2595                                    | PackageParser.PARSE_IS_PRIVILEGED;
2596                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2597                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2598                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2599                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2600                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2601                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2602                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2603                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2604                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2605                        } else {
2606                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2607                            continue;
2608                        }
2609
2610                        mSettings.enableSystemPackageLPw(packageName);
2611
2612                        try {
2613                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2614                        } catch (PackageManagerException e) {
2615                            Slog.e(TAG, "Failed to parse original system package: "
2616                                    + e.getMessage());
2617                        }
2618                    }
2619                }
2620            }
2621            mExpectingBetter.clear();
2622
2623            // Resolve the storage manager.
2624            mStorageManagerPackage = getStorageManagerPackageName();
2625
2626            // Resolve protected action filters. Only the setup wizard is allowed to
2627            // have a high priority filter for these actions.
2628            mSetupWizardPackage = getSetupWizardPackageName();
2629            if (mProtectedFilters.size() > 0) {
2630                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2631                    Slog.i(TAG, "No setup wizard;"
2632                        + " All protected intents capped to priority 0");
2633                }
2634                for (ActivityIntentInfo filter : mProtectedFilters) {
2635                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2636                        if (DEBUG_FILTERS) {
2637                            Slog.i(TAG, "Found setup wizard;"
2638                                + " allow priority " + filter.getPriority() + ";"
2639                                + " package: " + filter.activity.info.packageName
2640                                + " activity: " + filter.activity.className
2641                                + " priority: " + filter.getPriority());
2642                        }
2643                        // skip setup wizard; allow it to keep the high priority filter
2644                        continue;
2645                    }
2646                    Slog.w(TAG, "Protected action; cap priority to 0;"
2647                            + " package: " + filter.activity.info.packageName
2648                            + " activity: " + filter.activity.className
2649                            + " origPrio: " + filter.getPriority());
2650                    filter.setPriority(0);
2651                }
2652            }
2653            mDeferProtectedFilters = false;
2654            mProtectedFilters.clear();
2655
2656            // Now that we know all of the shared libraries, update all clients to have
2657            // the correct library paths.
2658            updateAllSharedLibrariesLPw(null);
2659
2660            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2661                // NOTE: We ignore potential failures here during a system scan (like
2662                // the rest of the commands above) because there's precious little we
2663                // can do about it. A settings error is reported, though.
2664                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2665            }
2666
2667            // Now that we know all the packages we are keeping,
2668            // read and update their last usage times.
2669            mPackageUsage.read(mPackages);
2670            mCompilerStats.read();
2671
2672            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2673                    SystemClock.uptimeMillis());
2674            Slog.i(TAG, "Time to scan packages: "
2675                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2676                    + " seconds");
2677
2678            // If the platform SDK has changed since the last time we booted,
2679            // we need to re-grant app permission to catch any new ones that
2680            // appear.  This is really a hack, and means that apps can in some
2681            // cases get permissions that the user didn't initially explicitly
2682            // allow...  it would be nice to have some better way to handle
2683            // this situation.
2684            int updateFlags = UPDATE_PERMISSIONS_ALL;
2685            if (ver.sdkVersion != mSdkVersion) {
2686                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2687                        + mSdkVersion + "; regranting permissions for internal storage");
2688                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2689            }
2690            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2691            ver.sdkVersion = mSdkVersion;
2692
2693            // If this is the first boot or an update from pre-M, and it is a normal
2694            // boot, then we need to initialize the default preferred apps across
2695            // all defined users.
2696            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2697                for (UserInfo user : sUserManager.getUsers(true)) {
2698                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2699                    applyFactoryDefaultBrowserLPw(user.id);
2700                    primeDomainVerificationsLPw(user.id);
2701                }
2702            }
2703
2704            // Prepare storage for system user really early during boot,
2705            // since core system apps like SettingsProvider and SystemUI
2706            // can't wait for user to start
2707            final int storageFlags;
2708            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2709                storageFlags = StorageManager.FLAG_STORAGE_DE;
2710            } else {
2711                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2712            }
2713            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2714                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2715                    true /* onlyCoreApps */);
2716            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2717                if (deferPackages == null || deferPackages.isEmpty()) {
2718                    return;
2719                }
2720                int count = 0;
2721                for (String pkgName : deferPackages) {
2722                    PackageParser.Package pkg = null;
2723                    synchronized (mPackages) {
2724                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2725                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2726                            pkg = ps.pkg;
2727                        }
2728                    }
2729                    if (pkg != null) {
2730                        synchronized (mInstallLock) {
2731                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2732                                    true /* maybeMigrateAppData */);
2733                        }
2734                        count++;
2735                    }
2736                }
2737                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2738            }, "prepareAppData");
2739
2740            // If this is first boot after an OTA, and a normal boot, then
2741            // we need to clear code cache directories.
2742            // Note that we do *not* clear the application profiles. These remain valid
2743            // across OTAs and are used to drive profile verification (post OTA) and
2744            // profile compilation (without waiting to collect a fresh set of profiles).
2745            if (mIsUpgrade && !onlyCore) {
2746                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2747                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2748                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2749                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2750                        // No apps are running this early, so no need to freeze
2751                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2752                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2753                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2754                    }
2755                }
2756                ver.fingerprint = Build.FINGERPRINT;
2757            }
2758
2759            checkDefaultBrowser();
2760
2761            // clear only after permissions and other defaults have been updated
2762            mExistingSystemPackages.clear();
2763            mPromoteSystemApps = false;
2764
2765            // All the changes are done during package scanning.
2766            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2767
2768            // can downgrade to reader
2769            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2770            mSettings.writeLPr();
2771            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2772
2773            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2774                    SystemClock.uptimeMillis());
2775
2776            if (!mOnlyCore) {
2777                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2778                mRequiredInstallerPackage = getRequiredInstallerLPr();
2779                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2780                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2781                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2782                        mIntentFilterVerifierComponent);
2783                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2784                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2785                        SharedLibraryInfo.VERSION_UNDEFINED);
2786                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2787                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2788                        SharedLibraryInfo.VERSION_UNDEFINED);
2789            } else {
2790                mRequiredVerifierPackage = null;
2791                mRequiredInstallerPackage = null;
2792                mRequiredUninstallerPackage = null;
2793                mIntentFilterVerifierComponent = null;
2794                mIntentFilterVerifier = null;
2795                mServicesSystemSharedLibraryPackageName = null;
2796                mSharedSystemSharedLibraryPackageName = null;
2797            }
2798
2799            mInstallerService = new PackageInstallerService(context, this);
2800            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2801            if (ephemeralResolverComponent != null) {
2802                if (DEBUG_EPHEMERAL) {
2803                    Slog.d(TAG, "Set ephemeral resolver: " + ephemeralResolverComponent);
2804                }
2805                mInstantAppResolverConnection =
2806                        new EphemeralResolverConnection(mContext, ephemeralResolverComponent);
2807            } else {
2808                mInstantAppResolverConnection = null;
2809            }
2810            updateInstantAppInstallerLocked();
2811            mInstantAppResolverSettingsComponent = getEphemeralResolverSettingsLPr();
2812
2813            // Read and update the usage of dex files.
2814            // Do this at the end of PM init so that all the packages have their
2815            // data directory reconciled.
2816            // At this point we know the code paths of the packages, so we can validate
2817            // the disk file and build the internal cache.
2818            // The usage file is expected to be small so loading and verifying it
2819            // should take a fairly small time compare to the other activities (e.g. package
2820            // scanning).
2821            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2822            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2823            for (int userId : currentUserIds) {
2824                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2825            }
2826            mDexManager.load(userPackages);
2827        } // synchronized (mPackages)
2828        } // synchronized (mInstallLock)
2829
2830        // Now after opening every single application zip, make sure they
2831        // are all flushed.  Not really needed, but keeps things nice and
2832        // tidy.
2833        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2834        Runtime.getRuntime().gc();
2835        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2836
2837        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2838        FallbackCategoryProvider.loadFallbacks();
2839        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2840
2841        // The initial scanning above does many calls into installd while
2842        // holding the mPackages lock, but we're mostly interested in yelling
2843        // once we have a booted system.
2844        mInstaller.setWarnIfHeld(mPackages);
2845
2846        // Expose private service for system components to use.
2847        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2848        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2849    }
2850
2851    private void updateInstantAppInstallerLocked() {
2852        final ComponentName oldInstantAppInstallerComponent = mInstantAppInstallerComponent;
2853        final ActivityInfo newInstantAppInstaller = getEphemeralInstallerLPr();
2854        ComponentName newInstantAppInstallerComponent = newInstantAppInstaller == null
2855                ? null : newInstantAppInstaller.getComponentName();
2856
2857        if (newInstantAppInstallerComponent != null
2858                && !newInstantAppInstallerComponent.equals(oldInstantAppInstallerComponent)) {
2859            if (DEBUG_EPHEMERAL) {
2860                Slog.d(TAG, "Set ephemeral installer: " + newInstantAppInstallerComponent);
2861            }
2862            setUpInstantAppInstallerActivityLP(newInstantAppInstaller);
2863        } else if (DEBUG_EPHEMERAL && newInstantAppInstallerComponent == null) {
2864            Slog.d(TAG, "Unset ephemeral installer; none available");
2865        }
2866        mInstantAppInstallerComponent = newInstantAppInstallerComponent;
2867    }
2868
2869    private static File preparePackageParserCache(boolean isUpgrade) {
2870        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2871            return null;
2872        }
2873
2874        // Disable package parsing on eng builds to allow for faster incremental development.
2875        if ("eng".equals(Build.TYPE)) {
2876            return null;
2877        }
2878
2879        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2880            Slog.i(TAG, "Disabling package parser cache due to system property.");
2881            return null;
2882        }
2883
2884        // The base directory for the package parser cache lives under /data/system/.
2885        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2886                "package_cache");
2887        if (cacheBaseDir == null) {
2888            return null;
2889        }
2890
2891        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2892        // This also serves to "GC" unused entries when the package cache version changes (which
2893        // can only happen during upgrades).
2894        if (isUpgrade) {
2895            FileUtils.deleteContents(cacheBaseDir);
2896        }
2897
2898
2899        // Return the versioned package cache directory. This is something like
2900        // "/data/system/package_cache/1"
2901        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2902
2903        // The following is a workaround to aid development on non-numbered userdebug
2904        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2905        // the system partition is newer.
2906        //
2907        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2908        // that starts with "eng." to signify that this is an engineering build and not
2909        // destined for release.
2910        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2911            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2912
2913            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2914            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2915            // in general and should not be used for production changes. In this specific case,
2916            // we know that they will work.
2917            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2918            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
2919                FileUtils.deleteContents(cacheBaseDir);
2920                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2921            }
2922        }
2923
2924        return cacheDir;
2925    }
2926
2927    @Override
2928    public boolean isFirstBoot() {
2929        return mFirstBoot;
2930    }
2931
2932    @Override
2933    public boolean isOnlyCoreApps() {
2934        return mOnlyCore;
2935    }
2936
2937    @Override
2938    public boolean isUpgrade() {
2939        return mIsUpgrade;
2940    }
2941
2942    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2943        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2944
2945        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2946                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2947                UserHandle.USER_SYSTEM);
2948        if (matches.size() == 1) {
2949            return matches.get(0).getComponentInfo().packageName;
2950        } else if (matches.size() == 0) {
2951            Log.e(TAG, "There should probably be a verifier, but, none were found");
2952            return null;
2953        }
2954        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2955    }
2956
2957    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
2958        synchronized (mPackages) {
2959            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
2960            if (libraryEntry == null) {
2961                throw new IllegalStateException("Missing required shared library:" + name);
2962            }
2963            return libraryEntry.apk;
2964        }
2965    }
2966
2967    private @NonNull String getRequiredInstallerLPr() {
2968        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2969        intent.addCategory(Intent.CATEGORY_DEFAULT);
2970        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2971
2972        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2973                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2974                UserHandle.USER_SYSTEM);
2975        if (matches.size() == 1) {
2976            ResolveInfo resolveInfo = matches.get(0);
2977            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2978                throw new RuntimeException("The installer must be a privileged app");
2979            }
2980            return matches.get(0).getComponentInfo().packageName;
2981        } else {
2982            throw new RuntimeException("There must be exactly one installer; found " + matches);
2983        }
2984    }
2985
2986    private @NonNull String getRequiredUninstallerLPr() {
2987        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2988        intent.addCategory(Intent.CATEGORY_DEFAULT);
2989        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2990
2991        final ResolveInfo resolveInfo = resolveIntent(intent, null,
2992                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2993                UserHandle.USER_SYSTEM);
2994        if (resolveInfo == null ||
2995                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
2996            throw new RuntimeException("There must be exactly one uninstaller; found "
2997                    + resolveInfo);
2998        }
2999        return resolveInfo.getComponentInfo().packageName;
3000    }
3001
3002    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3003        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3004
3005        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3006                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3007                UserHandle.USER_SYSTEM);
3008        ResolveInfo best = null;
3009        final int N = matches.size();
3010        for (int i = 0; i < N; i++) {
3011            final ResolveInfo cur = matches.get(i);
3012            final String packageName = cur.getComponentInfo().packageName;
3013            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3014                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3015                continue;
3016            }
3017
3018            if (best == null || cur.priority > best.priority) {
3019                best = cur;
3020            }
3021        }
3022
3023        if (best != null) {
3024            return best.getComponentInfo().getComponentName();
3025        } else {
3026            throw new RuntimeException("There must be at least one intent filter verifier");
3027        }
3028    }
3029
3030    private @Nullable ComponentName getEphemeralResolverLPr() {
3031        final String[] packageArray =
3032                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3033        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3034            if (DEBUG_EPHEMERAL) {
3035                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3036            }
3037            return null;
3038        }
3039
3040        final int resolveFlags =
3041                MATCH_DIRECT_BOOT_AWARE
3042                | MATCH_DIRECT_BOOT_UNAWARE
3043                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3044        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
3045        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3046                resolveFlags, UserHandle.USER_SYSTEM);
3047
3048        final int N = resolvers.size();
3049        if (N == 0) {
3050            if (DEBUG_EPHEMERAL) {
3051                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3052            }
3053            return null;
3054        }
3055
3056        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3057        for (int i = 0; i < N; i++) {
3058            final ResolveInfo info = resolvers.get(i);
3059
3060            if (info.serviceInfo == null) {
3061                continue;
3062            }
3063
3064            final String packageName = info.serviceInfo.packageName;
3065            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3066                if (DEBUG_EPHEMERAL) {
3067                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3068                            + " pkg: " + packageName + ", info:" + info);
3069                }
3070                continue;
3071            }
3072
3073            if (DEBUG_EPHEMERAL) {
3074                Slog.v(TAG, "Ephemeral resolver found;"
3075                        + " pkg: " + packageName + ", info:" + info);
3076            }
3077            return new ComponentName(packageName, info.serviceInfo.name);
3078        }
3079        if (DEBUG_EPHEMERAL) {
3080            Slog.v(TAG, "Ephemeral resolver NOT found");
3081        }
3082        return null;
3083    }
3084
3085    private @Nullable ActivityInfo getEphemeralInstallerLPr() {
3086        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3087        intent.addCategory(Intent.CATEGORY_DEFAULT);
3088        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3089
3090        final int resolveFlags =
3091                MATCH_DIRECT_BOOT_AWARE
3092                | MATCH_DIRECT_BOOT_UNAWARE
3093                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3094        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3095                resolveFlags, UserHandle.USER_SYSTEM);
3096        Iterator<ResolveInfo> iter = matches.iterator();
3097        while (iter.hasNext()) {
3098            final ResolveInfo rInfo = iter.next();
3099            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3100            if (ps != null) {
3101                final PermissionsState permissionsState = ps.getPermissionsState();
3102                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3103                    continue;
3104                }
3105            }
3106            iter.remove();
3107        }
3108        if (matches.size() == 0) {
3109            return null;
3110        } else if (matches.size() == 1) {
3111            return (ActivityInfo) matches.get(0).getComponentInfo();
3112        } else {
3113            throw new RuntimeException(
3114                    "There must be at most one ephemeral installer; found " + matches);
3115        }
3116    }
3117
3118    private @Nullable ComponentName getEphemeralResolverSettingsLPr() {
3119        final Intent intent = new Intent(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3120        intent.addCategory(Intent.CATEGORY_DEFAULT);
3121        final int resolveFlags =
3122                MATCH_DIRECT_BOOT_AWARE
3123                | MATCH_DIRECT_BOOT_UNAWARE
3124                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3125        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
3126                resolveFlags, UserHandle.USER_SYSTEM);
3127        Iterator<ResolveInfo> iter = matches.iterator();
3128        while (iter.hasNext()) {
3129            final ResolveInfo rInfo = iter.next();
3130            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3131            if (ps != null) {
3132                final PermissionsState permissionsState = ps.getPermissionsState();
3133                if (permissionsState.hasPermission(Manifest.permission.ACCESS_INSTANT_APPS, 0)) {
3134                    continue;
3135                }
3136            }
3137            iter.remove();
3138        }
3139        if (matches.size() == 0) {
3140            return null;
3141        } else if (matches.size() == 1) {
3142            return matches.get(0).getComponentInfo().getComponentName();
3143        } else {
3144            throw new RuntimeException(
3145                    "There must be at most one ephemeral resolver settings; found " + matches);
3146        }
3147    }
3148
3149    private void primeDomainVerificationsLPw(int userId) {
3150        if (DEBUG_DOMAIN_VERIFICATION) {
3151            Slog.d(TAG, "Priming domain verifications in user " + userId);
3152        }
3153
3154        SystemConfig systemConfig = SystemConfig.getInstance();
3155        ArraySet<String> packages = systemConfig.getLinkedApps();
3156
3157        for (String packageName : packages) {
3158            PackageParser.Package pkg = mPackages.get(packageName);
3159            if (pkg != null) {
3160                if (!pkg.isSystemApp()) {
3161                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3162                    continue;
3163                }
3164
3165                ArraySet<String> domains = null;
3166                for (PackageParser.Activity a : pkg.activities) {
3167                    for (ActivityIntentInfo filter : a.intents) {
3168                        if (hasValidDomains(filter)) {
3169                            if (domains == null) {
3170                                domains = new ArraySet<String>();
3171                            }
3172                            domains.addAll(filter.getHostsList());
3173                        }
3174                    }
3175                }
3176
3177                if (domains != null && domains.size() > 0) {
3178                    if (DEBUG_DOMAIN_VERIFICATION) {
3179                        Slog.v(TAG, "      + " + packageName);
3180                    }
3181                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3182                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3183                    // and then 'always' in the per-user state actually used for intent resolution.
3184                    final IntentFilterVerificationInfo ivi;
3185                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3186                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3187                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3188                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3189                } else {
3190                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3191                            + "' does not handle web links");
3192                }
3193            } else {
3194                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3195            }
3196        }
3197
3198        scheduleWritePackageRestrictionsLocked(userId);
3199        scheduleWriteSettingsLocked();
3200    }
3201
3202    private void applyFactoryDefaultBrowserLPw(int userId) {
3203        // The default browser app's package name is stored in a string resource,
3204        // with a product-specific overlay used for vendor customization.
3205        String browserPkg = mContext.getResources().getString(
3206                com.android.internal.R.string.default_browser);
3207        if (!TextUtils.isEmpty(browserPkg)) {
3208            // non-empty string => required to be a known package
3209            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3210            if (ps == null) {
3211                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3212                browserPkg = null;
3213            } else {
3214                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3215            }
3216        }
3217
3218        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3219        // default.  If there's more than one, just leave everything alone.
3220        if (browserPkg == null) {
3221            calculateDefaultBrowserLPw(userId);
3222        }
3223    }
3224
3225    private void calculateDefaultBrowserLPw(int userId) {
3226        List<String> allBrowsers = resolveAllBrowserApps(userId);
3227        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3228        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3229    }
3230
3231    private List<String> resolveAllBrowserApps(int userId) {
3232        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3233        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3234                PackageManager.MATCH_ALL, userId);
3235
3236        final int count = list.size();
3237        List<String> result = new ArrayList<String>(count);
3238        for (int i=0; i<count; i++) {
3239            ResolveInfo info = list.get(i);
3240            if (info.activityInfo == null
3241                    || !info.handleAllWebDataURI
3242                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3243                    || result.contains(info.activityInfo.packageName)) {
3244                continue;
3245            }
3246            result.add(info.activityInfo.packageName);
3247        }
3248
3249        return result;
3250    }
3251
3252    private boolean packageIsBrowser(String packageName, int userId) {
3253        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3254                PackageManager.MATCH_ALL, userId);
3255        final int N = list.size();
3256        for (int i = 0; i < N; i++) {
3257            ResolveInfo info = list.get(i);
3258            if (packageName.equals(info.activityInfo.packageName)) {
3259                return true;
3260            }
3261        }
3262        return false;
3263    }
3264
3265    private void checkDefaultBrowser() {
3266        final int myUserId = UserHandle.myUserId();
3267        final String packageName = getDefaultBrowserPackageName(myUserId);
3268        if (packageName != null) {
3269            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3270            if (info == null) {
3271                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3272                synchronized (mPackages) {
3273                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3274                }
3275            }
3276        }
3277    }
3278
3279    @Override
3280    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3281            throws RemoteException {
3282        try {
3283            return super.onTransact(code, data, reply, flags);
3284        } catch (RuntimeException e) {
3285            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3286                Slog.wtf(TAG, "Package Manager Crash", e);
3287            }
3288            throw e;
3289        }
3290    }
3291
3292    static int[] appendInts(int[] cur, int[] add) {
3293        if (add == null) return cur;
3294        if (cur == null) return add;
3295        final int N = add.length;
3296        for (int i=0; i<N; i++) {
3297            cur = appendInt(cur, add[i]);
3298        }
3299        return cur;
3300    }
3301
3302    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3303        if (!sUserManager.exists(userId)) return null;
3304        if (ps == null) {
3305            return null;
3306        }
3307        final PackageParser.Package p = ps.pkg;
3308        if (p == null) {
3309            return null;
3310        }
3311        // Filter out ephemeral app metadata:
3312        //   * The system/shell/root can see metadata for any app
3313        //   * An installed app can see metadata for 1) other installed apps
3314        //     and 2) ephemeral apps that have explicitly interacted with it
3315        //   * Ephemeral apps can only see their own data and exposed installed apps
3316        //   * Holding a signature permission allows seeing instant apps
3317        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3318        if (callingAppId != Process.SYSTEM_UID
3319                && callingAppId != Process.SHELL_UID
3320                && callingAppId != Process.ROOT_UID
3321                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3322                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3323            final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid());
3324            if (instantAppPackageName != null) {
3325                // ephemeral apps can only get information on themselves or
3326                // installed apps that are exposed.
3327                if (!instantAppPackageName.equals(p.packageName)
3328                        && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) {
3329                    return null;
3330                }
3331            } else {
3332                if (ps.getInstantApp(userId)) {
3333                    // only get access to the ephemeral app if we've been granted access
3334                    if (!mInstantAppRegistry.isInstantAccessGranted(
3335                            userId, callingAppId, ps.appId)) {
3336                        return null;
3337                    }
3338                }
3339            }
3340        }
3341
3342        final PermissionsState permissionsState = ps.getPermissionsState();
3343
3344        // Compute GIDs only if requested
3345        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3346                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3347        // Compute granted permissions only if package has requested permissions
3348        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3349                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3350        final PackageUserState state = ps.readUserState(userId);
3351
3352        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3353                && ps.isSystem()) {
3354            flags |= MATCH_ANY_USER;
3355        }
3356
3357        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3358                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3359
3360        if (packageInfo == null) {
3361            return null;
3362        }
3363
3364        rebaseEnabledOverlays(packageInfo.applicationInfo, userId);
3365
3366        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3367                resolveExternalPackageNameLPr(p);
3368
3369        return packageInfo;
3370    }
3371
3372    @Override
3373    public void checkPackageStartable(String packageName, int userId) {
3374        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3375
3376        synchronized (mPackages) {
3377            final PackageSetting ps = mSettings.mPackages.get(packageName);
3378            if (ps == null) {
3379                throw new SecurityException("Package " + packageName + " was not found!");
3380            }
3381
3382            if (!ps.getInstalled(userId)) {
3383                throw new SecurityException(
3384                        "Package " + packageName + " was not installed for user " + userId + "!");
3385            }
3386
3387            if (mSafeMode && !ps.isSystem()) {
3388                throw new SecurityException("Package " + packageName + " not a system app!");
3389            }
3390
3391            if (mFrozenPackages.contains(packageName)) {
3392                throw new SecurityException("Package " + packageName + " is currently frozen!");
3393            }
3394
3395            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3396                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3397                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3398            }
3399        }
3400    }
3401
3402    @Override
3403    public boolean isPackageAvailable(String packageName, int userId) {
3404        if (!sUserManager.exists(userId)) return false;
3405        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3406                false /* requireFullPermission */, false /* checkShell */, "is package available");
3407        synchronized (mPackages) {
3408            PackageParser.Package p = mPackages.get(packageName);
3409            if (p != null) {
3410                final PackageSetting ps = (PackageSetting) p.mExtras;
3411                if (ps != null) {
3412                    final PackageUserState state = ps.readUserState(userId);
3413                    if (state != null) {
3414                        return PackageParser.isAvailable(state);
3415                    }
3416                }
3417            }
3418        }
3419        return false;
3420    }
3421
3422    @Override
3423    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3424        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3425                flags, userId);
3426    }
3427
3428    @Override
3429    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3430            int flags, int userId) {
3431        return getPackageInfoInternal(versionedPackage.getPackageName(),
3432                // TODO: We will change version code to long, so in the new API it is long
3433                (int) versionedPackage.getVersionCode(), flags, userId);
3434    }
3435
3436    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3437            int flags, int userId) {
3438        if (!sUserManager.exists(userId)) return null;
3439        flags = updateFlagsForPackage(flags, userId, packageName);
3440        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3441                false /* requireFullPermission */, false /* checkShell */, "get package info");
3442
3443        // reader
3444        synchronized (mPackages) {
3445            // Normalize package name to handle renamed packages and static libs
3446            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3447
3448            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3449            if (matchFactoryOnly) {
3450                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3451                if (ps != null) {
3452                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3453                        return null;
3454                    }
3455                    return generatePackageInfo(ps, flags, userId);
3456                }
3457            }
3458
3459            PackageParser.Package p = mPackages.get(packageName);
3460            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3461                return null;
3462            }
3463            if (DEBUG_PACKAGE_INFO)
3464                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3465            if (p != null) {
3466                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3467                        Binder.getCallingUid(), userId)) {
3468                    return null;
3469                }
3470                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3471            }
3472            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3473                final PackageSetting ps = mSettings.mPackages.get(packageName);
3474                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3475                    return null;
3476                }
3477                return generatePackageInfo(ps, flags, userId);
3478            }
3479        }
3480        return null;
3481    }
3482
3483
3484    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) {
3485        // System/shell/root get to see all static libs
3486        final int appId = UserHandle.getAppId(uid);
3487        if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3488                || appId == Process.ROOT_UID) {
3489            return false;
3490        }
3491
3492        // No package means no static lib as it is always on internal storage
3493        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3494            return false;
3495        }
3496
3497        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3498                ps.pkg.staticSharedLibVersion);
3499        if (libEntry == null) {
3500            return false;
3501        }
3502
3503        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3504        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3505        if (uidPackageNames == null) {
3506            return true;
3507        }
3508
3509        for (String uidPackageName : uidPackageNames) {
3510            if (ps.name.equals(uidPackageName)) {
3511                return false;
3512            }
3513            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3514            if (uidPs != null) {
3515                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3516                        libEntry.info.getName());
3517                if (index < 0) {
3518                    continue;
3519                }
3520                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3521                    return false;
3522                }
3523            }
3524        }
3525        return true;
3526    }
3527
3528    @Override
3529    public String[] currentToCanonicalPackageNames(String[] names) {
3530        String[] out = new String[names.length];
3531        // reader
3532        synchronized (mPackages) {
3533            for (int i=names.length-1; i>=0; i--) {
3534                PackageSetting ps = mSettings.mPackages.get(names[i]);
3535                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3536            }
3537        }
3538        return out;
3539    }
3540
3541    @Override
3542    public String[] canonicalToCurrentPackageNames(String[] names) {
3543        String[] out = new String[names.length];
3544        // reader
3545        synchronized (mPackages) {
3546            for (int i=names.length-1; i>=0; i--) {
3547                String cur = mSettings.getRenamedPackageLPr(names[i]);
3548                out[i] = cur != null ? cur : names[i];
3549            }
3550        }
3551        return out;
3552    }
3553
3554    @Override
3555    public int getPackageUid(String packageName, int flags, int userId) {
3556        if (!sUserManager.exists(userId)) return -1;
3557        flags = updateFlagsForPackage(flags, userId, packageName);
3558        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3559                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3560
3561        // reader
3562        synchronized (mPackages) {
3563            final PackageParser.Package p = mPackages.get(packageName);
3564            if (p != null && p.isMatch(flags)) {
3565                return UserHandle.getUid(userId, p.applicationInfo.uid);
3566            }
3567            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3568                final PackageSetting ps = mSettings.mPackages.get(packageName);
3569                if (ps != null && ps.isMatch(flags)) {
3570                    return UserHandle.getUid(userId, ps.appId);
3571                }
3572            }
3573        }
3574
3575        return -1;
3576    }
3577
3578    @Override
3579    public int[] getPackageGids(String packageName, int flags, int userId) {
3580        if (!sUserManager.exists(userId)) return null;
3581        flags = updateFlagsForPackage(flags, userId, packageName);
3582        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3583                false /* requireFullPermission */, false /* checkShell */,
3584                "getPackageGids");
3585
3586        // reader
3587        synchronized (mPackages) {
3588            final PackageParser.Package p = mPackages.get(packageName);
3589            if (p != null && p.isMatch(flags)) {
3590                PackageSetting ps = (PackageSetting) p.mExtras;
3591                // TODO: Shouldn't this be checking for package installed state for userId and
3592                // return null?
3593                return ps.getPermissionsState().computeGids(userId);
3594            }
3595            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3596                final PackageSetting ps = mSettings.mPackages.get(packageName);
3597                if (ps != null && ps.isMatch(flags)) {
3598                    return ps.getPermissionsState().computeGids(userId);
3599                }
3600            }
3601        }
3602
3603        return null;
3604    }
3605
3606    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3607        if (bp.perm != null) {
3608            return PackageParser.generatePermissionInfo(bp.perm, flags);
3609        }
3610        PermissionInfo pi = new PermissionInfo();
3611        pi.name = bp.name;
3612        pi.packageName = bp.sourcePackage;
3613        pi.nonLocalizedLabel = bp.name;
3614        pi.protectionLevel = bp.protectionLevel;
3615        return pi;
3616    }
3617
3618    @Override
3619    public PermissionInfo getPermissionInfo(String name, int flags) {
3620        // reader
3621        synchronized (mPackages) {
3622            final BasePermission p = mSettings.mPermissions.get(name);
3623            if (p != null) {
3624                return generatePermissionInfo(p, flags);
3625            }
3626            return null;
3627        }
3628    }
3629
3630    @Override
3631    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3632            int flags) {
3633        // reader
3634        synchronized (mPackages) {
3635            if (group != null && !mPermissionGroups.containsKey(group)) {
3636                // This is thrown as NameNotFoundException
3637                return null;
3638            }
3639
3640            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3641            for (BasePermission p : mSettings.mPermissions.values()) {
3642                if (group == null) {
3643                    if (p.perm == null || p.perm.info.group == null) {
3644                        out.add(generatePermissionInfo(p, flags));
3645                    }
3646                } else {
3647                    if (p.perm != null && group.equals(p.perm.info.group)) {
3648                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3649                    }
3650                }
3651            }
3652            return new ParceledListSlice<>(out);
3653        }
3654    }
3655
3656    @Override
3657    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3658        // reader
3659        synchronized (mPackages) {
3660            return PackageParser.generatePermissionGroupInfo(
3661                    mPermissionGroups.get(name), flags);
3662        }
3663    }
3664
3665    @Override
3666    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3667        // reader
3668        synchronized (mPackages) {
3669            final int N = mPermissionGroups.size();
3670            ArrayList<PermissionGroupInfo> out
3671                    = new ArrayList<PermissionGroupInfo>(N);
3672            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3673                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3674            }
3675            return new ParceledListSlice<>(out);
3676        }
3677    }
3678
3679    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3680            int uid, int userId) {
3681        if (!sUserManager.exists(userId)) return null;
3682        PackageSetting ps = mSettings.mPackages.get(packageName);
3683        if (ps != null) {
3684            if (filterSharedLibPackageLPr(ps, uid, userId)) {
3685                return null;
3686            }
3687            if (ps.pkg == null) {
3688                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3689                if (pInfo != null) {
3690                    return pInfo.applicationInfo;
3691                }
3692                return null;
3693            }
3694            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3695                    ps.readUserState(userId), userId);
3696            if (ai != null) {
3697                rebaseEnabledOverlays(ai, userId);
3698                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3699            }
3700            return ai;
3701        }
3702        return null;
3703    }
3704
3705    @Override
3706    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3707        if (!sUserManager.exists(userId)) return null;
3708        flags = updateFlagsForApplication(flags, userId, packageName);
3709        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3710                false /* requireFullPermission */, false /* checkShell */, "get application info");
3711
3712        // writer
3713        synchronized (mPackages) {
3714            // Normalize package name to handle renamed packages and static libs
3715            packageName = resolveInternalPackageNameLPr(packageName,
3716                    PackageManager.VERSION_CODE_HIGHEST);
3717
3718            PackageParser.Package p = mPackages.get(packageName);
3719            if (DEBUG_PACKAGE_INFO) Log.v(
3720                    TAG, "getApplicationInfo " + packageName
3721                    + ": " + p);
3722            if (p != null) {
3723                PackageSetting ps = mSettings.mPackages.get(packageName);
3724                if (ps == null) return null;
3725                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3726                    return null;
3727                }
3728                // Note: isEnabledLP() does not apply here - always return info
3729                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3730                        p, flags, ps.readUserState(userId), userId);
3731                if (ai != null) {
3732                    rebaseEnabledOverlays(ai, userId);
3733                    ai.packageName = resolveExternalPackageNameLPr(p);
3734                }
3735                return ai;
3736            }
3737            if ("android".equals(packageName)||"system".equals(packageName)) {
3738                return mAndroidApplication;
3739            }
3740            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3741                // Already generates the external package name
3742                return generateApplicationInfoFromSettingsLPw(packageName,
3743                        Binder.getCallingUid(), flags, userId);
3744            }
3745        }
3746        return null;
3747    }
3748
3749    private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) {
3750        List<String> paths = new ArrayList<>();
3751        ArrayMap<String, ArrayList<String>> userSpecificOverlays =
3752            mEnabledOverlayPaths.get(userId);
3753        if (userSpecificOverlays != null) {
3754            if (!"android".equals(ai.packageName)) {
3755                ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android");
3756                if (frameworkOverlays != null) {
3757                    paths.addAll(frameworkOverlays);
3758                }
3759            }
3760
3761            ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName);
3762            if (appOverlays != null) {
3763                paths.addAll(appOverlays);
3764            }
3765        }
3766        ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null;
3767    }
3768
3769    private String normalizePackageNameLPr(String packageName) {
3770        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3771        return normalizedPackageName != null ? normalizedPackageName : packageName;
3772    }
3773
3774    @Override
3775    public void deletePreloadsFileCache() {
3776        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
3777            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
3778        }
3779        File dir = Environment.getDataPreloadsFileCacheDirectory();
3780        Slog.i(TAG, "Deleting preloaded file cache " + dir);
3781        FileUtils.deleteContents(dir);
3782    }
3783
3784    @Override
3785    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3786            final IPackageDataObserver observer) {
3787        mContext.enforceCallingOrSelfPermission(
3788                android.Manifest.permission.CLEAR_APP_CACHE, null);
3789        mHandler.post(() -> {
3790            boolean success = false;
3791            try {
3792                freeStorage(volumeUuid, freeStorageSize, 0);
3793                success = true;
3794            } catch (IOException e) {
3795                Slog.w(TAG, e);
3796            }
3797            if (observer != null) {
3798                try {
3799                    observer.onRemoveCompleted(null, success);
3800                } catch (RemoteException e) {
3801                    Slog.w(TAG, e);
3802                }
3803            }
3804        });
3805    }
3806
3807    @Override
3808    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3809            final IntentSender pi) {
3810        mContext.enforceCallingOrSelfPermission(
3811                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
3812        mHandler.post(() -> {
3813            boolean success = false;
3814            try {
3815                freeStorage(volumeUuid, freeStorageSize, 0);
3816                success = true;
3817            } catch (IOException e) {
3818                Slog.w(TAG, e);
3819            }
3820            if (pi != null) {
3821                try {
3822                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
3823                } catch (SendIntentException e) {
3824                    Slog.w(TAG, e);
3825                }
3826            }
3827        });
3828    }
3829
3830    /**
3831     * Blocking call to clear various types of cached data across the system
3832     * until the requested bytes are available.
3833     */
3834    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
3835        final StorageManager storage = mContext.getSystemService(StorageManager.class);
3836        final File file = storage.findPathForUuid(volumeUuid);
3837        if (file.getUsableSpace() >= bytes) return;
3838
3839        if (ENABLE_FREE_CACHE_V2) {
3840            final boolean aggressive = (storageFlags
3841                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
3842            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
3843                    volumeUuid);
3844
3845            // 1. Pre-flight to determine if we have any chance to succeed
3846            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
3847            if (internalVolume && (aggressive || SystemProperties
3848                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
3849                deletePreloadsFileCache();
3850                if (file.getUsableSpace() >= bytes) return;
3851            }
3852
3853            // 3. Consider parsed APK data (aggressive only)
3854            if (internalVolume && aggressive) {
3855                FileUtils.deleteContents(mCacheDir);
3856                if (file.getUsableSpace() >= bytes) return;
3857            }
3858
3859            // 4. Consider cached app data (above quotas)
3860            try {
3861                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2);
3862            } catch (InstallerException ignored) {
3863            }
3864            if (file.getUsableSpace() >= bytes) return;
3865
3866            // 5. Consider shared libraries with refcount=0 and age>2h
3867            // 6. Consider dexopt output (aggressive only)
3868            // 7. Consider ephemeral apps not used in last week
3869
3870            // 8. Consider cached app data (below quotas)
3871            try {
3872                mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2
3873                        | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
3874            } catch (InstallerException ignored) {
3875            }
3876            if (file.getUsableSpace() >= bytes) return;
3877
3878            // 9. Consider DropBox entries
3879            // 10. Consider ephemeral cookies
3880
3881        } else {
3882            try {
3883                mInstaller.freeCache(volumeUuid, bytes, 0);
3884            } catch (InstallerException ignored) {
3885            }
3886            if (file.getUsableSpace() >= bytes) return;
3887        }
3888
3889        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
3890    }
3891
3892    /**
3893     * Update given flags based on encryption status of current user.
3894     */
3895    private int updateFlags(int flags, int userId) {
3896        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3897                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3898            // Caller expressed an explicit opinion about what encryption
3899            // aware/unaware components they want to see, so fall through and
3900            // give them what they want
3901        } else {
3902            // Caller expressed no opinion, so match based on user state
3903            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3904                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3905            } else {
3906                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3907            }
3908        }
3909        return flags;
3910    }
3911
3912    private UserManagerInternal getUserManagerInternal() {
3913        if (mUserManagerInternal == null) {
3914            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3915        }
3916        return mUserManagerInternal;
3917    }
3918
3919    private DeviceIdleController.LocalService getDeviceIdleController() {
3920        if (mDeviceIdleController == null) {
3921            mDeviceIdleController =
3922                    LocalServices.getService(DeviceIdleController.LocalService.class);
3923        }
3924        return mDeviceIdleController;
3925    }
3926
3927    /**
3928     * Update given flags when being used to request {@link PackageInfo}.
3929     */
3930    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3931        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3932        boolean triaged = true;
3933        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3934                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3935            // Caller is asking for component details, so they'd better be
3936            // asking for specific encryption matching behavior, or be triaged
3937            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3938                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3939                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3940                triaged = false;
3941            }
3942        }
3943        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3944                | PackageManager.MATCH_SYSTEM_ONLY
3945                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3946            triaged = false;
3947        }
3948        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3949            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3950                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3951                    + Debug.getCallers(5));
3952        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3953                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3954            // If the caller wants all packages and has a restricted profile associated with it,
3955            // then match all users. This is to make sure that launchers that need to access work
3956            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3957            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3958            flags |= PackageManager.MATCH_ANY_USER;
3959        }
3960        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3961            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3962                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3963        }
3964        return updateFlags(flags, userId);
3965    }
3966
3967    /**
3968     * Update given flags when being used to request {@link ApplicationInfo}.
3969     */
3970    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3971        return updateFlagsForPackage(flags, userId, cookie);
3972    }
3973
3974    /**
3975     * Update given flags when being used to request {@link ComponentInfo}.
3976     */
3977    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3978        if (cookie instanceof Intent) {
3979            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3980                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3981            }
3982        }
3983
3984        boolean triaged = true;
3985        // Caller is asking for component details, so they'd better be
3986        // asking for specific encryption matching behavior, or be triaged
3987        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3988                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3989                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3990            triaged = false;
3991        }
3992        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3993            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3994                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3995        }
3996
3997        return updateFlags(flags, userId);
3998    }
3999
4000    /**
4001     * Update given intent when being used to request {@link ResolveInfo}.
4002     */
4003    private Intent updateIntentForResolve(Intent intent) {
4004        if (intent.getSelector() != null) {
4005            intent = intent.getSelector();
4006        }
4007        if (DEBUG_PREFERRED) {
4008            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4009        }
4010        return intent;
4011    }
4012
4013    /**
4014     * Update given flags when being used to request {@link ResolveInfo}.
4015     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4016     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4017     * flag set. However, this flag is only honoured in three circumstances:
4018     * <ul>
4019     * <li>when called from a system process</li>
4020     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4021     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4022     * action and a {@code android.intent.category.BROWSABLE} category</li>
4023     * </ul>
4024     */
4025    int updateFlagsForResolve(int flags, int userId, Intent intent, boolean includeInstantApp) {
4026        // Safe mode means we shouldn't match any third-party components
4027        if (mSafeMode) {
4028            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4029        }
4030        final int callingUid = Binder.getCallingUid();
4031        if (getInstantAppPackageName(callingUid) != null) {
4032            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4033            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4034            flags |= PackageManager.MATCH_INSTANT;
4035        } else {
4036            // Otherwise, prevent leaking ephemeral components
4037            final boolean isSpecialProcess =
4038                    callingUid == Process.SYSTEM_UID
4039                    || callingUid == Process.SHELL_UID
4040                    || callingUid == 0;
4041            final boolean allowMatchInstant =
4042                    (includeInstantApp
4043                            && Intent.ACTION_VIEW.equals(intent.getAction())
4044                            && intent.hasCategory(Intent.CATEGORY_BROWSABLE)
4045                            && hasWebURI(intent))
4046                    || isSpecialProcess
4047                    || mContext.checkCallingOrSelfPermission(
4048                            android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED;
4049            flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4050            if (!allowMatchInstant) {
4051                flags &= ~PackageManager.MATCH_INSTANT;
4052            }
4053        }
4054        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4055    }
4056
4057    @Override
4058    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4059        if (!sUserManager.exists(userId)) return null;
4060        flags = updateFlagsForComponent(flags, userId, component);
4061        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4062                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4063        synchronized (mPackages) {
4064            PackageParser.Activity a = mActivities.mActivities.get(component);
4065
4066            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4067            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4068                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4069                if (ps == null) return null;
4070                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
4071                        userId);
4072            }
4073            if (mResolveComponentName.equals(component)) {
4074                return PackageParser.generateActivityInfo(mResolveActivity, flags,
4075                        new PackageUserState(), userId);
4076            }
4077        }
4078        return null;
4079    }
4080
4081    @Override
4082    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4083            String resolvedType) {
4084        synchronized (mPackages) {
4085            if (component.equals(mResolveComponentName)) {
4086                // The resolver supports EVERYTHING!
4087                return true;
4088            }
4089            PackageParser.Activity a = mActivities.mActivities.get(component);
4090            if (a == null) {
4091                return false;
4092            }
4093            for (int i=0; i<a.intents.size(); i++) {
4094                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4095                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4096                    return true;
4097                }
4098            }
4099            return false;
4100        }
4101    }
4102
4103    @Override
4104    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4105        if (!sUserManager.exists(userId)) return null;
4106        flags = updateFlagsForComponent(flags, userId, component);
4107        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4108                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4109        synchronized (mPackages) {
4110            PackageParser.Activity a = mReceivers.mActivities.get(component);
4111            if (DEBUG_PACKAGE_INFO) Log.v(
4112                TAG, "getReceiverInfo " + component + ": " + a);
4113            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4114                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4115                if (ps == null) return null;
4116                ActivityInfo ri = PackageParser.generateActivityInfo(a, flags,
4117                        ps.readUserState(userId), userId);
4118                if (ri != null) {
4119                    rebaseEnabledOverlays(ri.applicationInfo, userId);
4120                }
4121                return ri;
4122            }
4123        }
4124        return null;
4125    }
4126
4127    @Override
4128    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4129        if (!sUserManager.exists(userId)) return null;
4130        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4131
4132        flags = updateFlagsForPackage(flags, userId, null);
4133
4134        final boolean canSeeStaticLibraries =
4135                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4136                        == PERMISSION_GRANTED
4137                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4138                        == PERMISSION_GRANTED
4139                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4140                        == PERMISSION_GRANTED
4141                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4142                        == PERMISSION_GRANTED;
4143
4144        synchronized (mPackages) {
4145            List<SharedLibraryInfo> result = null;
4146
4147            final int libCount = mSharedLibraries.size();
4148            for (int i = 0; i < libCount; i++) {
4149                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4150                if (versionedLib == null) {
4151                    continue;
4152                }
4153
4154                final int versionCount = versionedLib.size();
4155                for (int j = 0; j < versionCount; j++) {
4156                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4157                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4158                        break;
4159                    }
4160                    final long identity = Binder.clearCallingIdentity();
4161                    try {
4162                        // TODO: We will change version code to long, so in the new API it is long
4163                        PackageInfo packageInfo = getPackageInfoVersioned(
4164                                libInfo.getDeclaringPackage(), flags, userId);
4165                        if (packageInfo == null) {
4166                            continue;
4167                        }
4168                    } finally {
4169                        Binder.restoreCallingIdentity(identity);
4170                    }
4171
4172                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4173                            libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(),
4174                            getPackagesUsingSharedLibraryLPr(libInfo, flags, userId));
4175
4176                    if (result == null) {
4177                        result = new ArrayList<>();
4178                    }
4179                    result.add(resLibInfo);
4180                }
4181            }
4182
4183            return result != null ? new ParceledListSlice<>(result) : null;
4184        }
4185    }
4186
4187    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4188            SharedLibraryInfo libInfo, int flags, int userId) {
4189        List<VersionedPackage> versionedPackages = null;
4190        final int packageCount = mSettings.mPackages.size();
4191        for (int i = 0; i < packageCount; i++) {
4192            PackageSetting ps = mSettings.mPackages.valueAt(i);
4193
4194            if (ps == null) {
4195                continue;
4196            }
4197
4198            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4199                continue;
4200            }
4201
4202            final String libName = libInfo.getName();
4203            if (libInfo.isStatic()) {
4204                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4205                if (libIdx < 0) {
4206                    continue;
4207                }
4208                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4209                    continue;
4210                }
4211                if (versionedPackages == null) {
4212                    versionedPackages = new ArrayList<>();
4213                }
4214                // If the dependent is a static shared lib, use the public package name
4215                String dependentPackageName = ps.name;
4216                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4217                    dependentPackageName = ps.pkg.manifestPackageName;
4218                }
4219                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4220            } else if (ps.pkg != null) {
4221                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4222                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4223                    if (versionedPackages == null) {
4224                        versionedPackages = new ArrayList<>();
4225                    }
4226                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4227                }
4228            }
4229        }
4230
4231        return versionedPackages;
4232    }
4233
4234    @Override
4235    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4236        if (!sUserManager.exists(userId)) return null;
4237        flags = updateFlagsForComponent(flags, userId, component);
4238        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4239                false /* requireFullPermission */, false /* checkShell */, "get service info");
4240        synchronized (mPackages) {
4241            PackageParser.Service s = mServices.mServices.get(component);
4242            if (DEBUG_PACKAGE_INFO) Log.v(
4243                TAG, "getServiceInfo " + component + ": " + s);
4244            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4245                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4246                if (ps == null) return null;
4247                ServiceInfo si = PackageParser.generateServiceInfo(s, flags,
4248                        ps.readUserState(userId), userId);
4249                if (si != null) {
4250                    rebaseEnabledOverlays(si.applicationInfo, userId);
4251                }
4252                return si;
4253            }
4254        }
4255        return null;
4256    }
4257
4258    @Override
4259    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4260        if (!sUserManager.exists(userId)) return null;
4261        flags = updateFlagsForComponent(flags, userId, component);
4262        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4263                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4264        synchronized (mPackages) {
4265            PackageParser.Provider p = mProviders.mProviders.get(component);
4266            if (DEBUG_PACKAGE_INFO) Log.v(
4267                TAG, "getProviderInfo " + component + ": " + p);
4268            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4269                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4270                if (ps == null) return null;
4271                ProviderInfo pi = PackageParser.generateProviderInfo(p, flags,
4272                        ps.readUserState(userId), userId);
4273                if (pi != null) {
4274                    rebaseEnabledOverlays(pi.applicationInfo, userId);
4275                }
4276                return pi;
4277            }
4278        }
4279        return null;
4280    }
4281
4282    @Override
4283    public String[] getSystemSharedLibraryNames() {
4284        synchronized (mPackages) {
4285            Set<String> libs = null;
4286            final int libCount = mSharedLibraries.size();
4287            for (int i = 0; i < libCount; i++) {
4288                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4289                if (versionedLib == null) {
4290                    continue;
4291                }
4292                final int versionCount = versionedLib.size();
4293                for (int j = 0; j < versionCount; j++) {
4294                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4295                    if (!libEntry.info.isStatic()) {
4296                        if (libs == null) {
4297                            libs = new ArraySet<>();
4298                        }
4299                        libs.add(libEntry.info.getName());
4300                        break;
4301                    }
4302                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4303                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4304                            UserHandle.getUserId(Binder.getCallingUid()))) {
4305                        if (libs == null) {
4306                            libs = new ArraySet<>();
4307                        }
4308                        libs.add(libEntry.info.getName());
4309                        break;
4310                    }
4311                }
4312            }
4313
4314            if (libs != null) {
4315                String[] libsArray = new String[libs.size()];
4316                libs.toArray(libsArray);
4317                return libsArray;
4318            }
4319
4320            return null;
4321        }
4322    }
4323
4324    @Override
4325    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4326        synchronized (mPackages) {
4327            return mServicesSystemSharedLibraryPackageName;
4328        }
4329    }
4330
4331    @Override
4332    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4333        synchronized (mPackages) {
4334            return mSharedSystemSharedLibraryPackageName;
4335        }
4336    }
4337
4338    private void updateSequenceNumberLP(String packageName, int[] userList) {
4339        for (int i = userList.length - 1; i >= 0; --i) {
4340            final int userId = userList[i];
4341            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4342            if (changedPackages == null) {
4343                changedPackages = new SparseArray<>();
4344                mChangedPackages.put(userId, changedPackages);
4345            }
4346            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4347            if (sequenceNumbers == null) {
4348                sequenceNumbers = new HashMap<>();
4349                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4350            }
4351            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4352            if (sequenceNumber != null) {
4353                changedPackages.remove(sequenceNumber);
4354            }
4355            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4356            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4357        }
4358        mChangedPackagesSequenceNumber++;
4359    }
4360
4361    @Override
4362    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4363        synchronized (mPackages) {
4364            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4365                return null;
4366            }
4367            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4368            if (changedPackages == null) {
4369                return null;
4370            }
4371            final List<String> packageNames =
4372                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4373            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4374                final String packageName = changedPackages.get(i);
4375                if (packageName != null) {
4376                    packageNames.add(packageName);
4377                }
4378            }
4379            return packageNames.isEmpty()
4380                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4381        }
4382    }
4383
4384    @Override
4385    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4386        ArrayList<FeatureInfo> res;
4387        synchronized (mAvailableFeatures) {
4388            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4389            res.addAll(mAvailableFeatures.values());
4390        }
4391        final FeatureInfo fi = new FeatureInfo();
4392        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4393                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4394        res.add(fi);
4395
4396        return new ParceledListSlice<>(res);
4397    }
4398
4399    @Override
4400    public boolean hasSystemFeature(String name, int version) {
4401        synchronized (mAvailableFeatures) {
4402            final FeatureInfo feat = mAvailableFeatures.get(name);
4403            if (feat == null) {
4404                return false;
4405            } else {
4406                return feat.version >= version;
4407            }
4408        }
4409    }
4410
4411    @Override
4412    public int checkPermission(String permName, String pkgName, int userId) {
4413        if (!sUserManager.exists(userId)) {
4414            return PackageManager.PERMISSION_DENIED;
4415        }
4416
4417        synchronized (mPackages) {
4418            final PackageParser.Package p = mPackages.get(pkgName);
4419            if (p != null && p.mExtras != null) {
4420                final PackageSetting ps = (PackageSetting) p.mExtras;
4421                final PermissionsState permissionsState = ps.getPermissionsState();
4422                if (permissionsState.hasPermission(permName, userId)) {
4423                    return PackageManager.PERMISSION_GRANTED;
4424                }
4425                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4426                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4427                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4428                    return PackageManager.PERMISSION_GRANTED;
4429                }
4430            }
4431        }
4432
4433        return PackageManager.PERMISSION_DENIED;
4434    }
4435
4436    @Override
4437    public int checkUidPermission(String permName, int uid) {
4438        final int userId = UserHandle.getUserId(uid);
4439
4440        if (!sUserManager.exists(userId)) {
4441            return PackageManager.PERMISSION_DENIED;
4442        }
4443
4444        synchronized (mPackages) {
4445            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4446            if (obj != null) {
4447                final SettingBase ps = (SettingBase) obj;
4448                final PermissionsState permissionsState = ps.getPermissionsState();
4449                if (permissionsState.hasPermission(permName, userId)) {
4450                    return PackageManager.PERMISSION_GRANTED;
4451                }
4452                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4453                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4454                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4455                    return PackageManager.PERMISSION_GRANTED;
4456                }
4457            } else {
4458                ArraySet<String> perms = mSystemPermissions.get(uid);
4459                if (perms != null) {
4460                    if (perms.contains(permName)) {
4461                        return PackageManager.PERMISSION_GRANTED;
4462                    }
4463                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4464                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4465                        return PackageManager.PERMISSION_GRANTED;
4466                    }
4467                }
4468            }
4469        }
4470
4471        return PackageManager.PERMISSION_DENIED;
4472    }
4473
4474    @Override
4475    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4476        if (UserHandle.getCallingUserId() != userId) {
4477            mContext.enforceCallingPermission(
4478                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4479                    "isPermissionRevokedByPolicy for user " + userId);
4480        }
4481
4482        if (checkPermission(permission, packageName, userId)
4483                == PackageManager.PERMISSION_GRANTED) {
4484            return false;
4485        }
4486
4487        final long identity = Binder.clearCallingIdentity();
4488        try {
4489            final int flags = getPermissionFlags(permission, packageName, userId);
4490            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4491        } finally {
4492            Binder.restoreCallingIdentity(identity);
4493        }
4494    }
4495
4496    @Override
4497    public String getPermissionControllerPackageName() {
4498        synchronized (mPackages) {
4499            return mRequiredInstallerPackage;
4500        }
4501    }
4502
4503    /**
4504     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4505     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4506     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4507     * @param message the message to log on security exception
4508     */
4509    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4510            boolean checkShell, String message) {
4511        if (userId < 0) {
4512            throw new IllegalArgumentException("Invalid userId " + userId);
4513        }
4514        if (checkShell) {
4515            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4516        }
4517        if (userId == UserHandle.getUserId(callingUid)) return;
4518        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4519            if (requireFullPermission) {
4520                mContext.enforceCallingOrSelfPermission(
4521                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4522            } else {
4523                try {
4524                    mContext.enforceCallingOrSelfPermission(
4525                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4526                } catch (SecurityException se) {
4527                    mContext.enforceCallingOrSelfPermission(
4528                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4529                }
4530            }
4531        }
4532    }
4533
4534    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4535        if (callingUid == Process.SHELL_UID) {
4536            if (userHandle >= 0
4537                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4538                throw new SecurityException("Shell does not have permission to access user "
4539                        + userHandle);
4540            } else if (userHandle < 0) {
4541                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4542                        + Debug.getCallers(3));
4543            }
4544        }
4545    }
4546
4547    private BasePermission findPermissionTreeLP(String permName) {
4548        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4549            if (permName.startsWith(bp.name) &&
4550                    permName.length() > bp.name.length() &&
4551                    permName.charAt(bp.name.length()) == '.') {
4552                return bp;
4553            }
4554        }
4555        return null;
4556    }
4557
4558    private BasePermission checkPermissionTreeLP(String permName) {
4559        if (permName != null) {
4560            BasePermission bp = findPermissionTreeLP(permName);
4561            if (bp != null) {
4562                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4563                    return bp;
4564                }
4565                throw new SecurityException("Calling uid "
4566                        + Binder.getCallingUid()
4567                        + " is not allowed to add to permission tree "
4568                        + bp.name + " owned by uid " + bp.uid);
4569            }
4570        }
4571        throw new SecurityException("No permission tree found for " + permName);
4572    }
4573
4574    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4575        if (s1 == null) {
4576            return s2 == null;
4577        }
4578        if (s2 == null) {
4579            return false;
4580        }
4581        if (s1.getClass() != s2.getClass()) {
4582            return false;
4583        }
4584        return s1.equals(s2);
4585    }
4586
4587    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4588        if (pi1.icon != pi2.icon) return false;
4589        if (pi1.logo != pi2.logo) return false;
4590        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4591        if (!compareStrings(pi1.name, pi2.name)) return false;
4592        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4593        // We'll take care of setting this one.
4594        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4595        // These are not currently stored in settings.
4596        //if (!compareStrings(pi1.group, pi2.group)) return false;
4597        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4598        //if (pi1.labelRes != pi2.labelRes) return false;
4599        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4600        return true;
4601    }
4602
4603    int permissionInfoFootprint(PermissionInfo info) {
4604        int size = info.name.length();
4605        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4606        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4607        return size;
4608    }
4609
4610    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4611        int size = 0;
4612        for (BasePermission perm : mSettings.mPermissions.values()) {
4613            if (perm.uid == tree.uid) {
4614                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4615            }
4616        }
4617        return size;
4618    }
4619
4620    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4621        // We calculate the max size of permissions defined by this uid and throw
4622        // if that plus the size of 'info' would exceed our stated maximum.
4623        if (tree.uid != Process.SYSTEM_UID) {
4624            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4625            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4626                throw new SecurityException("Permission tree size cap exceeded");
4627            }
4628        }
4629    }
4630
4631    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4632        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4633            throw new SecurityException("Label must be specified in permission");
4634        }
4635        BasePermission tree = checkPermissionTreeLP(info.name);
4636        BasePermission bp = mSettings.mPermissions.get(info.name);
4637        boolean added = bp == null;
4638        boolean changed = true;
4639        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4640        if (added) {
4641            enforcePermissionCapLocked(info, tree);
4642            bp = new BasePermission(info.name, tree.sourcePackage,
4643                    BasePermission.TYPE_DYNAMIC);
4644        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4645            throw new SecurityException(
4646                    "Not allowed to modify non-dynamic permission "
4647                    + info.name);
4648        } else {
4649            if (bp.protectionLevel == fixedLevel
4650                    && bp.perm.owner.equals(tree.perm.owner)
4651                    && bp.uid == tree.uid
4652                    && comparePermissionInfos(bp.perm.info, info)) {
4653                changed = false;
4654            }
4655        }
4656        bp.protectionLevel = fixedLevel;
4657        info = new PermissionInfo(info);
4658        info.protectionLevel = fixedLevel;
4659        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4660        bp.perm.info.packageName = tree.perm.info.packageName;
4661        bp.uid = tree.uid;
4662        if (added) {
4663            mSettings.mPermissions.put(info.name, bp);
4664        }
4665        if (changed) {
4666            if (!async) {
4667                mSettings.writeLPr();
4668            } else {
4669                scheduleWriteSettingsLocked();
4670            }
4671        }
4672        return added;
4673    }
4674
4675    @Override
4676    public boolean addPermission(PermissionInfo info) {
4677        synchronized (mPackages) {
4678            return addPermissionLocked(info, false);
4679        }
4680    }
4681
4682    @Override
4683    public boolean addPermissionAsync(PermissionInfo info) {
4684        synchronized (mPackages) {
4685            return addPermissionLocked(info, true);
4686        }
4687    }
4688
4689    @Override
4690    public void removePermission(String name) {
4691        synchronized (mPackages) {
4692            checkPermissionTreeLP(name);
4693            BasePermission bp = mSettings.mPermissions.get(name);
4694            if (bp != null) {
4695                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4696                    throw new SecurityException(
4697                            "Not allowed to modify non-dynamic permission "
4698                            + name);
4699                }
4700                mSettings.mPermissions.remove(name);
4701                mSettings.writeLPr();
4702            }
4703        }
4704    }
4705
4706    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4707            BasePermission bp) {
4708        int index = pkg.requestedPermissions.indexOf(bp.name);
4709        if (index == -1) {
4710            throw new SecurityException("Package " + pkg.packageName
4711                    + " has not requested permission " + bp.name);
4712        }
4713        if (!bp.isRuntime() && !bp.isDevelopment()) {
4714            throw new SecurityException("Permission " + bp.name
4715                    + " is not a changeable permission type");
4716        }
4717    }
4718
4719    @Override
4720    public void grantRuntimePermission(String packageName, String name, final int userId) {
4721        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4722    }
4723
4724    private void grantRuntimePermission(String packageName, String name, final int userId,
4725            boolean overridePolicy) {
4726        if (!sUserManager.exists(userId)) {
4727            Log.e(TAG, "No such user:" + userId);
4728            return;
4729        }
4730
4731        mContext.enforceCallingOrSelfPermission(
4732                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4733                "grantRuntimePermission");
4734
4735        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4736                true /* requireFullPermission */, true /* checkShell */,
4737                "grantRuntimePermission");
4738
4739        final int uid;
4740        final SettingBase sb;
4741
4742        synchronized (mPackages) {
4743            final PackageParser.Package pkg = mPackages.get(packageName);
4744            if (pkg == null) {
4745                throw new IllegalArgumentException("Unknown package: " + packageName);
4746            }
4747
4748            final BasePermission bp = mSettings.mPermissions.get(name);
4749            if (bp == null) {
4750                throw new IllegalArgumentException("Unknown permission: " + name);
4751            }
4752
4753            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4754
4755            // If a permission review is required for legacy apps we represent
4756            // their permissions as always granted runtime ones since we need
4757            // to keep the review required permission flag per user while an
4758            // install permission's state is shared across all users.
4759            if (mPermissionReviewRequired
4760                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4761                    && bp.isRuntime()) {
4762                return;
4763            }
4764
4765            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4766            sb = (SettingBase) pkg.mExtras;
4767            if (sb == null) {
4768                throw new IllegalArgumentException("Unknown package: " + packageName);
4769            }
4770
4771            final PermissionsState permissionsState = sb.getPermissionsState();
4772
4773            final int flags = permissionsState.getPermissionFlags(name, userId);
4774            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4775                throw new SecurityException("Cannot grant system fixed permission "
4776                        + name + " for package " + packageName);
4777            }
4778            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4779                throw new SecurityException("Cannot grant policy fixed permission "
4780                        + name + " for package " + packageName);
4781            }
4782
4783            if (bp.isDevelopment()) {
4784                // Development permissions must be handled specially, since they are not
4785                // normal runtime permissions.  For now they apply to all users.
4786                if (permissionsState.grantInstallPermission(bp) !=
4787                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4788                    scheduleWriteSettingsLocked();
4789                }
4790                return;
4791            }
4792
4793            final PackageSetting ps = mSettings.mPackages.get(packageName);
4794            if (ps.getInstantApp(userId) && !bp.isInstant()) {
4795                throw new SecurityException("Cannot grant non-ephemeral permission"
4796                        + name + " for package " + packageName);
4797            }
4798
4799            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4800                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4801                return;
4802            }
4803
4804            final int result = permissionsState.grantRuntimePermission(bp, userId);
4805            switch (result) {
4806                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4807                    return;
4808                }
4809
4810                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4811                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4812                    mHandler.post(new Runnable() {
4813                        @Override
4814                        public void run() {
4815                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4816                        }
4817                    });
4818                }
4819                break;
4820            }
4821
4822            if (bp.isRuntime()) {
4823                logPermissionGranted(mContext, name, packageName);
4824            }
4825
4826            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4827
4828            // Not critical if that is lost - app has to request again.
4829            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4830        }
4831
4832        // Only need to do this if user is initialized. Otherwise it's a new user
4833        // and there are no processes running as the user yet and there's no need
4834        // to make an expensive call to remount processes for the changed permissions.
4835        if (READ_EXTERNAL_STORAGE.equals(name)
4836                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4837            final long token = Binder.clearCallingIdentity();
4838            try {
4839                if (sUserManager.isInitialized(userId)) {
4840                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4841                            StorageManagerInternal.class);
4842                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4843                }
4844            } finally {
4845                Binder.restoreCallingIdentity(token);
4846            }
4847        }
4848    }
4849
4850    @Override
4851    public void revokeRuntimePermission(String packageName, String name, int userId) {
4852        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4853    }
4854
4855    private void revokeRuntimePermission(String packageName, String name, int userId,
4856            boolean overridePolicy) {
4857        if (!sUserManager.exists(userId)) {
4858            Log.e(TAG, "No such user:" + userId);
4859            return;
4860        }
4861
4862        mContext.enforceCallingOrSelfPermission(
4863                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4864                "revokeRuntimePermission");
4865
4866        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4867                true /* requireFullPermission */, true /* checkShell */,
4868                "revokeRuntimePermission");
4869
4870        final int appId;
4871
4872        synchronized (mPackages) {
4873            final PackageParser.Package pkg = mPackages.get(packageName);
4874            if (pkg == null) {
4875                throw new IllegalArgumentException("Unknown package: " + packageName);
4876            }
4877
4878            final BasePermission bp = mSettings.mPermissions.get(name);
4879            if (bp == null) {
4880                throw new IllegalArgumentException("Unknown permission: " + name);
4881            }
4882
4883            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4884
4885            // If a permission review is required for legacy apps we represent
4886            // their permissions as always granted runtime ones since we need
4887            // to keep the review required permission flag per user while an
4888            // install permission's state is shared across all users.
4889            if (mPermissionReviewRequired
4890                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4891                    && bp.isRuntime()) {
4892                return;
4893            }
4894
4895            SettingBase sb = (SettingBase) pkg.mExtras;
4896            if (sb == null) {
4897                throw new IllegalArgumentException("Unknown package: " + packageName);
4898            }
4899
4900            final PermissionsState permissionsState = sb.getPermissionsState();
4901
4902            final int flags = permissionsState.getPermissionFlags(name, userId);
4903            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4904                throw new SecurityException("Cannot revoke system fixed permission "
4905                        + name + " for package " + packageName);
4906            }
4907            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4908                throw new SecurityException("Cannot revoke policy fixed permission "
4909                        + name + " for package " + packageName);
4910            }
4911
4912            if (bp.isDevelopment()) {
4913                // Development permissions must be handled specially, since they are not
4914                // normal runtime permissions.  For now they apply to all users.
4915                if (permissionsState.revokeInstallPermission(bp) !=
4916                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4917                    scheduleWriteSettingsLocked();
4918                }
4919                return;
4920            }
4921
4922            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4923                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4924                return;
4925            }
4926
4927            if (bp.isRuntime()) {
4928                logPermissionRevoked(mContext, name, packageName);
4929            }
4930
4931            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4932
4933            // Critical, after this call app should never have the permission.
4934            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4935
4936            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4937        }
4938
4939        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4940    }
4941
4942    /**
4943     * Get the first event id for the permission.
4944     *
4945     * <p>There are four events for each permission: <ul>
4946     *     <li>Request permission: first id + 0</li>
4947     *     <li>Grant permission: first id + 1</li>
4948     *     <li>Request for permission denied: first id + 2</li>
4949     *     <li>Revoke permission: first id + 3</li>
4950     * </ul></p>
4951     *
4952     * @param name name of the permission
4953     *
4954     * @return The first event id for the permission
4955     */
4956    private static int getBaseEventId(@NonNull String name) {
4957        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
4958
4959        if (eventIdIndex == -1) {
4960            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
4961                    || "user".equals(Build.TYPE)) {
4962                Log.i(TAG, "Unknown permission " + name);
4963
4964                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
4965            } else {
4966                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
4967                //
4968                // Also update
4969                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
4970                // - metrics_constants.proto
4971                throw new IllegalStateException("Unknown permission " + name);
4972            }
4973        }
4974
4975        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
4976    }
4977
4978    /**
4979     * Log that a permission was revoked.
4980     *
4981     * @param context Context of the caller
4982     * @param name name of the permission
4983     * @param packageName package permission if for
4984     */
4985    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
4986            @NonNull String packageName) {
4987        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
4988    }
4989
4990    /**
4991     * Log that a permission request was granted.
4992     *
4993     * @param context Context of the caller
4994     * @param name name of the permission
4995     * @param packageName package permission if for
4996     */
4997    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
4998            @NonNull String packageName) {
4999        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5000    }
5001
5002    @Override
5003    public void resetRuntimePermissions() {
5004        mContext.enforceCallingOrSelfPermission(
5005                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5006                "revokeRuntimePermission");
5007
5008        int callingUid = Binder.getCallingUid();
5009        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5010            mContext.enforceCallingOrSelfPermission(
5011                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5012                    "resetRuntimePermissions");
5013        }
5014
5015        synchronized (mPackages) {
5016            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5017            for (int userId : UserManagerService.getInstance().getUserIds()) {
5018                final int packageCount = mPackages.size();
5019                for (int i = 0; i < packageCount; i++) {
5020                    PackageParser.Package pkg = mPackages.valueAt(i);
5021                    if (!(pkg.mExtras instanceof PackageSetting)) {
5022                        continue;
5023                    }
5024                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5025                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5026                }
5027            }
5028        }
5029    }
5030
5031    @Override
5032    public int getPermissionFlags(String name, String packageName, int userId) {
5033        if (!sUserManager.exists(userId)) {
5034            return 0;
5035        }
5036
5037        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5038
5039        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5040                true /* requireFullPermission */, false /* checkShell */,
5041                "getPermissionFlags");
5042
5043        synchronized (mPackages) {
5044            final PackageParser.Package pkg = mPackages.get(packageName);
5045            if (pkg == null) {
5046                return 0;
5047            }
5048
5049            final BasePermission bp = mSettings.mPermissions.get(name);
5050            if (bp == null) {
5051                return 0;
5052            }
5053
5054            SettingBase sb = (SettingBase) pkg.mExtras;
5055            if (sb == null) {
5056                return 0;
5057            }
5058
5059            PermissionsState permissionsState = sb.getPermissionsState();
5060            return permissionsState.getPermissionFlags(name, userId);
5061        }
5062    }
5063
5064    @Override
5065    public void updatePermissionFlags(String name, String packageName, int flagMask,
5066            int flagValues, int userId) {
5067        if (!sUserManager.exists(userId)) {
5068            return;
5069        }
5070
5071        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5072
5073        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5074                true /* requireFullPermission */, true /* checkShell */,
5075                "updatePermissionFlags");
5076
5077        // Only the system can change these flags and nothing else.
5078        if (getCallingUid() != Process.SYSTEM_UID) {
5079            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5080            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5081            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5082            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5083            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5084        }
5085
5086        synchronized (mPackages) {
5087            final PackageParser.Package pkg = mPackages.get(packageName);
5088            if (pkg == null) {
5089                throw new IllegalArgumentException("Unknown package: " + packageName);
5090            }
5091
5092            final BasePermission bp = mSettings.mPermissions.get(name);
5093            if (bp == null) {
5094                throw new IllegalArgumentException("Unknown permission: " + name);
5095            }
5096
5097            SettingBase sb = (SettingBase) pkg.mExtras;
5098            if (sb == null) {
5099                throw new IllegalArgumentException("Unknown package: " + packageName);
5100            }
5101
5102            PermissionsState permissionsState = sb.getPermissionsState();
5103
5104            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5105
5106            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5107                // Install and runtime permissions are stored in different places,
5108                // so figure out what permission changed and persist the change.
5109                if (permissionsState.getInstallPermissionState(name) != null) {
5110                    scheduleWriteSettingsLocked();
5111                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5112                        || hadState) {
5113                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5114                }
5115            }
5116        }
5117    }
5118
5119    /**
5120     * Update the permission flags for all packages and runtime permissions of a user in order
5121     * to allow device or profile owner to remove POLICY_FIXED.
5122     */
5123    @Override
5124    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5125        if (!sUserManager.exists(userId)) {
5126            return;
5127        }
5128
5129        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5130
5131        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5132                true /* requireFullPermission */, true /* checkShell */,
5133                "updatePermissionFlagsForAllApps");
5134
5135        // Only the system can change system fixed flags.
5136        if (getCallingUid() != Process.SYSTEM_UID) {
5137            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5138            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5139        }
5140
5141        synchronized (mPackages) {
5142            boolean changed = false;
5143            final int packageCount = mPackages.size();
5144            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5145                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5146                SettingBase sb = (SettingBase) pkg.mExtras;
5147                if (sb == null) {
5148                    continue;
5149                }
5150                PermissionsState permissionsState = sb.getPermissionsState();
5151                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5152                        userId, flagMask, flagValues);
5153            }
5154            if (changed) {
5155                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5156            }
5157        }
5158    }
5159
5160    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5161        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5162                != PackageManager.PERMISSION_GRANTED
5163            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5164                != PackageManager.PERMISSION_GRANTED) {
5165            throw new SecurityException(message + " requires "
5166                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5167                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5168        }
5169    }
5170
5171    @Override
5172    public boolean shouldShowRequestPermissionRationale(String permissionName,
5173            String packageName, int userId) {
5174        if (UserHandle.getCallingUserId() != userId) {
5175            mContext.enforceCallingPermission(
5176                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5177                    "canShowRequestPermissionRationale for user " + userId);
5178        }
5179
5180        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5181        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5182            return false;
5183        }
5184
5185        if (checkPermission(permissionName, packageName, userId)
5186                == PackageManager.PERMISSION_GRANTED) {
5187            return false;
5188        }
5189
5190        final int flags;
5191
5192        final long identity = Binder.clearCallingIdentity();
5193        try {
5194            flags = getPermissionFlags(permissionName,
5195                    packageName, userId);
5196        } finally {
5197            Binder.restoreCallingIdentity(identity);
5198        }
5199
5200        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5201                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5202                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5203
5204        if ((flags & fixedFlags) != 0) {
5205            return false;
5206        }
5207
5208        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5209    }
5210
5211    @Override
5212    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5213        mContext.enforceCallingOrSelfPermission(
5214                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5215                "addOnPermissionsChangeListener");
5216
5217        synchronized (mPackages) {
5218            mOnPermissionChangeListeners.addListenerLocked(listener);
5219        }
5220    }
5221
5222    @Override
5223    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5224        synchronized (mPackages) {
5225            mOnPermissionChangeListeners.removeListenerLocked(listener);
5226        }
5227    }
5228
5229    @Override
5230    public boolean isProtectedBroadcast(String actionName) {
5231        synchronized (mPackages) {
5232            if (mProtectedBroadcasts.contains(actionName)) {
5233                return true;
5234            } else if (actionName != null) {
5235                // TODO: remove these terrible hacks
5236                if (actionName.startsWith("android.net.netmon.lingerExpired")
5237                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5238                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5239                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5240                    return true;
5241                }
5242            }
5243        }
5244        return false;
5245    }
5246
5247    @Override
5248    public int checkSignatures(String pkg1, String pkg2) {
5249        synchronized (mPackages) {
5250            final PackageParser.Package p1 = mPackages.get(pkg1);
5251            final PackageParser.Package p2 = mPackages.get(pkg2);
5252            if (p1 == null || p1.mExtras == null
5253                    || p2 == null || p2.mExtras == null) {
5254                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5255            }
5256            return compareSignatures(p1.mSignatures, p2.mSignatures);
5257        }
5258    }
5259
5260    @Override
5261    public int checkUidSignatures(int uid1, int uid2) {
5262        // Map to base uids.
5263        uid1 = UserHandle.getAppId(uid1);
5264        uid2 = UserHandle.getAppId(uid2);
5265        // reader
5266        synchronized (mPackages) {
5267            Signature[] s1;
5268            Signature[] s2;
5269            Object obj = mSettings.getUserIdLPr(uid1);
5270            if (obj != null) {
5271                if (obj instanceof SharedUserSetting) {
5272                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5273                } else if (obj instanceof PackageSetting) {
5274                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5275                } else {
5276                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5277                }
5278            } else {
5279                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5280            }
5281            obj = mSettings.getUserIdLPr(uid2);
5282            if (obj != null) {
5283                if (obj instanceof SharedUserSetting) {
5284                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5285                } else if (obj instanceof PackageSetting) {
5286                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5287                } else {
5288                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5289                }
5290            } else {
5291                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5292            }
5293            return compareSignatures(s1, s2);
5294        }
5295    }
5296
5297    /**
5298     * This method should typically only be used when granting or revoking
5299     * permissions, since the app may immediately restart after this call.
5300     * <p>
5301     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5302     * guard your work against the app being relaunched.
5303     */
5304    private void killUid(int appId, int userId, String reason) {
5305        final long identity = Binder.clearCallingIdentity();
5306        try {
5307            IActivityManager am = ActivityManager.getService();
5308            if (am != null) {
5309                try {
5310                    am.killUid(appId, userId, reason);
5311                } catch (RemoteException e) {
5312                    /* ignore - same process */
5313                }
5314            }
5315        } finally {
5316            Binder.restoreCallingIdentity(identity);
5317        }
5318    }
5319
5320    /**
5321     * Compares two sets of signatures. Returns:
5322     * <br />
5323     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5324     * <br />
5325     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5326     * <br />
5327     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5328     * <br />
5329     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5330     * <br />
5331     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5332     */
5333    static int compareSignatures(Signature[] s1, Signature[] s2) {
5334        if (s1 == null) {
5335            return s2 == null
5336                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5337                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5338        }
5339
5340        if (s2 == null) {
5341            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5342        }
5343
5344        if (s1.length != s2.length) {
5345            return PackageManager.SIGNATURE_NO_MATCH;
5346        }
5347
5348        // Since both signature sets are of size 1, we can compare without HashSets.
5349        if (s1.length == 1) {
5350            return s1[0].equals(s2[0]) ?
5351                    PackageManager.SIGNATURE_MATCH :
5352                    PackageManager.SIGNATURE_NO_MATCH;
5353        }
5354
5355        ArraySet<Signature> set1 = new ArraySet<Signature>();
5356        for (Signature sig : s1) {
5357            set1.add(sig);
5358        }
5359        ArraySet<Signature> set2 = new ArraySet<Signature>();
5360        for (Signature sig : s2) {
5361            set2.add(sig);
5362        }
5363        // Make sure s2 contains all signatures in s1.
5364        if (set1.equals(set2)) {
5365            return PackageManager.SIGNATURE_MATCH;
5366        }
5367        return PackageManager.SIGNATURE_NO_MATCH;
5368    }
5369
5370    /**
5371     * If the database version for this type of package (internal storage or
5372     * external storage) is less than the version where package signatures
5373     * were updated, return true.
5374     */
5375    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5376        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5377        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5378    }
5379
5380    /**
5381     * Used for backward compatibility to make sure any packages with
5382     * certificate chains get upgraded to the new style. {@code existingSigs}
5383     * will be in the old format (since they were stored on disk from before the
5384     * system upgrade) and {@code scannedSigs} will be in the newer format.
5385     */
5386    private int compareSignaturesCompat(PackageSignatures existingSigs,
5387            PackageParser.Package scannedPkg) {
5388        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5389            return PackageManager.SIGNATURE_NO_MATCH;
5390        }
5391
5392        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5393        for (Signature sig : existingSigs.mSignatures) {
5394            existingSet.add(sig);
5395        }
5396        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5397        for (Signature sig : scannedPkg.mSignatures) {
5398            try {
5399                Signature[] chainSignatures = sig.getChainSignatures();
5400                for (Signature chainSig : chainSignatures) {
5401                    scannedCompatSet.add(chainSig);
5402                }
5403            } catch (CertificateEncodingException e) {
5404                scannedCompatSet.add(sig);
5405            }
5406        }
5407        /*
5408         * Make sure the expanded scanned set contains all signatures in the
5409         * existing one.
5410         */
5411        if (scannedCompatSet.equals(existingSet)) {
5412            // Migrate the old signatures to the new scheme.
5413            existingSigs.assignSignatures(scannedPkg.mSignatures);
5414            // The new KeySets will be re-added later in the scanning process.
5415            synchronized (mPackages) {
5416                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5417            }
5418            return PackageManager.SIGNATURE_MATCH;
5419        }
5420        return PackageManager.SIGNATURE_NO_MATCH;
5421    }
5422
5423    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5424        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5425        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5426    }
5427
5428    private int compareSignaturesRecover(PackageSignatures existingSigs,
5429            PackageParser.Package scannedPkg) {
5430        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5431            return PackageManager.SIGNATURE_NO_MATCH;
5432        }
5433
5434        String msg = null;
5435        try {
5436            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5437                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5438                        + scannedPkg.packageName);
5439                return PackageManager.SIGNATURE_MATCH;
5440            }
5441        } catch (CertificateException e) {
5442            msg = e.getMessage();
5443        }
5444
5445        logCriticalInfo(Log.INFO,
5446                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5447        return PackageManager.SIGNATURE_NO_MATCH;
5448    }
5449
5450    @Override
5451    public List<String> getAllPackages() {
5452        synchronized (mPackages) {
5453            return new ArrayList<String>(mPackages.keySet());
5454        }
5455    }
5456
5457    @Override
5458    public String[] getPackagesForUid(int uid) {
5459        final int userId = UserHandle.getUserId(uid);
5460        uid = UserHandle.getAppId(uid);
5461        // reader
5462        synchronized (mPackages) {
5463            Object obj = mSettings.getUserIdLPr(uid);
5464            if (obj instanceof SharedUserSetting) {
5465                final SharedUserSetting sus = (SharedUserSetting) obj;
5466                final int N = sus.packages.size();
5467                String[] res = new String[N];
5468                final Iterator<PackageSetting> it = sus.packages.iterator();
5469                int i = 0;
5470                while (it.hasNext()) {
5471                    PackageSetting ps = it.next();
5472                    if (ps.getInstalled(userId)) {
5473                        res[i++] = ps.name;
5474                    } else {
5475                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5476                    }
5477                }
5478                return res;
5479            } else if (obj instanceof PackageSetting) {
5480                final PackageSetting ps = (PackageSetting) obj;
5481                if (ps.getInstalled(userId)) {
5482                    return new String[]{ps.name};
5483                }
5484            }
5485        }
5486        return null;
5487    }
5488
5489    @Override
5490    public String getNameForUid(int uid) {
5491        // reader
5492        synchronized (mPackages) {
5493            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5494            if (obj instanceof SharedUserSetting) {
5495                final SharedUserSetting sus = (SharedUserSetting) obj;
5496                return sus.name + ":" + sus.userId;
5497            } else if (obj instanceof PackageSetting) {
5498                final PackageSetting ps = (PackageSetting) obj;
5499                return ps.name;
5500            }
5501        }
5502        return null;
5503    }
5504
5505    @Override
5506    public int getUidForSharedUser(String sharedUserName) {
5507        if(sharedUserName == null) {
5508            return -1;
5509        }
5510        // reader
5511        synchronized (mPackages) {
5512            SharedUserSetting suid;
5513            try {
5514                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5515                if (suid != null) {
5516                    return suid.userId;
5517                }
5518            } catch (PackageManagerException ignore) {
5519                // can't happen, but, still need to catch it
5520            }
5521            return -1;
5522        }
5523    }
5524
5525    @Override
5526    public int getFlagsForUid(int uid) {
5527        synchronized (mPackages) {
5528            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5529            if (obj instanceof SharedUserSetting) {
5530                final SharedUserSetting sus = (SharedUserSetting) obj;
5531                return sus.pkgFlags;
5532            } else if (obj instanceof PackageSetting) {
5533                final PackageSetting ps = (PackageSetting) obj;
5534                return ps.pkgFlags;
5535            }
5536        }
5537        return 0;
5538    }
5539
5540    @Override
5541    public int getPrivateFlagsForUid(int uid) {
5542        synchronized (mPackages) {
5543            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5544            if (obj instanceof SharedUserSetting) {
5545                final SharedUserSetting sus = (SharedUserSetting) obj;
5546                return sus.pkgPrivateFlags;
5547            } else if (obj instanceof PackageSetting) {
5548                final PackageSetting ps = (PackageSetting) obj;
5549                return ps.pkgPrivateFlags;
5550            }
5551        }
5552        return 0;
5553    }
5554
5555    @Override
5556    public boolean isUidPrivileged(int uid) {
5557        uid = UserHandle.getAppId(uid);
5558        // reader
5559        synchronized (mPackages) {
5560            Object obj = mSettings.getUserIdLPr(uid);
5561            if (obj instanceof SharedUserSetting) {
5562                final SharedUserSetting sus = (SharedUserSetting) obj;
5563                final Iterator<PackageSetting> it = sus.packages.iterator();
5564                while (it.hasNext()) {
5565                    if (it.next().isPrivileged()) {
5566                        return true;
5567                    }
5568                }
5569            } else if (obj instanceof PackageSetting) {
5570                final PackageSetting ps = (PackageSetting) obj;
5571                return ps.isPrivileged();
5572            }
5573        }
5574        return false;
5575    }
5576
5577    @Override
5578    public String[] getAppOpPermissionPackages(String permissionName) {
5579        synchronized (mPackages) {
5580            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5581            if (pkgs == null) {
5582                return null;
5583            }
5584            return pkgs.toArray(new String[pkgs.size()]);
5585        }
5586    }
5587
5588    @Override
5589    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5590            int flags, int userId) {
5591        return resolveIntentInternal(
5592                intent, resolvedType, flags, userId, false /*includeInstantApp*/);
5593    }
5594
5595    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5596            int flags, int userId, boolean includeInstantApp) {
5597        try {
5598            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5599
5600            if (!sUserManager.exists(userId)) return null;
5601            flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp);
5602            enforceCrossUserPermission(Binder.getCallingUid(), userId,
5603                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5604
5605            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5606            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5607                    flags, userId, includeInstantApp);
5608            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5609
5610            final ResolveInfo bestChoice =
5611                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5612            return bestChoice;
5613        } finally {
5614            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5615        }
5616    }
5617
5618    @Override
5619    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5620        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5621            throw new SecurityException(
5622                    "findPersistentPreferredActivity can only be run by the system");
5623        }
5624        if (!sUserManager.exists(userId)) {
5625            return null;
5626        }
5627        intent = updateIntentForResolve(intent);
5628        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5629        final int flags = updateFlagsForResolve(0, userId, intent, false);
5630        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5631                userId);
5632        synchronized (mPackages) {
5633            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5634                    userId);
5635        }
5636    }
5637
5638    @Override
5639    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5640            IntentFilter filter, int match, ComponentName activity) {
5641        final int userId = UserHandle.getCallingUserId();
5642        if (DEBUG_PREFERRED) {
5643            Log.v(TAG, "setLastChosenActivity intent=" + intent
5644                + " resolvedType=" + resolvedType
5645                + " flags=" + flags
5646                + " filter=" + filter
5647                + " match=" + match
5648                + " activity=" + activity);
5649            filter.dump(new PrintStreamPrinter(System.out), "    ");
5650        }
5651        intent.setComponent(null);
5652        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5653                userId);
5654        // Find any earlier preferred or last chosen entries and nuke them
5655        findPreferredActivity(intent, resolvedType,
5656                flags, query, 0, false, true, false, userId);
5657        // Add the new activity as the last chosen for this filter
5658        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5659                "Setting last chosen");
5660    }
5661
5662    @Override
5663    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5664        final int userId = UserHandle.getCallingUserId();
5665        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5666        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5667                userId);
5668        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5669                false, false, false, userId);
5670    }
5671
5672    /**
5673     * Returns whether or not instant apps have been disabled remotely.
5674     * <p><em>IMPORTANT</em> This should not be called with the package manager lock
5675     * held. Otherwise we run the risk of deadlock.
5676     */
5677    private boolean isEphemeralDisabled() {
5678        // ephemeral apps have been disabled across the board
5679        if (DISABLE_EPHEMERAL_APPS) {
5680            return true;
5681        }
5682        // system isn't up yet; can't read settings, so, assume no ephemeral apps
5683        if (!mSystemReady) {
5684            return true;
5685        }
5686        // we can't get a content resolver until the system is ready; these checks must happen last
5687        final ContentResolver resolver = mContext.getContentResolver();
5688        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
5689            return true;
5690        }
5691        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
5692    }
5693
5694    private boolean isEphemeralAllowed(
5695            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5696            boolean skipPackageCheck) {
5697        final int callingUser = UserHandle.getCallingUserId();
5698        if (callingUser != UserHandle.USER_SYSTEM) {
5699            return false;
5700        }
5701        if (mInstantAppResolverConnection == null) {
5702            return false;
5703        }
5704        if (mInstantAppInstallerComponent == null) {
5705            return false;
5706        }
5707        if (intent.getComponent() != null) {
5708            return false;
5709        }
5710        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5711            return false;
5712        }
5713        if (!skipPackageCheck && intent.getPackage() != null) {
5714            return false;
5715        }
5716        final boolean isWebUri = hasWebURI(intent);
5717        if (!isWebUri || intent.getData().getHost() == null) {
5718            return false;
5719        }
5720        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5721        // Or if there's already an ephemeral app installed that handles the action
5722        synchronized (mPackages) {
5723            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5724            for (int n = 0; n < count; n++) {
5725                ResolveInfo info = resolvedActivities.get(n);
5726                String packageName = info.activityInfo.packageName;
5727                PackageSetting ps = mSettings.mPackages.get(packageName);
5728                if (ps != null) {
5729                    // Try to get the status from User settings first
5730                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5731                    int status = (int) (packedStatus >> 32);
5732                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5733                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5734                        if (DEBUG_EPHEMERAL) {
5735                            Slog.v(TAG, "DENY ephemeral apps;"
5736                                + " pkg: " + packageName + ", status: " + status);
5737                        }
5738                        return false;
5739                    }
5740                    if (ps.getInstantApp(userId)) {
5741                        if (DEBUG_EPHEMERAL) {
5742                            Slog.v(TAG, "DENY instant app installed;"
5743                                    + " pkg: " + packageName);
5744                        }
5745                        return false;
5746                    }
5747                }
5748            }
5749        }
5750        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5751        return true;
5752    }
5753
5754    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
5755            Intent origIntent, String resolvedType, String callingPackage,
5756            int userId) {
5757        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
5758                new InstantAppRequest(responseObj, origIntent, resolvedType,
5759                        callingPackage, userId));
5760        mHandler.sendMessage(msg);
5761    }
5762
5763    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5764            int flags, List<ResolveInfo> query, int userId) {
5765        if (query != null) {
5766            final int N = query.size();
5767            if (N == 1) {
5768                return query.get(0);
5769            } else if (N > 1) {
5770                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5771                // If there is more than one activity with the same priority,
5772                // then let the user decide between them.
5773                ResolveInfo r0 = query.get(0);
5774                ResolveInfo r1 = query.get(1);
5775                if (DEBUG_INTENT_MATCHING || debug) {
5776                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5777                            + r1.activityInfo.name + "=" + r1.priority);
5778                }
5779                // If the first activity has a higher priority, or a different
5780                // default, then it is always desirable to pick it.
5781                if (r0.priority != r1.priority
5782                        || r0.preferredOrder != r1.preferredOrder
5783                        || r0.isDefault != r1.isDefault) {
5784                    return query.get(0);
5785                }
5786                // If we have saved a preference for a preferred activity for
5787                // this Intent, use that.
5788                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5789                        flags, query, r0.priority, true, false, debug, userId);
5790                if (ri != null) {
5791                    return ri;
5792                }
5793                // If we have an ephemeral app, use it
5794                for (int i = 0; i < N; i++) {
5795                    ri = query.get(i);
5796                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
5797                        return ri;
5798                    }
5799                }
5800                ri = new ResolveInfo(mResolveInfo);
5801                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5802                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5803                // If all of the options come from the same package, show the application's
5804                // label and icon instead of the generic resolver's.
5805                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5806                // and then throw away the ResolveInfo itself, meaning that the caller loses
5807                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5808                // a fallback for this case; we only set the target package's resources on
5809                // the ResolveInfo, not the ActivityInfo.
5810                final String intentPackage = intent.getPackage();
5811                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5812                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5813                    ri.resolvePackageName = intentPackage;
5814                    if (userNeedsBadging(userId)) {
5815                        ri.noResourceId = true;
5816                    } else {
5817                        ri.icon = appi.icon;
5818                    }
5819                    ri.iconResourceId = appi.icon;
5820                    ri.labelRes = appi.labelRes;
5821                }
5822                ri.activityInfo.applicationInfo = new ApplicationInfo(
5823                        ri.activityInfo.applicationInfo);
5824                if (userId != 0) {
5825                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5826                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5827                }
5828                // Make sure that the resolver is displayable in car mode
5829                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5830                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5831                return ri;
5832            }
5833        }
5834        return null;
5835    }
5836
5837    /**
5838     * Return true if the given list is not empty and all of its contents have
5839     * an activityInfo with the given package name.
5840     */
5841    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5842        if (ArrayUtils.isEmpty(list)) {
5843            return false;
5844        }
5845        for (int i = 0, N = list.size(); i < N; i++) {
5846            final ResolveInfo ri = list.get(i);
5847            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5848            if (ai == null || !packageName.equals(ai.packageName)) {
5849                return false;
5850            }
5851        }
5852        return true;
5853    }
5854
5855    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5856            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5857        final int N = query.size();
5858        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5859                .get(userId);
5860        // Get the list of persistent preferred activities that handle the intent
5861        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5862        List<PersistentPreferredActivity> pprefs = ppir != null
5863                ? ppir.queryIntent(intent, resolvedType,
5864                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5865                        userId)
5866                : null;
5867        if (pprefs != null && pprefs.size() > 0) {
5868            final int M = pprefs.size();
5869            for (int i=0; i<M; i++) {
5870                final PersistentPreferredActivity ppa = pprefs.get(i);
5871                if (DEBUG_PREFERRED || debug) {
5872                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5873                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5874                            + "\n  component=" + ppa.mComponent);
5875                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5876                }
5877                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5878                        flags | MATCH_DISABLED_COMPONENTS, userId);
5879                if (DEBUG_PREFERRED || debug) {
5880                    Slog.v(TAG, "Found persistent preferred activity:");
5881                    if (ai != null) {
5882                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5883                    } else {
5884                        Slog.v(TAG, "  null");
5885                    }
5886                }
5887                if (ai == null) {
5888                    // This previously registered persistent preferred activity
5889                    // component is no longer known. Ignore it and do NOT remove it.
5890                    continue;
5891                }
5892                for (int j=0; j<N; j++) {
5893                    final ResolveInfo ri = query.get(j);
5894                    if (!ri.activityInfo.applicationInfo.packageName
5895                            .equals(ai.applicationInfo.packageName)) {
5896                        continue;
5897                    }
5898                    if (!ri.activityInfo.name.equals(ai.name)) {
5899                        continue;
5900                    }
5901                    //  Found a persistent preference that can handle the intent.
5902                    if (DEBUG_PREFERRED || debug) {
5903                        Slog.v(TAG, "Returning persistent preferred activity: " +
5904                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5905                    }
5906                    return ri;
5907                }
5908            }
5909        }
5910        return null;
5911    }
5912
5913    // TODO: handle preferred activities missing while user has amnesia
5914    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5915            List<ResolveInfo> query, int priority, boolean always,
5916            boolean removeMatches, boolean debug, int userId) {
5917        if (!sUserManager.exists(userId)) return null;
5918        flags = updateFlagsForResolve(flags, userId, intent, false);
5919        intent = updateIntentForResolve(intent);
5920        // writer
5921        synchronized (mPackages) {
5922            // Try to find a matching persistent preferred activity.
5923            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5924                    debug, userId);
5925
5926            // If a persistent preferred activity matched, use it.
5927            if (pri != null) {
5928                return pri;
5929            }
5930
5931            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5932            // Get the list of preferred activities that handle the intent
5933            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5934            List<PreferredActivity> prefs = pir != null
5935                    ? pir.queryIntent(intent, resolvedType,
5936                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5937                            userId)
5938                    : null;
5939            if (prefs != null && prefs.size() > 0) {
5940                boolean changed = false;
5941                try {
5942                    // First figure out how good the original match set is.
5943                    // We will only allow preferred activities that came
5944                    // from the same match quality.
5945                    int match = 0;
5946
5947                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5948
5949                    final int N = query.size();
5950                    for (int j=0; j<N; j++) {
5951                        final ResolveInfo ri = query.get(j);
5952                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5953                                + ": 0x" + Integer.toHexString(match));
5954                        if (ri.match > match) {
5955                            match = ri.match;
5956                        }
5957                    }
5958
5959                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5960                            + Integer.toHexString(match));
5961
5962                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5963                    final int M = prefs.size();
5964                    for (int i=0; i<M; i++) {
5965                        final PreferredActivity pa = prefs.get(i);
5966                        if (DEBUG_PREFERRED || debug) {
5967                            Slog.v(TAG, "Checking PreferredActivity ds="
5968                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5969                                    + "\n  component=" + pa.mPref.mComponent);
5970                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5971                        }
5972                        if (pa.mPref.mMatch != match) {
5973                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5974                                    + Integer.toHexString(pa.mPref.mMatch));
5975                            continue;
5976                        }
5977                        // If it's not an "always" type preferred activity and that's what we're
5978                        // looking for, skip it.
5979                        if (always && !pa.mPref.mAlways) {
5980                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5981                            continue;
5982                        }
5983                        final ActivityInfo ai = getActivityInfo(
5984                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5985                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5986                                userId);
5987                        if (DEBUG_PREFERRED || debug) {
5988                            Slog.v(TAG, "Found preferred activity:");
5989                            if (ai != null) {
5990                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5991                            } else {
5992                                Slog.v(TAG, "  null");
5993                            }
5994                        }
5995                        if (ai == null) {
5996                            // This previously registered preferred activity
5997                            // component is no longer known.  Most likely an update
5998                            // to the app was installed and in the new version this
5999                            // component no longer exists.  Clean it up by removing
6000                            // it from the preferred activities list, and skip it.
6001                            Slog.w(TAG, "Removing dangling preferred activity: "
6002                                    + pa.mPref.mComponent);
6003                            pir.removeFilter(pa);
6004                            changed = true;
6005                            continue;
6006                        }
6007                        for (int j=0; j<N; j++) {
6008                            final ResolveInfo ri = query.get(j);
6009                            if (!ri.activityInfo.applicationInfo.packageName
6010                                    .equals(ai.applicationInfo.packageName)) {
6011                                continue;
6012                            }
6013                            if (!ri.activityInfo.name.equals(ai.name)) {
6014                                continue;
6015                            }
6016
6017                            if (removeMatches) {
6018                                pir.removeFilter(pa);
6019                                changed = true;
6020                                if (DEBUG_PREFERRED) {
6021                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6022                                }
6023                                break;
6024                            }
6025
6026                            // Okay we found a previously set preferred or last chosen app.
6027                            // If the result set is different from when this
6028                            // was created, we need to clear it and re-ask the
6029                            // user their preference, if we're looking for an "always" type entry.
6030                            if (always && !pa.mPref.sameSet(query)) {
6031                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6032                                        + intent + " type " + resolvedType);
6033                                if (DEBUG_PREFERRED) {
6034                                    Slog.v(TAG, "Removing preferred activity since set changed "
6035                                            + pa.mPref.mComponent);
6036                                }
6037                                pir.removeFilter(pa);
6038                                // Re-add the filter as a "last chosen" entry (!always)
6039                                PreferredActivity lastChosen = new PreferredActivity(
6040                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6041                                pir.addFilter(lastChosen);
6042                                changed = true;
6043                                return null;
6044                            }
6045
6046                            // Yay! Either the set matched or we're looking for the last chosen
6047                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6048                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6049                            return ri;
6050                        }
6051                    }
6052                } finally {
6053                    if (changed) {
6054                        if (DEBUG_PREFERRED) {
6055                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6056                        }
6057                        scheduleWritePackageRestrictionsLocked(userId);
6058                    }
6059                }
6060            }
6061        }
6062        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6063        return null;
6064    }
6065
6066    /*
6067     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6068     */
6069    @Override
6070    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6071            int targetUserId) {
6072        mContext.enforceCallingOrSelfPermission(
6073                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6074        List<CrossProfileIntentFilter> matches =
6075                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6076        if (matches != null) {
6077            int size = matches.size();
6078            for (int i = 0; i < size; i++) {
6079                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6080            }
6081        }
6082        if (hasWebURI(intent)) {
6083            // cross-profile app linking works only towards the parent.
6084            final UserInfo parent = getProfileParent(sourceUserId);
6085            synchronized(mPackages) {
6086                int flags = updateFlagsForResolve(0, parent.id, intent, false);
6087                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6088                        intent, resolvedType, flags, sourceUserId, parent.id);
6089                return xpDomainInfo != null;
6090            }
6091        }
6092        return false;
6093    }
6094
6095    private UserInfo getProfileParent(int userId) {
6096        final long identity = Binder.clearCallingIdentity();
6097        try {
6098            return sUserManager.getProfileParent(userId);
6099        } finally {
6100            Binder.restoreCallingIdentity(identity);
6101        }
6102    }
6103
6104    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6105            String resolvedType, int userId) {
6106        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6107        if (resolver != null) {
6108            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6109        }
6110        return null;
6111    }
6112
6113    @Override
6114    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6115            String resolvedType, int flags, int userId) {
6116        try {
6117            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6118
6119            return new ParceledListSlice<>(
6120                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6121        } finally {
6122            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6123        }
6124    }
6125
6126    /**
6127     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6128     * instant, returns {@code null}.
6129     */
6130    private String getInstantAppPackageName(int callingUid) {
6131        // If the caller is an isolated app use the owner's uid for the lookup.
6132        if (Process.isIsolated(callingUid)) {
6133            callingUid = mIsolatedOwners.get(callingUid);
6134        }
6135        final int appId = UserHandle.getAppId(callingUid);
6136        synchronized (mPackages) {
6137            final Object obj = mSettings.getUserIdLPr(appId);
6138            if (obj instanceof PackageSetting) {
6139                final PackageSetting ps = (PackageSetting) obj;
6140                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6141                return isInstantApp ? ps.pkg.packageName : null;
6142            }
6143        }
6144        return null;
6145    }
6146
6147    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6148            String resolvedType, int flags, int userId) {
6149        return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false);
6150    }
6151
6152    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6153            String resolvedType, int flags, int userId, boolean includeInstantApp) {
6154        if (!sUserManager.exists(userId)) return Collections.emptyList();
6155        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
6156        flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp);
6157        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6158                false /* requireFullPermission */, false /* checkShell */,
6159                "query intent activities");
6160        ComponentName comp = intent.getComponent();
6161        if (comp == null) {
6162            if (intent.getSelector() != null) {
6163                intent = intent.getSelector();
6164                comp = intent.getComponent();
6165            }
6166        }
6167
6168        if (comp != null) {
6169            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6170            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6171            if (ai != null) {
6172                // When specifying an explicit component, we prevent the activity from being
6173                // used when either 1) the calling package is normal and the activity is within
6174                // an ephemeral application or 2) the calling package is ephemeral and the
6175                // activity is not visible to ephemeral applications.
6176                final boolean matchInstantApp =
6177                        (flags & PackageManager.MATCH_INSTANT) != 0;
6178                final boolean matchVisibleToInstantAppOnly =
6179                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6180                final boolean isCallerInstantApp =
6181                        instantAppPkgName != null;
6182                final boolean isTargetSameInstantApp =
6183                        comp.getPackageName().equals(instantAppPkgName);
6184                final boolean isTargetInstantApp =
6185                        (ai.applicationInfo.privateFlags
6186                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6187                final boolean isTargetHiddenFromInstantApp =
6188                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0;
6189                final boolean blockResolution =
6190                        !isTargetSameInstantApp
6191                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6192                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6193                                        && isTargetHiddenFromInstantApp));
6194                if (!blockResolution) {
6195                    final ResolveInfo ri = new ResolveInfo();
6196                    ri.activityInfo = ai;
6197                    list.add(ri);
6198                }
6199            }
6200            return applyPostResolutionFilter(list, instantAppPkgName);
6201        }
6202
6203        // reader
6204        boolean sortResult = false;
6205        boolean addEphemeral = false;
6206        List<ResolveInfo> result;
6207        final String pkgName = intent.getPackage();
6208        final boolean ephemeralDisabled = isEphemeralDisabled();
6209        synchronized (mPackages) {
6210            if (pkgName == null) {
6211                List<CrossProfileIntentFilter> matchingFilters =
6212                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6213                // Check for results that need to skip the current profile.
6214                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6215                        resolvedType, flags, userId);
6216                if (xpResolveInfo != null) {
6217                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6218                    xpResult.add(xpResolveInfo);
6219                    return applyPostResolutionFilter(
6220                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6221                }
6222
6223                // Check for results in the current profile.
6224                result = filterIfNotSystemUser(mActivities.queryIntent(
6225                        intent, resolvedType, flags, userId), userId);
6226                addEphemeral = !ephemeralDisabled
6227                        && isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
6228                // Check for cross profile results.
6229                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6230                xpResolveInfo = queryCrossProfileIntents(
6231                        matchingFilters, intent, resolvedType, flags, userId,
6232                        hasNonNegativePriorityResult);
6233                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6234                    boolean isVisibleToUser = filterIfNotSystemUser(
6235                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6236                    if (isVisibleToUser) {
6237                        result.add(xpResolveInfo);
6238                        sortResult = true;
6239                    }
6240                }
6241                if (hasWebURI(intent)) {
6242                    CrossProfileDomainInfo xpDomainInfo = null;
6243                    final UserInfo parent = getProfileParent(userId);
6244                    if (parent != null) {
6245                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6246                                flags, userId, parent.id);
6247                    }
6248                    if (xpDomainInfo != null) {
6249                        if (xpResolveInfo != null) {
6250                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6251                            // in the result.
6252                            result.remove(xpResolveInfo);
6253                        }
6254                        if (result.size() == 0 && !addEphemeral) {
6255                            // No result in current profile, but found candidate in parent user.
6256                            // And we are not going to add emphemeral app, so we can return the
6257                            // result straight away.
6258                            result.add(xpDomainInfo.resolveInfo);
6259                            return applyPostResolutionFilter(result, instantAppPkgName);
6260                        }
6261                    } else if (result.size() <= 1 && !addEphemeral) {
6262                        // No result in parent user and <= 1 result in current profile, and we
6263                        // are not going to add emphemeral app, so we can return the result without
6264                        // further processing.
6265                        return applyPostResolutionFilter(result, instantAppPkgName);
6266                    }
6267                    // We have more than one candidate (combining results from current and parent
6268                    // profile), so we need filtering and sorting.
6269                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6270                            intent, flags, result, xpDomainInfo, userId);
6271                    sortResult = true;
6272                }
6273            } else {
6274                final PackageParser.Package pkg = mPackages.get(pkgName);
6275                if (pkg != null) {
6276                    return applyPostResolutionFilter(filterIfNotSystemUser(
6277                            mActivities.queryIntentForPackage(
6278                                    intent, resolvedType, flags, pkg.activities, userId),
6279                            userId), instantAppPkgName);
6280                } else {
6281                    // the caller wants to resolve for a particular package; however, there
6282                    // were no installed results, so, try to find an ephemeral result
6283                    addEphemeral = !ephemeralDisabled
6284                            && isEphemeralAllowed(
6285                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6286                    result = new ArrayList<ResolveInfo>();
6287                }
6288            }
6289        }
6290        if (addEphemeral) {
6291            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6292            final InstantAppRequest requestObject = new InstantAppRequest(
6293                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
6294                    null /*callingPackage*/, userId);
6295            final AuxiliaryResolveInfo auxiliaryResponse =
6296                    InstantAppResolver.doInstantAppResolutionPhaseOne(
6297                            mContext, mInstantAppResolverConnection, requestObject);
6298            if (auxiliaryResponse != null) {
6299                if (DEBUG_EPHEMERAL) {
6300                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6301                }
6302                final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6303                ephemeralInstaller.activityInfo = new ActivityInfo(mInstantAppInstallerActivity);
6304                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
6305                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6306                // make sure this resolver is the default
6307                ephemeralInstaller.isDefault = true;
6308                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6309                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6310                // add a non-generic filter
6311                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6312                ephemeralInstaller.filter.addDataPath(
6313                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6314                ephemeralInstaller.instantAppAvailable = true;
6315                result.add(ephemeralInstaller);
6316            }
6317            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6318        }
6319        if (sortResult) {
6320            Collections.sort(result, mResolvePrioritySorter);
6321        }
6322        return applyPostResolutionFilter(result, instantAppPkgName);
6323    }
6324
6325    private static class CrossProfileDomainInfo {
6326        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6327        ResolveInfo resolveInfo;
6328        /* Best domain verification status of the activities found in the other profile */
6329        int bestDomainVerificationStatus;
6330    }
6331
6332    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6333            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6334        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6335                sourceUserId)) {
6336            return null;
6337        }
6338        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6339                resolvedType, flags, parentUserId);
6340
6341        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6342            return null;
6343        }
6344        CrossProfileDomainInfo result = null;
6345        int size = resultTargetUser.size();
6346        for (int i = 0; i < size; i++) {
6347            ResolveInfo riTargetUser = resultTargetUser.get(i);
6348            // Intent filter verification is only for filters that specify a host. So don't return
6349            // those that handle all web uris.
6350            if (riTargetUser.handleAllWebDataURI) {
6351                continue;
6352            }
6353            String packageName = riTargetUser.activityInfo.packageName;
6354            PackageSetting ps = mSettings.mPackages.get(packageName);
6355            if (ps == null) {
6356                continue;
6357            }
6358            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6359            int status = (int)(verificationState >> 32);
6360            if (result == null) {
6361                result = new CrossProfileDomainInfo();
6362                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6363                        sourceUserId, parentUserId);
6364                result.bestDomainVerificationStatus = status;
6365            } else {
6366                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6367                        result.bestDomainVerificationStatus);
6368            }
6369        }
6370        // Don't consider matches with status NEVER across profiles.
6371        if (result != null && result.bestDomainVerificationStatus
6372                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6373            return null;
6374        }
6375        return result;
6376    }
6377
6378    /**
6379     * Verification statuses are ordered from the worse to the best, except for
6380     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6381     */
6382    private int bestDomainVerificationStatus(int status1, int status2) {
6383        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6384            return status2;
6385        }
6386        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6387            return status1;
6388        }
6389        return (int) MathUtils.max(status1, status2);
6390    }
6391
6392    private boolean isUserEnabled(int userId) {
6393        long callingId = Binder.clearCallingIdentity();
6394        try {
6395            UserInfo userInfo = sUserManager.getUserInfo(userId);
6396            return userInfo != null && userInfo.isEnabled();
6397        } finally {
6398            Binder.restoreCallingIdentity(callingId);
6399        }
6400    }
6401
6402    /**
6403     * Filter out activities with systemUserOnly flag set, when current user is not System.
6404     *
6405     * @return filtered list
6406     */
6407    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6408        if (userId == UserHandle.USER_SYSTEM) {
6409            return resolveInfos;
6410        }
6411        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6412            ResolveInfo info = resolveInfos.get(i);
6413            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6414                resolveInfos.remove(i);
6415            }
6416        }
6417        return resolveInfos;
6418    }
6419
6420    /**
6421     * Filters out ephemeral activities.
6422     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6423     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6424     *
6425     * @param resolveInfos The pre-filtered list of resolved activities
6426     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6427     *          is performed.
6428     * @return A filtered list of resolved activities.
6429     */
6430    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6431            String ephemeralPkgName) {
6432        // TODO: When adding on-demand split support for non-instant apps, remove this check
6433        // and always apply post filtering
6434        if (ephemeralPkgName == null) {
6435            return resolveInfos;
6436        }
6437        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6438            final ResolveInfo info = resolveInfos.get(i);
6439            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6440            // allow activities that are defined in the provided package
6441            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6442                if (info.activityInfo.splitName != null
6443                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6444                                info.activityInfo.splitName)) {
6445                    // requested activity is defined in a split that hasn't been installed yet.
6446                    // add the installer to the resolve list
6447                    if (DEBUG_EPHEMERAL) {
6448                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6449                    }
6450                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
6451                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6452                            info.activityInfo.packageName, info.activityInfo.splitName,
6453                            info.activityInfo.applicationInfo.versionCode);
6454                    // make sure this resolver is the default
6455                    installerInfo.isDefault = true;
6456                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6457                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6458                    // add a non-generic filter
6459                    installerInfo.filter = new IntentFilter();
6460                    // load resources from the correct package
6461                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6462                    resolveInfos.set(i, installerInfo);
6463                }
6464                continue;
6465            }
6466            // allow activities that have been explicitly exposed to ephemeral apps
6467            if (!isEphemeralApp
6468                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
6469                continue;
6470            }
6471            resolveInfos.remove(i);
6472        }
6473        return resolveInfos;
6474    }
6475
6476    /**
6477     * @param resolveInfos list of resolve infos in descending priority order
6478     * @return if the list contains a resolve info with non-negative priority
6479     */
6480    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6481        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6482    }
6483
6484    private static boolean hasWebURI(Intent intent) {
6485        if (intent.getData() == null) {
6486            return false;
6487        }
6488        final String scheme = intent.getScheme();
6489        if (TextUtils.isEmpty(scheme)) {
6490            return false;
6491        }
6492        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6493    }
6494
6495    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6496            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6497            int userId) {
6498        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6499
6500        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6501            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6502                    candidates.size());
6503        }
6504
6505        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6506        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6507        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6508        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6509        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6510        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6511
6512        synchronized (mPackages) {
6513            final int count = candidates.size();
6514            // First, try to use linked apps. Partition the candidates into four lists:
6515            // one for the final results, one for the "do not use ever", one for "undefined status"
6516            // and finally one for "browser app type".
6517            for (int n=0; n<count; n++) {
6518                ResolveInfo info = candidates.get(n);
6519                String packageName = info.activityInfo.packageName;
6520                PackageSetting ps = mSettings.mPackages.get(packageName);
6521                if (ps != null) {
6522                    // Add to the special match all list (Browser use case)
6523                    if (info.handleAllWebDataURI) {
6524                        matchAllList.add(info);
6525                        continue;
6526                    }
6527                    // Try to get the status from User settings first
6528                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6529                    int status = (int)(packedStatus >> 32);
6530                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6531                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6532                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6533                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6534                                    + " : linkgen=" + linkGeneration);
6535                        }
6536                        // Use link-enabled generation as preferredOrder, i.e.
6537                        // prefer newly-enabled over earlier-enabled.
6538                        info.preferredOrder = linkGeneration;
6539                        alwaysList.add(info);
6540                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6541                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6542                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6543                        }
6544                        neverList.add(info);
6545                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6546                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6547                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6548                        }
6549                        alwaysAskList.add(info);
6550                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6551                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6552                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6553                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6554                        }
6555                        undefinedList.add(info);
6556                    }
6557                }
6558            }
6559
6560            // We'll want to include browser possibilities in a few cases
6561            boolean includeBrowser = false;
6562
6563            // First try to add the "always" resolution(s) for the current user, if any
6564            if (alwaysList.size() > 0) {
6565                result.addAll(alwaysList);
6566            } else {
6567                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6568                result.addAll(undefinedList);
6569                // Maybe add one for the other profile.
6570                if (xpDomainInfo != null && (
6571                        xpDomainInfo.bestDomainVerificationStatus
6572                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6573                    result.add(xpDomainInfo.resolveInfo);
6574                }
6575                includeBrowser = true;
6576            }
6577
6578            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6579            // If there were 'always' entries their preferred order has been set, so we also
6580            // back that off to make the alternatives equivalent
6581            if (alwaysAskList.size() > 0) {
6582                for (ResolveInfo i : result) {
6583                    i.preferredOrder = 0;
6584                }
6585                result.addAll(alwaysAskList);
6586                includeBrowser = true;
6587            }
6588
6589            if (includeBrowser) {
6590                // Also add browsers (all of them or only the default one)
6591                if (DEBUG_DOMAIN_VERIFICATION) {
6592                    Slog.v(TAG, "   ...including browsers in candidate set");
6593                }
6594                if ((matchFlags & MATCH_ALL) != 0) {
6595                    result.addAll(matchAllList);
6596                } else {
6597                    // Browser/generic handling case.  If there's a default browser, go straight
6598                    // to that (but only if there is no other higher-priority match).
6599                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6600                    int maxMatchPrio = 0;
6601                    ResolveInfo defaultBrowserMatch = null;
6602                    final int numCandidates = matchAllList.size();
6603                    for (int n = 0; n < numCandidates; n++) {
6604                        ResolveInfo info = matchAllList.get(n);
6605                        // track the highest overall match priority...
6606                        if (info.priority > maxMatchPrio) {
6607                            maxMatchPrio = info.priority;
6608                        }
6609                        // ...and the highest-priority default browser match
6610                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6611                            if (defaultBrowserMatch == null
6612                                    || (defaultBrowserMatch.priority < info.priority)) {
6613                                if (debug) {
6614                                    Slog.v(TAG, "Considering default browser match " + info);
6615                                }
6616                                defaultBrowserMatch = info;
6617                            }
6618                        }
6619                    }
6620                    if (defaultBrowserMatch != null
6621                            && defaultBrowserMatch.priority >= maxMatchPrio
6622                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6623                    {
6624                        if (debug) {
6625                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6626                        }
6627                        result.add(defaultBrowserMatch);
6628                    } else {
6629                        result.addAll(matchAllList);
6630                    }
6631                }
6632
6633                // If there is nothing selected, add all candidates and remove the ones that the user
6634                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6635                if (result.size() == 0) {
6636                    result.addAll(candidates);
6637                    result.removeAll(neverList);
6638                }
6639            }
6640        }
6641        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6642            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6643                    result.size());
6644            for (ResolveInfo info : result) {
6645                Slog.v(TAG, "  + " + info.activityInfo);
6646            }
6647        }
6648        return result;
6649    }
6650
6651    // Returns a packed value as a long:
6652    //
6653    // high 'int'-sized word: link status: undefined/ask/never/always.
6654    // low 'int'-sized word: relative priority among 'always' results.
6655    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6656        long result = ps.getDomainVerificationStatusForUser(userId);
6657        // if none available, get the master status
6658        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6659            if (ps.getIntentFilterVerificationInfo() != null) {
6660                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6661            }
6662        }
6663        return result;
6664    }
6665
6666    private ResolveInfo querySkipCurrentProfileIntents(
6667            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6668            int flags, int sourceUserId) {
6669        if (matchingFilters != null) {
6670            int size = matchingFilters.size();
6671            for (int i = 0; i < size; i ++) {
6672                CrossProfileIntentFilter filter = matchingFilters.get(i);
6673                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6674                    // Checking if there are activities in the target user that can handle the
6675                    // intent.
6676                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6677                            resolvedType, flags, sourceUserId);
6678                    if (resolveInfo != null) {
6679                        return resolveInfo;
6680                    }
6681                }
6682            }
6683        }
6684        return null;
6685    }
6686
6687    // Return matching ResolveInfo in target user if any.
6688    private ResolveInfo queryCrossProfileIntents(
6689            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6690            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6691        if (matchingFilters != null) {
6692            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6693            // match the same intent. For performance reasons, it is better not to
6694            // run queryIntent twice for the same userId
6695            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6696            int size = matchingFilters.size();
6697            for (int i = 0; i < size; i++) {
6698                CrossProfileIntentFilter filter = matchingFilters.get(i);
6699                int targetUserId = filter.getTargetUserId();
6700                boolean skipCurrentProfile =
6701                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6702                boolean skipCurrentProfileIfNoMatchFound =
6703                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6704                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6705                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6706                    // Checking if there are activities in the target user that can handle the
6707                    // intent.
6708                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6709                            resolvedType, flags, sourceUserId);
6710                    if (resolveInfo != null) return resolveInfo;
6711                    alreadyTriedUserIds.put(targetUserId, true);
6712                }
6713            }
6714        }
6715        return null;
6716    }
6717
6718    /**
6719     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6720     * will forward the intent to the filter's target user.
6721     * Otherwise, returns null.
6722     */
6723    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6724            String resolvedType, int flags, int sourceUserId) {
6725        int targetUserId = filter.getTargetUserId();
6726        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6727                resolvedType, flags, targetUserId);
6728        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6729            // If all the matches in the target profile are suspended, return null.
6730            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6731                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6732                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6733                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6734                            targetUserId);
6735                }
6736            }
6737        }
6738        return null;
6739    }
6740
6741    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6742            int sourceUserId, int targetUserId) {
6743        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6744        long ident = Binder.clearCallingIdentity();
6745        boolean targetIsProfile;
6746        try {
6747            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6748        } finally {
6749            Binder.restoreCallingIdentity(ident);
6750        }
6751        String className;
6752        if (targetIsProfile) {
6753            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6754        } else {
6755            className = FORWARD_INTENT_TO_PARENT;
6756        }
6757        ComponentName forwardingActivityComponentName = new ComponentName(
6758                mAndroidApplication.packageName, className);
6759        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6760                sourceUserId);
6761        if (!targetIsProfile) {
6762            forwardingActivityInfo.showUserIcon = targetUserId;
6763            forwardingResolveInfo.noResourceId = true;
6764        }
6765        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6766        forwardingResolveInfo.priority = 0;
6767        forwardingResolveInfo.preferredOrder = 0;
6768        forwardingResolveInfo.match = 0;
6769        forwardingResolveInfo.isDefault = true;
6770        forwardingResolveInfo.filter = filter;
6771        forwardingResolveInfo.targetUserId = targetUserId;
6772        return forwardingResolveInfo;
6773    }
6774
6775    @Override
6776    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6777            Intent[] specifics, String[] specificTypes, Intent intent,
6778            String resolvedType, int flags, int userId) {
6779        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6780                specificTypes, intent, resolvedType, flags, userId));
6781    }
6782
6783    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6784            Intent[] specifics, String[] specificTypes, Intent intent,
6785            String resolvedType, int flags, int userId) {
6786        if (!sUserManager.exists(userId)) return Collections.emptyList();
6787        flags = updateFlagsForResolve(flags, userId, intent, false);
6788        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6789                false /* requireFullPermission */, false /* checkShell */,
6790                "query intent activity options");
6791        final String resultsAction = intent.getAction();
6792
6793        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6794                | PackageManager.GET_RESOLVED_FILTER, userId);
6795
6796        if (DEBUG_INTENT_MATCHING) {
6797            Log.v(TAG, "Query " + intent + ": " + results);
6798        }
6799
6800        int specificsPos = 0;
6801        int N;
6802
6803        // todo: note that the algorithm used here is O(N^2).  This
6804        // isn't a problem in our current environment, but if we start running
6805        // into situations where we have more than 5 or 10 matches then this
6806        // should probably be changed to something smarter...
6807
6808        // First we go through and resolve each of the specific items
6809        // that were supplied, taking care of removing any corresponding
6810        // duplicate items in the generic resolve list.
6811        if (specifics != null) {
6812            for (int i=0; i<specifics.length; i++) {
6813                final Intent sintent = specifics[i];
6814                if (sintent == null) {
6815                    continue;
6816                }
6817
6818                if (DEBUG_INTENT_MATCHING) {
6819                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6820                }
6821
6822                String action = sintent.getAction();
6823                if (resultsAction != null && resultsAction.equals(action)) {
6824                    // If this action was explicitly requested, then don't
6825                    // remove things that have it.
6826                    action = null;
6827                }
6828
6829                ResolveInfo ri = null;
6830                ActivityInfo ai = null;
6831
6832                ComponentName comp = sintent.getComponent();
6833                if (comp == null) {
6834                    ri = resolveIntent(
6835                        sintent,
6836                        specificTypes != null ? specificTypes[i] : null,
6837                            flags, userId);
6838                    if (ri == null) {
6839                        continue;
6840                    }
6841                    if (ri == mResolveInfo) {
6842                        // ACK!  Must do something better with this.
6843                    }
6844                    ai = ri.activityInfo;
6845                    comp = new ComponentName(ai.applicationInfo.packageName,
6846                            ai.name);
6847                } else {
6848                    ai = getActivityInfo(comp, flags, userId);
6849                    if (ai == null) {
6850                        continue;
6851                    }
6852                }
6853
6854                // Look for any generic query activities that are duplicates
6855                // of this specific one, and remove them from the results.
6856                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6857                N = results.size();
6858                int j;
6859                for (j=specificsPos; j<N; j++) {
6860                    ResolveInfo sri = results.get(j);
6861                    if ((sri.activityInfo.name.equals(comp.getClassName())
6862                            && sri.activityInfo.applicationInfo.packageName.equals(
6863                                    comp.getPackageName()))
6864                        || (action != null && sri.filter.matchAction(action))) {
6865                        results.remove(j);
6866                        if (DEBUG_INTENT_MATCHING) Log.v(
6867                            TAG, "Removing duplicate item from " + j
6868                            + " due to specific " + specificsPos);
6869                        if (ri == null) {
6870                            ri = sri;
6871                        }
6872                        j--;
6873                        N--;
6874                    }
6875                }
6876
6877                // Add this specific item to its proper place.
6878                if (ri == null) {
6879                    ri = new ResolveInfo();
6880                    ri.activityInfo = ai;
6881                }
6882                results.add(specificsPos, ri);
6883                ri.specificIndex = i;
6884                specificsPos++;
6885            }
6886        }
6887
6888        // Now we go through the remaining generic results and remove any
6889        // duplicate actions that are found here.
6890        N = results.size();
6891        for (int i=specificsPos; i<N-1; i++) {
6892            final ResolveInfo rii = results.get(i);
6893            if (rii.filter == null) {
6894                continue;
6895            }
6896
6897            // Iterate over all of the actions of this result's intent
6898            // filter...  typically this should be just one.
6899            final Iterator<String> it = rii.filter.actionsIterator();
6900            if (it == null) {
6901                continue;
6902            }
6903            while (it.hasNext()) {
6904                final String action = it.next();
6905                if (resultsAction != null && resultsAction.equals(action)) {
6906                    // If this action was explicitly requested, then don't
6907                    // remove things that have it.
6908                    continue;
6909                }
6910                for (int j=i+1; j<N; j++) {
6911                    final ResolveInfo rij = results.get(j);
6912                    if (rij.filter != null && rij.filter.hasAction(action)) {
6913                        results.remove(j);
6914                        if (DEBUG_INTENT_MATCHING) Log.v(
6915                            TAG, "Removing duplicate item from " + j
6916                            + " due to action " + action + " at " + i);
6917                        j--;
6918                        N--;
6919                    }
6920                }
6921            }
6922
6923            // If the caller didn't request filter information, drop it now
6924            // so we don't have to marshall/unmarshall it.
6925            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6926                rii.filter = null;
6927            }
6928        }
6929
6930        // Filter out the caller activity if so requested.
6931        if (caller != null) {
6932            N = results.size();
6933            for (int i=0; i<N; i++) {
6934                ActivityInfo ainfo = results.get(i).activityInfo;
6935                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6936                        && caller.getClassName().equals(ainfo.name)) {
6937                    results.remove(i);
6938                    break;
6939                }
6940            }
6941        }
6942
6943        // If the caller didn't request filter information,
6944        // drop them now so we don't have to
6945        // marshall/unmarshall it.
6946        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6947            N = results.size();
6948            for (int i=0; i<N; i++) {
6949                results.get(i).filter = null;
6950            }
6951        }
6952
6953        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6954        return results;
6955    }
6956
6957    @Override
6958    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6959            String resolvedType, int flags, int userId) {
6960        return new ParceledListSlice<>(
6961                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6962    }
6963
6964    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6965            String resolvedType, int flags, int userId) {
6966        if (!sUserManager.exists(userId)) return Collections.emptyList();
6967        flags = updateFlagsForResolve(flags, userId, intent, false);
6968        ComponentName comp = intent.getComponent();
6969        if (comp == null) {
6970            if (intent.getSelector() != null) {
6971                intent = intent.getSelector();
6972                comp = intent.getComponent();
6973            }
6974        }
6975        if (comp != null) {
6976            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6977            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6978            if (ai != null) {
6979                ResolveInfo ri = new ResolveInfo();
6980                ri.activityInfo = ai;
6981                list.add(ri);
6982            }
6983            return list;
6984        }
6985
6986        // reader
6987        synchronized (mPackages) {
6988            String pkgName = intent.getPackage();
6989            if (pkgName == null) {
6990                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6991            }
6992            final PackageParser.Package pkg = mPackages.get(pkgName);
6993            if (pkg != null) {
6994                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6995                        userId);
6996            }
6997            return Collections.emptyList();
6998        }
6999    }
7000
7001    @Override
7002    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7003        if (!sUserManager.exists(userId)) return null;
7004        flags = updateFlagsForResolve(flags, userId, intent, false);
7005        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
7006        if (query != null) {
7007            if (query.size() >= 1) {
7008                // If there is more than one service with the same priority,
7009                // just arbitrarily pick the first one.
7010                return query.get(0);
7011            }
7012        }
7013        return null;
7014    }
7015
7016    @Override
7017    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7018            String resolvedType, int flags, int userId) {
7019        return new ParceledListSlice<>(
7020                queryIntentServicesInternal(intent, resolvedType, flags, userId));
7021    }
7022
7023    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7024            String resolvedType, int flags, int userId) {
7025        if (!sUserManager.exists(userId)) return Collections.emptyList();
7026        flags = updateFlagsForResolve(flags, userId, intent, false);
7027        ComponentName comp = intent.getComponent();
7028        if (comp == null) {
7029            if (intent.getSelector() != null) {
7030                intent = intent.getSelector();
7031                comp = intent.getComponent();
7032            }
7033        }
7034        if (comp != null) {
7035            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7036            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7037            if (si != null) {
7038                final ResolveInfo ri = new ResolveInfo();
7039                ri.serviceInfo = si;
7040                list.add(ri);
7041            }
7042            return list;
7043        }
7044
7045        // reader
7046        synchronized (mPackages) {
7047            String pkgName = intent.getPackage();
7048            if (pkgName == null) {
7049                return mServices.queryIntent(intent, resolvedType, flags, userId);
7050            }
7051            final PackageParser.Package pkg = mPackages.get(pkgName);
7052            if (pkg != null) {
7053                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7054                        userId);
7055            }
7056            return Collections.emptyList();
7057        }
7058    }
7059
7060    @Override
7061    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7062            String resolvedType, int flags, int userId) {
7063        return new ParceledListSlice<>(
7064                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7065    }
7066
7067    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7068            Intent intent, String resolvedType, int flags, int userId) {
7069        if (!sUserManager.exists(userId)) return Collections.emptyList();
7070        flags = updateFlagsForResolve(flags, userId, intent, false);
7071        ComponentName comp = intent.getComponent();
7072        if (comp == null) {
7073            if (intent.getSelector() != null) {
7074                intent = intent.getSelector();
7075                comp = intent.getComponent();
7076            }
7077        }
7078        if (comp != null) {
7079            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7080            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7081            if (pi != null) {
7082                final ResolveInfo ri = new ResolveInfo();
7083                ri.providerInfo = pi;
7084                list.add(ri);
7085            }
7086            return list;
7087        }
7088
7089        // reader
7090        synchronized (mPackages) {
7091            String pkgName = intent.getPackage();
7092            if (pkgName == null) {
7093                return mProviders.queryIntent(intent, resolvedType, flags, userId);
7094            }
7095            final PackageParser.Package pkg = mPackages.get(pkgName);
7096            if (pkg != null) {
7097                return mProviders.queryIntentForPackage(
7098                        intent, resolvedType, flags, pkg.providers, userId);
7099            }
7100            return Collections.emptyList();
7101        }
7102    }
7103
7104    @Override
7105    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7106        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7107        flags = updateFlagsForPackage(flags, userId, null);
7108        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7109        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7110                true /* requireFullPermission */, false /* checkShell */,
7111                "get installed packages");
7112
7113        // writer
7114        synchronized (mPackages) {
7115            ArrayList<PackageInfo> list;
7116            if (listUninstalled) {
7117                list = new ArrayList<>(mSettings.mPackages.size());
7118                for (PackageSetting ps : mSettings.mPackages.values()) {
7119                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7120                        continue;
7121                    }
7122                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7123                    if (pi != null) {
7124                        list.add(pi);
7125                    }
7126                }
7127            } else {
7128                list = new ArrayList<>(mPackages.size());
7129                for (PackageParser.Package p : mPackages.values()) {
7130                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
7131                            Binder.getCallingUid(), userId)) {
7132                        continue;
7133                    }
7134                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7135                            p.mExtras, flags, userId);
7136                    if (pi != null) {
7137                        list.add(pi);
7138                    }
7139                }
7140            }
7141
7142            return new ParceledListSlice<>(list);
7143        }
7144    }
7145
7146    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7147            String[] permissions, boolean[] tmp, int flags, int userId) {
7148        int numMatch = 0;
7149        final PermissionsState permissionsState = ps.getPermissionsState();
7150        for (int i=0; i<permissions.length; i++) {
7151            final String permission = permissions[i];
7152            if (permissionsState.hasPermission(permission, userId)) {
7153                tmp[i] = true;
7154                numMatch++;
7155            } else {
7156                tmp[i] = false;
7157            }
7158        }
7159        if (numMatch == 0) {
7160            return;
7161        }
7162        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7163
7164        // The above might return null in cases of uninstalled apps or install-state
7165        // skew across users/profiles.
7166        if (pi != null) {
7167            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7168                if (numMatch == permissions.length) {
7169                    pi.requestedPermissions = permissions;
7170                } else {
7171                    pi.requestedPermissions = new String[numMatch];
7172                    numMatch = 0;
7173                    for (int i=0; i<permissions.length; i++) {
7174                        if (tmp[i]) {
7175                            pi.requestedPermissions[numMatch] = permissions[i];
7176                            numMatch++;
7177                        }
7178                    }
7179                }
7180            }
7181            list.add(pi);
7182        }
7183    }
7184
7185    @Override
7186    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7187            String[] permissions, int flags, int userId) {
7188        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7189        flags = updateFlagsForPackage(flags, userId, permissions);
7190        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7191                true /* requireFullPermission */, false /* checkShell */,
7192                "get packages holding permissions");
7193        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7194
7195        // writer
7196        synchronized (mPackages) {
7197            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7198            boolean[] tmpBools = new boolean[permissions.length];
7199            if (listUninstalled) {
7200                for (PackageSetting ps : mSettings.mPackages.values()) {
7201                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7202                            userId);
7203                }
7204            } else {
7205                for (PackageParser.Package pkg : mPackages.values()) {
7206                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7207                    if (ps != null) {
7208                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7209                                userId);
7210                    }
7211                }
7212            }
7213
7214            return new ParceledListSlice<PackageInfo>(list);
7215        }
7216    }
7217
7218    @Override
7219    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7220        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7221        flags = updateFlagsForApplication(flags, userId, null);
7222        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7223
7224        // writer
7225        synchronized (mPackages) {
7226            ArrayList<ApplicationInfo> list;
7227            if (listUninstalled) {
7228                list = new ArrayList<>(mSettings.mPackages.size());
7229                for (PackageSetting ps : mSettings.mPackages.values()) {
7230                    ApplicationInfo ai;
7231                    int effectiveFlags = flags;
7232                    if (ps.isSystem()) {
7233                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7234                    }
7235                    if (ps.pkg != null) {
7236                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7237                            continue;
7238                        }
7239                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7240                                ps.readUserState(userId), userId);
7241                        if (ai != null) {
7242                            rebaseEnabledOverlays(ai, userId);
7243                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7244                        }
7245                    } else {
7246                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7247                        // and already converts to externally visible package name
7248                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7249                                Binder.getCallingUid(), effectiveFlags, userId);
7250                    }
7251                    if (ai != null) {
7252                        list.add(ai);
7253                    }
7254                }
7255            } else {
7256                list = new ArrayList<>(mPackages.size());
7257                for (PackageParser.Package p : mPackages.values()) {
7258                    if (p.mExtras != null) {
7259                        PackageSetting ps = (PackageSetting) p.mExtras;
7260                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7261                            continue;
7262                        }
7263                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7264                                ps.readUserState(userId), userId);
7265                        if (ai != null) {
7266                            rebaseEnabledOverlays(ai, userId);
7267                            ai.packageName = resolveExternalPackageNameLPr(p);
7268                            list.add(ai);
7269                        }
7270                    }
7271                }
7272            }
7273
7274            return new ParceledListSlice<>(list);
7275        }
7276    }
7277
7278    @Override
7279    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7280        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7281            return null;
7282        }
7283
7284        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7285                "getEphemeralApplications");
7286        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7287                true /* requireFullPermission */, false /* checkShell */,
7288                "getEphemeralApplications");
7289        synchronized (mPackages) {
7290            List<InstantAppInfo> instantApps = mInstantAppRegistry
7291                    .getInstantAppsLPr(userId);
7292            if (instantApps != null) {
7293                return new ParceledListSlice<>(instantApps);
7294            }
7295        }
7296        return null;
7297    }
7298
7299    @Override
7300    public boolean isInstantApp(String packageName, int userId) {
7301        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7302                true /* requireFullPermission */, false /* checkShell */,
7303                "isInstantApp");
7304        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7305            return false;
7306        }
7307        int uid = Binder.getCallingUid();
7308        if (Process.isIsolated(uid)) {
7309            uid = mIsolatedOwners.get(uid);
7310        }
7311
7312        synchronized (mPackages) {
7313            final PackageSetting ps = mSettings.mPackages.get(packageName);
7314            PackageParser.Package pkg = mPackages.get(packageName);
7315            final boolean returnAllowed =
7316                    ps != null
7317                    && (isCallerSameApp(packageName, uid)
7318                            || mContext.checkCallingOrSelfPermission(
7319                                    android.Manifest.permission.ACCESS_INSTANT_APPS)
7320                                            == PERMISSION_GRANTED
7321                            || mInstantAppRegistry.isInstantAccessGranted(
7322                                    userId, UserHandle.getAppId(uid), ps.appId));
7323            if (returnAllowed) {
7324                return ps.getInstantApp(userId);
7325            }
7326        }
7327        return false;
7328    }
7329
7330    @Override
7331    public byte[] getInstantAppCookie(String packageName, int userId) {
7332        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7333            return null;
7334        }
7335
7336        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7337                true /* requireFullPermission */, false /* checkShell */,
7338                "getInstantAppCookie");
7339        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7340            return null;
7341        }
7342        synchronized (mPackages) {
7343            return mInstantAppRegistry.getInstantAppCookieLPw(
7344                    packageName, userId);
7345        }
7346    }
7347
7348    @Override
7349    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7350        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7351            return true;
7352        }
7353
7354        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7355                true /* requireFullPermission */, true /* checkShell */,
7356                "setInstantAppCookie");
7357        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
7358            return false;
7359        }
7360        synchronized (mPackages) {
7361            return mInstantAppRegistry.setInstantAppCookieLPw(
7362                    packageName, cookie, userId);
7363        }
7364    }
7365
7366    @Override
7367    public Bitmap getInstantAppIcon(String packageName, int userId) {
7368        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7369            return null;
7370        }
7371
7372        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7373                "getInstantAppIcon");
7374
7375        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7376                true /* requireFullPermission */, false /* checkShell */,
7377                "getInstantAppIcon");
7378
7379        synchronized (mPackages) {
7380            return mInstantAppRegistry.getInstantAppIconLPw(
7381                    packageName, userId);
7382        }
7383    }
7384
7385    private boolean isCallerSameApp(String packageName, int uid) {
7386        PackageParser.Package pkg = mPackages.get(packageName);
7387        return pkg != null
7388                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
7389    }
7390
7391    @Override
7392    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7393        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7394    }
7395
7396    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7397        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7398
7399        // reader
7400        synchronized (mPackages) {
7401            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7402            final int userId = UserHandle.getCallingUserId();
7403            while (i.hasNext()) {
7404                final PackageParser.Package p = i.next();
7405                if (p.applicationInfo == null) continue;
7406
7407                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7408                        && !p.applicationInfo.isDirectBootAware();
7409                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7410                        && p.applicationInfo.isDirectBootAware();
7411
7412                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7413                        && (!mSafeMode || isSystemApp(p))
7414                        && (matchesUnaware || matchesAware)) {
7415                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7416                    if (ps != null) {
7417                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7418                                ps.readUserState(userId), userId);
7419                        if (ai != null) {
7420                            rebaseEnabledOverlays(ai, userId);
7421                            finalList.add(ai);
7422                        }
7423                    }
7424                }
7425            }
7426        }
7427
7428        return finalList;
7429    }
7430
7431    @Override
7432    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7433        if (!sUserManager.exists(userId)) return null;
7434        flags = updateFlagsForComponent(flags, userId, name);
7435        // reader
7436        synchronized (mPackages) {
7437            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7438            PackageSetting ps = provider != null
7439                    ? mSettings.mPackages.get(provider.owner.packageName)
7440                    : null;
7441            return ps != null
7442                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
7443                    ? PackageParser.generateProviderInfo(provider, flags,
7444                            ps.readUserState(userId), userId)
7445                    : null;
7446        }
7447    }
7448
7449    /**
7450     * @deprecated
7451     */
7452    @Deprecated
7453    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7454        // reader
7455        synchronized (mPackages) {
7456            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7457                    .entrySet().iterator();
7458            final int userId = UserHandle.getCallingUserId();
7459            while (i.hasNext()) {
7460                Map.Entry<String, PackageParser.Provider> entry = i.next();
7461                PackageParser.Provider p = entry.getValue();
7462                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7463
7464                if (ps != null && p.syncable
7465                        && (!mSafeMode || (p.info.applicationInfo.flags
7466                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7467                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7468                            ps.readUserState(userId), userId);
7469                    if (info != null) {
7470                        outNames.add(entry.getKey());
7471                        outInfo.add(info);
7472                    }
7473                }
7474            }
7475        }
7476    }
7477
7478    @Override
7479    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7480            int uid, int flags, String metaDataKey) {
7481        final int userId = processName != null ? UserHandle.getUserId(uid)
7482                : UserHandle.getCallingUserId();
7483        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7484        flags = updateFlagsForComponent(flags, userId, processName);
7485
7486        ArrayList<ProviderInfo> finalList = null;
7487        // reader
7488        synchronized (mPackages) {
7489            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7490            while (i.hasNext()) {
7491                final PackageParser.Provider p = i.next();
7492                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7493                if (ps != null && p.info.authority != null
7494                        && (processName == null
7495                                || (p.info.processName.equals(processName)
7496                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7497                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7498
7499                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
7500                    // parameter.
7501                    if (metaDataKey != null
7502                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
7503                        continue;
7504                    }
7505
7506                    if (finalList == null) {
7507                        finalList = new ArrayList<ProviderInfo>(3);
7508                    }
7509                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7510                            ps.readUserState(userId), userId);
7511                    if (info != null) {
7512                        finalList.add(info);
7513                    }
7514                }
7515            }
7516        }
7517
7518        if (finalList != null) {
7519            Collections.sort(finalList, mProviderInitOrderSorter);
7520            return new ParceledListSlice<ProviderInfo>(finalList);
7521        }
7522
7523        return ParceledListSlice.emptyList();
7524    }
7525
7526    @Override
7527    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7528        // reader
7529        synchronized (mPackages) {
7530            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7531            return PackageParser.generateInstrumentationInfo(i, flags);
7532        }
7533    }
7534
7535    @Override
7536    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7537            String targetPackage, int flags) {
7538        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7539    }
7540
7541    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7542            int flags) {
7543        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7544
7545        // reader
7546        synchronized (mPackages) {
7547            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7548            while (i.hasNext()) {
7549                final PackageParser.Instrumentation p = i.next();
7550                if (targetPackage == null
7551                        || targetPackage.equals(p.info.targetPackage)) {
7552                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7553                            flags);
7554                    if (ii != null) {
7555                        finalList.add(ii);
7556                    }
7557                }
7558            }
7559        }
7560
7561        return finalList;
7562    }
7563
7564    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7565        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7566        try {
7567            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7568        } finally {
7569            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7570        }
7571    }
7572
7573    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7574        final File[] files = dir.listFiles();
7575        if (ArrayUtils.isEmpty(files)) {
7576            Log.d(TAG, "No files in app dir " + dir);
7577            return;
7578        }
7579
7580        if (DEBUG_PACKAGE_SCANNING) {
7581            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7582                    + " flags=0x" + Integer.toHexString(parseFlags));
7583        }
7584        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7585                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, mPackageParserCallback);
7586
7587        // Submit files for parsing in parallel
7588        int fileCount = 0;
7589        for (File file : files) {
7590            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7591                    && !PackageInstallerService.isStageName(file.getName());
7592            if (!isPackage) {
7593                // Ignore entries which are not packages
7594                continue;
7595            }
7596            parallelPackageParser.submit(file, parseFlags);
7597            fileCount++;
7598        }
7599
7600        // Process results one by one
7601        for (; fileCount > 0; fileCount--) {
7602            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7603            Throwable throwable = parseResult.throwable;
7604            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7605
7606            if (throwable == null) {
7607                // Static shared libraries have synthetic package names
7608                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
7609                    renameStaticSharedLibraryPackage(parseResult.pkg);
7610                }
7611                try {
7612                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
7613                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7614                                currentTime, null);
7615                    }
7616                } catch (PackageManagerException e) {
7617                    errorCode = e.error;
7618                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7619                }
7620            } else if (throwable instanceof PackageParser.PackageParserException) {
7621                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7622                        throwable;
7623                errorCode = e.error;
7624                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7625            } else {
7626                throw new IllegalStateException("Unexpected exception occurred while parsing "
7627                        + parseResult.scanFile, throwable);
7628            }
7629
7630            // Delete invalid userdata apps
7631            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7632                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7633                logCriticalInfo(Log.WARN,
7634                        "Deleting invalid package at " + parseResult.scanFile);
7635                removeCodePathLI(parseResult.scanFile);
7636            }
7637        }
7638        parallelPackageParser.close();
7639    }
7640
7641    private static File getSettingsProblemFile() {
7642        File dataDir = Environment.getDataDirectory();
7643        File systemDir = new File(dataDir, "system");
7644        File fname = new File(systemDir, "uiderrors.txt");
7645        return fname;
7646    }
7647
7648    static void reportSettingsProblem(int priority, String msg) {
7649        logCriticalInfo(priority, msg);
7650    }
7651
7652    public static void logCriticalInfo(int priority, String msg) {
7653        Slog.println(priority, TAG, msg);
7654        EventLogTags.writePmCriticalInfo(msg);
7655        try {
7656            File fname = getSettingsProblemFile();
7657            FileOutputStream out = new FileOutputStream(fname, true);
7658            PrintWriter pw = new FastPrintWriter(out);
7659            SimpleDateFormat formatter = new SimpleDateFormat();
7660            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7661            pw.println(dateString + ": " + msg);
7662            pw.close();
7663            FileUtils.setPermissions(
7664                    fname.toString(),
7665                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7666                    -1, -1);
7667        } catch (java.io.IOException e) {
7668        }
7669    }
7670
7671    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7672        if (srcFile.isDirectory()) {
7673            final File baseFile = new File(pkg.baseCodePath);
7674            long maxModifiedTime = baseFile.lastModified();
7675            if (pkg.splitCodePaths != null) {
7676                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7677                    final File splitFile = new File(pkg.splitCodePaths[i]);
7678                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7679                }
7680            }
7681            return maxModifiedTime;
7682        }
7683        return srcFile.lastModified();
7684    }
7685
7686    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7687            final int policyFlags) throws PackageManagerException {
7688        // When upgrading from pre-N MR1, verify the package time stamp using the package
7689        // directory and not the APK file.
7690        final long lastModifiedTime = mIsPreNMR1Upgrade
7691                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7692        if (ps != null
7693                && ps.codePath.equals(srcFile)
7694                && ps.timeStamp == lastModifiedTime
7695                && !isCompatSignatureUpdateNeeded(pkg)
7696                && !isRecoverSignatureUpdateNeeded(pkg)) {
7697            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7698            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7699            ArraySet<PublicKey> signingKs;
7700            synchronized (mPackages) {
7701                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7702            }
7703            if (ps.signatures.mSignatures != null
7704                    && ps.signatures.mSignatures.length != 0
7705                    && signingKs != null) {
7706                // Optimization: reuse the existing cached certificates
7707                // if the package appears to be unchanged.
7708                pkg.mSignatures = ps.signatures.mSignatures;
7709                pkg.mSigningKeys = signingKs;
7710                return;
7711            }
7712
7713            Slog.w(TAG, "PackageSetting for " + ps.name
7714                    + " is missing signatures.  Collecting certs again to recover them.");
7715        } else {
7716            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7717        }
7718
7719        try {
7720            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7721            PackageParser.collectCertificates(pkg, policyFlags);
7722        } catch (PackageParserException e) {
7723            throw PackageManagerException.from(e);
7724        } finally {
7725            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7726        }
7727    }
7728
7729    /**
7730     *  Traces a package scan.
7731     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7732     */
7733    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7734            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7735        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7736        try {
7737            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7738        } finally {
7739            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7740        }
7741    }
7742
7743    /**
7744     *  Scans a package and returns the newly parsed package.
7745     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7746     */
7747    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7748            long currentTime, UserHandle user) throws PackageManagerException {
7749        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7750        PackageParser pp = new PackageParser();
7751        pp.setSeparateProcesses(mSeparateProcesses);
7752        pp.setOnlyCoreApps(mOnlyCore);
7753        pp.setDisplayMetrics(mMetrics);
7754        pp.setCallback(mPackageParserCallback);
7755
7756        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7757            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7758        }
7759
7760        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7761        final PackageParser.Package pkg;
7762        try {
7763            pkg = pp.parsePackage(scanFile, parseFlags);
7764        } catch (PackageParserException e) {
7765            throw PackageManagerException.from(e);
7766        } finally {
7767            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7768        }
7769
7770        // Static shared libraries have synthetic package names
7771        if (pkg.applicationInfo.isStaticSharedLibrary()) {
7772            renameStaticSharedLibraryPackage(pkg);
7773        }
7774
7775        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7776    }
7777
7778    /**
7779     *  Scans a package and returns the newly parsed package.
7780     *  @throws PackageManagerException on a parse error.
7781     */
7782    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7783            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7784            throws PackageManagerException {
7785        // If the package has children and this is the first dive in the function
7786        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7787        // packages (parent and children) would be successfully scanned before the
7788        // actual scan since scanning mutates internal state and we want to atomically
7789        // install the package and its children.
7790        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7791            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7792                scanFlags |= SCAN_CHECK_ONLY;
7793            }
7794        } else {
7795            scanFlags &= ~SCAN_CHECK_ONLY;
7796        }
7797
7798        // Scan the parent
7799        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7800                scanFlags, currentTime, user);
7801
7802        // Scan the children
7803        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7804        for (int i = 0; i < childCount; i++) {
7805            PackageParser.Package childPackage = pkg.childPackages.get(i);
7806            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7807                    currentTime, user);
7808        }
7809
7810
7811        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7812            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7813        }
7814
7815        return scannedPkg;
7816    }
7817
7818    /**
7819     *  Scans a package and returns the newly parsed package.
7820     *  @throws PackageManagerException on a parse error.
7821     */
7822    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7823            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
7824            throws PackageManagerException {
7825        PackageSetting ps = null;
7826        PackageSetting updatedPkg;
7827        // reader
7828        synchronized (mPackages) {
7829            // Look to see if we already know about this package.
7830            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7831            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7832                // This package has been renamed to its original name.  Let's
7833                // use that.
7834                ps = mSettings.getPackageLPr(oldName);
7835            }
7836            // If there was no original package, see one for the real package name.
7837            if (ps == null) {
7838                ps = mSettings.getPackageLPr(pkg.packageName);
7839            }
7840            // Check to see if this package could be hiding/updating a system
7841            // package.  Must look for it either under the original or real
7842            // package name depending on our state.
7843            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7844            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7845
7846            // If this is a package we don't know about on the system partition, we
7847            // may need to remove disabled child packages on the system partition
7848            // or may need to not add child packages if the parent apk is updated
7849            // on the data partition and no longer defines this child package.
7850            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7851                // If this is a parent package for an updated system app and this system
7852                // app got an OTA update which no longer defines some of the child packages
7853                // we have to prune them from the disabled system packages.
7854                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7855                if (disabledPs != null) {
7856                    final int scannedChildCount = (pkg.childPackages != null)
7857                            ? pkg.childPackages.size() : 0;
7858                    final int disabledChildCount = disabledPs.childPackageNames != null
7859                            ? disabledPs.childPackageNames.size() : 0;
7860                    for (int i = 0; i < disabledChildCount; i++) {
7861                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7862                        boolean disabledPackageAvailable = false;
7863                        for (int j = 0; j < scannedChildCount; j++) {
7864                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7865                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7866                                disabledPackageAvailable = true;
7867                                break;
7868                            }
7869                         }
7870                         if (!disabledPackageAvailable) {
7871                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7872                         }
7873                    }
7874                }
7875            }
7876        }
7877
7878        boolean updatedPkgBetter = false;
7879        // First check if this is a system package that may involve an update
7880        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7881            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7882            // it needs to drop FLAG_PRIVILEGED.
7883            if (locationIsPrivileged(scanFile)) {
7884                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7885            } else {
7886                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7887            }
7888
7889            if (ps != null && !ps.codePath.equals(scanFile)) {
7890                // The path has changed from what was last scanned...  check the
7891                // version of the new path against what we have stored to determine
7892                // what to do.
7893                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7894                if (pkg.mVersionCode <= ps.versionCode) {
7895                    // The system package has been updated and the code path does not match
7896                    // Ignore entry. Skip it.
7897                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7898                            + " ignored: updated version " + ps.versionCode
7899                            + " better than this " + pkg.mVersionCode);
7900                    if (!updatedPkg.codePath.equals(scanFile)) {
7901                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7902                                + ps.name + " changing from " + updatedPkg.codePathString
7903                                + " to " + scanFile);
7904                        updatedPkg.codePath = scanFile;
7905                        updatedPkg.codePathString = scanFile.toString();
7906                        updatedPkg.resourcePath = scanFile;
7907                        updatedPkg.resourcePathString = scanFile.toString();
7908                    }
7909                    updatedPkg.pkg = pkg;
7910                    updatedPkg.versionCode = pkg.mVersionCode;
7911
7912                    // Update the disabled system child packages to point to the package too.
7913                    final int childCount = updatedPkg.childPackageNames != null
7914                            ? updatedPkg.childPackageNames.size() : 0;
7915                    for (int i = 0; i < childCount; i++) {
7916                        String childPackageName = updatedPkg.childPackageNames.get(i);
7917                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7918                                childPackageName);
7919                        if (updatedChildPkg != null) {
7920                            updatedChildPkg.pkg = pkg;
7921                            updatedChildPkg.versionCode = pkg.mVersionCode;
7922                        }
7923                    }
7924
7925                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7926                            + scanFile + " ignored: updated version " + ps.versionCode
7927                            + " better than this " + pkg.mVersionCode);
7928                } else {
7929                    // The current app on the system partition is better than
7930                    // what we have updated to on the data partition; switch
7931                    // back to the system partition version.
7932                    // At this point, its safely assumed that package installation for
7933                    // apps in system partition will go through. If not there won't be a working
7934                    // version of the app
7935                    // writer
7936                    synchronized (mPackages) {
7937                        // Just remove the loaded entries from package lists.
7938                        mPackages.remove(ps.name);
7939                    }
7940
7941                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7942                            + " reverting from " + ps.codePathString
7943                            + ": new version " + pkg.mVersionCode
7944                            + " better than installed " + ps.versionCode);
7945
7946                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7947                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7948                    synchronized (mInstallLock) {
7949                        args.cleanUpResourcesLI();
7950                    }
7951                    synchronized (mPackages) {
7952                        mSettings.enableSystemPackageLPw(ps.name);
7953                    }
7954                    updatedPkgBetter = true;
7955                }
7956            }
7957        }
7958
7959        if (updatedPkg != null) {
7960            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7961            // initially
7962            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7963
7964            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7965            // flag set initially
7966            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7967                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7968            }
7969        }
7970
7971        // Verify certificates against what was last scanned
7972        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7973
7974        /*
7975         * A new system app appeared, but we already had a non-system one of the
7976         * same name installed earlier.
7977         */
7978        boolean shouldHideSystemApp = false;
7979        if (updatedPkg == null && ps != null
7980                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7981            /*
7982             * Check to make sure the signatures match first. If they don't,
7983             * wipe the installed application and its data.
7984             */
7985            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7986                    != PackageManager.SIGNATURE_MATCH) {
7987                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7988                        + " signatures don't match existing userdata copy; removing");
7989                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7990                        "scanPackageInternalLI")) {
7991                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7992                }
7993                ps = null;
7994            } else {
7995                /*
7996                 * If the newly-added system app is an older version than the
7997                 * already installed version, hide it. It will be scanned later
7998                 * and re-added like an update.
7999                 */
8000                if (pkg.mVersionCode <= ps.versionCode) {
8001                    shouldHideSystemApp = true;
8002                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
8003                            + " but new version " + pkg.mVersionCode + " better than installed "
8004                            + ps.versionCode + "; hiding system");
8005                } else {
8006                    /*
8007                     * The newly found system app is a newer version that the
8008                     * one previously installed. Simply remove the
8009                     * already-installed application and replace it with our own
8010                     * while keeping the application data.
8011                     */
8012                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
8013                            + " reverting from " + ps.codePathString + ": new version "
8014                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
8015                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
8016                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
8017                    synchronized (mInstallLock) {
8018                        args.cleanUpResourcesLI();
8019                    }
8020                }
8021            }
8022        }
8023
8024        // The apk is forward locked (not public) if its code and resources
8025        // are kept in different files. (except for app in either system or
8026        // vendor path).
8027        // TODO grab this value from PackageSettings
8028        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8029            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
8030                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
8031            }
8032        }
8033
8034        // TODO: extend to support forward-locked splits
8035        String resourcePath = null;
8036        String baseResourcePath = null;
8037        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
8038            if (ps != null && ps.resourcePathString != null) {
8039                resourcePath = ps.resourcePathString;
8040                baseResourcePath = ps.resourcePathString;
8041            } else {
8042                // Should not happen at all. Just log an error.
8043                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
8044            }
8045        } else {
8046            resourcePath = pkg.codePath;
8047            baseResourcePath = pkg.baseCodePath;
8048        }
8049
8050        // Set application objects path explicitly.
8051        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8052        pkg.setApplicationInfoCodePath(pkg.codePath);
8053        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8054        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8055        pkg.setApplicationInfoResourcePath(resourcePath);
8056        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
8057        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8058
8059        final int userId = ((user == null) ? 0 : user.getIdentifier());
8060        if (ps != null && ps.getInstantApp(userId)) {
8061            scanFlags |= SCAN_AS_INSTANT_APP;
8062        }
8063
8064        // Note that we invoke the following method only if we are about to unpack an application
8065        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
8066                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8067
8068        /*
8069         * If the system app should be overridden by a previously installed
8070         * data, hide the system app now and let the /data/app scan pick it up
8071         * again.
8072         */
8073        if (shouldHideSystemApp) {
8074            synchronized (mPackages) {
8075                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8076            }
8077        }
8078
8079        return scannedPkg;
8080    }
8081
8082    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8083        // Derive the new package synthetic package name
8084        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8085                + pkg.staticSharedLibVersion);
8086    }
8087
8088    private static String fixProcessName(String defProcessName,
8089            String processName) {
8090        if (processName == null) {
8091            return defProcessName;
8092        }
8093        return processName;
8094    }
8095
8096    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
8097            throws PackageManagerException {
8098        if (pkgSetting.signatures.mSignatures != null) {
8099            // Already existing package. Make sure signatures match
8100            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
8101                    == PackageManager.SIGNATURE_MATCH;
8102            if (!match) {
8103                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
8104                        == PackageManager.SIGNATURE_MATCH;
8105            }
8106            if (!match) {
8107                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
8108                        == PackageManager.SIGNATURE_MATCH;
8109            }
8110            if (!match) {
8111                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
8112                        + pkg.packageName + " signatures do not match the "
8113                        + "previously installed version; ignoring!");
8114            }
8115        }
8116
8117        // Check for shared user signatures
8118        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
8119            // Already existing package. Make sure signatures match
8120            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8121                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
8122            if (!match) {
8123                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
8124                        == PackageManager.SIGNATURE_MATCH;
8125            }
8126            if (!match) {
8127                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
8128                        == PackageManager.SIGNATURE_MATCH;
8129            }
8130            if (!match) {
8131                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
8132                        "Package " + pkg.packageName
8133                        + " has no signatures that match those in shared user "
8134                        + pkgSetting.sharedUser.name + "; ignoring!");
8135            }
8136        }
8137    }
8138
8139    /**
8140     * Enforces that only the system UID or root's UID can call a method exposed
8141     * via Binder.
8142     *
8143     * @param message used as message if SecurityException is thrown
8144     * @throws SecurityException if the caller is not system or root
8145     */
8146    private static final void enforceSystemOrRoot(String message) {
8147        final int uid = Binder.getCallingUid();
8148        if (uid != Process.SYSTEM_UID && uid != 0) {
8149            throw new SecurityException(message);
8150        }
8151    }
8152
8153    @Override
8154    public void performFstrimIfNeeded() {
8155        enforceSystemOrRoot("Only the system can request fstrim");
8156
8157        // Before everything else, see whether we need to fstrim.
8158        try {
8159            IStorageManager sm = PackageHelper.getStorageManager();
8160            if (sm != null) {
8161                boolean doTrim = false;
8162                final long interval = android.provider.Settings.Global.getLong(
8163                        mContext.getContentResolver(),
8164                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8165                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8166                if (interval > 0) {
8167                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8168                    if (timeSinceLast > interval) {
8169                        doTrim = true;
8170                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8171                                + "; running immediately");
8172                    }
8173                }
8174                if (doTrim) {
8175                    final boolean dexOptDialogShown;
8176                    synchronized (mPackages) {
8177                        dexOptDialogShown = mDexOptDialogShown;
8178                    }
8179                    if (!isFirstBoot() && dexOptDialogShown) {
8180                        try {
8181                            ActivityManager.getService().showBootMessage(
8182                                    mContext.getResources().getString(
8183                                            R.string.android_upgrading_fstrim), true);
8184                        } catch (RemoteException e) {
8185                        }
8186                    }
8187                    sm.runMaintenance();
8188                }
8189            } else {
8190                Slog.e(TAG, "storageManager service unavailable!");
8191            }
8192        } catch (RemoteException e) {
8193            // Can't happen; StorageManagerService is local
8194        }
8195    }
8196
8197    @Override
8198    public void updatePackagesIfNeeded() {
8199        enforceSystemOrRoot("Only the system can request package update");
8200
8201        // We need to re-extract after an OTA.
8202        boolean causeUpgrade = isUpgrade();
8203
8204        // First boot or factory reset.
8205        // Note: we also handle devices that are upgrading to N right now as if it is their
8206        //       first boot, as they do not have profile data.
8207        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8208
8209        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8210        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8211
8212        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8213            return;
8214        }
8215
8216        List<PackageParser.Package> pkgs;
8217        synchronized (mPackages) {
8218            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8219        }
8220
8221        final long startTime = System.nanoTime();
8222        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8223                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8224
8225        final int elapsedTimeSeconds =
8226                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8227
8228        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8229        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8230        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8231        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8232        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8233    }
8234
8235    /**
8236     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8237     * containing statistics about the invocation. The array consists of three elements,
8238     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8239     * and {@code numberOfPackagesFailed}.
8240     */
8241    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8242            String compilerFilter) {
8243
8244        int numberOfPackagesVisited = 0;
8245        int numberOfPackagesOptimized = 0;
8246        int numberOfPackagesSkipped = 0;
8247        int numberOfPackagesFailed = 0;
8248        final int numberOfPackagesToDexopt = pkgs.size();
8249
8250        for (PackageParser.Package pkg : pkgs) {
8251            numberOfPackagesVisited++;
8252
8253            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8254                if (DEBUG_DEXOPT) {
8255                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8256                }
8257                numberOfPackagesSkipped++;
8258                continue;
8259            }
8260
8261            if (DEBUG_DEXOPT) {
8262                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8263                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8264            }
8265
8266            if (showDialog) {
8267                try {
8268                    ActivityManager.getService().showBootMessage(
8269                            mContext.getResources().getString(R.string.android_upgrading_apk,
8270                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8271                } catch (RemoteException e) {
8272                }
8273                synchronized (mPackages) {
8274                    mDexOptDialogShown = true;
8275                }
8276            }
8277
8278            // If the OTA updates a system app which was previously preopted to a non-preopted state
8279            // the app might end up being verified at runtime. That's because by default the apps
8280            // are verify-profile but for preopted apps there's no profile.
8281            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8282            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8283            // filter (by default interpret-only).
8284            // Note that at this stage unused apps are already filtered.
8285            if (isSystemApp(pkg) &&
8286                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8287                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8288                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8289            }
8290
8291            // checkProfiles is false to avoid merging profiles during boot which
8292            // might interfere with background compilation (b/28612421).
8293            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8294            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8295            // trade-off worth doing to save boot time work.
8296            int dexOptStatus = performDexOptTraced(pkg.packageName,
8297                    false /* checkProfiles */,
8298                    compilerFilter,
8299                    false /* force */);
8300            switch (dexOptStatus) {
8301                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8302                    numberOfPackagesOptimized++;
8303                    break;
8304                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8305                    numberOfPackagesSkipped++;
8306                    break;
8307                case PackageDexOptimizer.DEX_OPT_FAILED:
8308                    numberOfPackagesFailed++;
8309                    break;
8310                default:
8311                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8312                    break;
8313            }
8314        }
8315
8316        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8317                numberOfPackagesFailed };
8318    }
8319
8320    @Override
8321    public void notifyPackageUse(String packageName, int reason) {
8322        synchronized (mPackages) {
8323            PackageParser.Package p = mPackages.get(packageName);
8324            if (p == null) {
8325                return;
8326            }
8327            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8328        }
8329    }
8330
8331    @Override
8332    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8333        int userId = UserHandle.getCallingUserId();
8334        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8335        if (ai == null) {
8336            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8337                + loadingPackageName + ", user=" + userId);
8338            return;
8339        }
8340        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8341    }
8342
8343    // TODO: this is not used nor needed. Delete it.
8344    @Override
8345    public boolean performDexOptIfNeeded(String packageName) {
8346        int dexOptStatus = performDexOptTraced(packageName,
8347                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
8348        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8349    }
8350
8351    @Override
8352    public boolean performDexOpt(String packageName,
8353            boolean checkProfiles, int compileReason, boolean force) {
8354        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8355                getCompilerFilterForReason(compileReason), force);
8356        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8357    }
8358
8359    @Override
8360    public boolean performDexOptMode(String packageName,
8361            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8362        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8363                targetCompilerFilter, force);
8364        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8365    }
8366
8367    private int performDexOptTraced(String packageName,
8368                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8369        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8370        try {
8371            return performDexOptInternal(packageName, checkProfiles,
8372                    targetCompilerFilter, force);
8373        } finally {
8374            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8375        }
8376    }
8377
8378    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8379    // if the package can now be considered up to date for the given filter.
8380    private int performDexOptInternal(String packageName,
8381                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8382        PackageParser.Package p;
8383        synchronized (mPackages) {
8384            p = mPackages.get(packageName);
8385            if (p == null) {
8386                // Package could not be found. Report failure.
8387                return PackageDexOptimizer.DEX_OPT_FAILED;
8388            }
8389            mPackageUsage.maybeWriteAsync(mPackages);
8390            mCompilerStats.maybeWriteAsync();
8391        }
8392        long callingId = Binder.clearCallingIdentity();
8393        try {
8394            synchronized (mInstallLock) {
8395                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8396                        targetCompilerFilter, force);
8397            }
8398        } finally {
8399            Binder.restoreCallingIdentity(callingId);
8400        }
8401    }
8402
8403    public ArraySet<String> getOptimizablePackages() {
8404        ArraySet<String> pkgs = new ArraySet<String>();
8405        synchronized (mPackages) {
8406            for (PackageParser.Package p : mPackages.values()) {
8407                if (PackageDexOptimizer.canOptimizePackage(p)) {
8408                    pkgs.add(p.packageName);
8409                }
8410            }
8411        }
8412        return pkgs;
8413    }
8414
8415    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8416            boolean checkProfiles, String targetCompilerFilter,
8417            boolean force) {
8418        // Select the dex optimizer based on the force parameter.
8419        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8420        //       allocate an object here.
8421        PackageDexOptimizer pdo = force
8422                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8423                : mPackageDexOptimizer;
8424
8425        // Dexopt all dependencies first. Note: we ignore the return value and march on
8426        // on errors.
8427        // Note that we are going to call performDexOpt on those libraries as many times as
8428        // they are referenced in packages. When we do a batch of performDexOpt (for example
8429        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
8430        // and the first package that uses the library will dexopt it. The
8431        // others will see that the compiled code for the library is up to date.
8432        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8433        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8434        if (!deps.isEmpty()) {
8435            for (PackageParser.Package depPackage : deps) {
8436                // TODO: Analyze and investigate if we (should) profile libraries.
8437                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8438                        false /* checkProfiles */,
8439                        targetCompilerFilter,
8440                        getOrCreateCompilerPackageStats(depPackage),
8441                        true /* isUsedByOtherApps */);
8442            }
8443        }
8444        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8445                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
8446                mDexManager.isUsedByOtherApps(p.packageName));
8447    }
8448
8449    // Performs dexopt on the used secondary dex files belonging to the given package.
8450    // Returns true if all dex files were process successfully (which could mean either dexopt or
8451    // skip). Returns false if any of the files caused errors.
8452    @Override
8453    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8454            boolean force) {
8455        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8456    }
8457
8458    public boolean performDexOptSecondary(String packageName, int compileReason,
8459            boolean force) {
8460        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
8461    }
8462
8463    /**
8464     * Reconcile the information we have about the secondary dex files belonging to
8465     * {@code packagName} and the actual dex files. For all dex files that were
8466     * deleted, update the internal records and delete the generated oat files.
8467     */
8468    @Override
8469    public void reconcileSecondaryDexFiles(String packageName) {
8470        mDexManager.reconcileSecondaryDexFiles(packageName);
8471    }
8472
8473    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8474    // a reference there.
8475    /*package*/ DexManager getDexManager() {
8476        return mDexManager;
8477    }
8478
8479    /**
8480     * Execute the background dexopt job immediately.
8481     */
8482    @Override
8483    public boolean runBackgroundDexoptJob() {
8484        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8485    }
8486
8487    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8488        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8489                || p.usesStaticLibraries != null) {
8490            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8491            Set<String> collectedNames = new HashSet<>();
8492            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8493
8494            retValue.remove(p);
8495
8496            return retValue;
8497        } else {
8498            return Collections.emptyList();
8499        }
8500    }
8501
8502    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8503            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8504        if (!collectedNames.contains(p.packageName)) {
8505            collectedNames.add(p.packageName);
8506            collected.add(p);
8507
8508            if (p.usesLibraries != null) {
8509                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8510                        null, collected, collectedNames);
8511            }
8512            if (p.usesOptionalLibraries != null) {
8513                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8514                        null, collected, collectedNames);
8515            }
8516            if (p.usesStaticLibraries != null) {
8517                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8518                        p.usesStaticLibrariesVersions, collected, collectedNames);
8519            }
8520        }
8521    }
8522
8523    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8524            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8525        final int libNameCount = libs.size();
8526        for (int i = 0; i < libNameCount; i++) {
8527            String libName = libs.get(i);
8528            int version = (versions != null && versions.length == libNameCount)
8529                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8530            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8531            if (libPkg != null) {
8532                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8533            }
8534        }
8535    }
8536
8537    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8538        synchronized (mPackages) {
8539            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8540            if (libEntry != null) {
8541                return mPackages.get(libEntry.apk);
8542            }
8543            return null;
8544        }
8545    }
8546
8547    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8548        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8549        if (versionedLib == null) {
8550            return null;
8551        }
8552        return versionedLib.get(version);
8553    }
8554
8555    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
8556        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
8557                pkg.staticSharedLibName);
8558        if (versionedLib == null) {
8559            return null;
8560        }
8561        int previousLibVersion = -1;
8562        final int versionCount = versionedLib.size();
8563        for (int i = 0; i < versionCount; i++) {
8564            final int libVersion = versionedLib.keyAt(i);
8565            if (libVersion < pkg.staticSharedLibVersion) {
8566                previousLibVersion = Math.max(previousLibVersion, libVersion);
8567            }
8568        }
8569        if (previousLibVersion >= 0) {
8570            return versionedLib.get(previousLibVersion);
8571        }
8572        return null;
8573    }
8574
8575    public void shutdown() {
8576        mPackageUsage.writeNow(mPackages);
8577        mCompilerStats.writeNow();
8578    }
8579
8580    @Override
8581    public void dumpProfiles(String packageName) {
8582        PackageParser.Package pkg;
8583        synchronized (mPackages) {
8584            pkg = mPackages.get(packageName);
8585            if (pkg == null) {
8586                throw new IllegalArgumentException("Unknown package: " + packageName);
8587            }
8588        }
8589        /* Only the shell, root, or the app user should be able to dump profiles. */
8590        int callingUid = Binder.getCallingUid();
8591        if (callingUid != Process.SHELL_UID &&
8592            callingUid != Process.ROOT_UID &&
8593            callingUid != pkg.applicationInfo.uid) {
8594            throw new SecurityException("dumpProfiles");
8595        }
8596
8597        synchronized (mInstallLock) {
8598            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
8599            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
8600            try {
8601                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
8602                String codePaths = TextUtils.join(";", allCodePaths);
8603                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
8604            } catch (InstallerException e) {
8605                Slog.w(TAG, "Failed to dump profiles", e);
8606            }
8607            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8608        }
8609    }
8610
8611    @Override
8612    public void forceDexOpt(String packageName) {
8613        enforceSystemOrRoot("forceDexOpt");
8614
8615        PackageParser.Package pkg;
8616        synchronized (mPackages) {
8617            pkg = mPackages.get(packageName);
8618            if (pkg == null) {
8619                throw new IllegalArgumentException("Unknown package: " + packageName);
8620            }
8621        }
8622
8623        synchronized (mInstallLock) {
8624            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8625
8626            // Whoever is calling forceDexOpt wants a fully compiled package.
8627            // Don't use profiles since that may cause compilation to be skipped.
8628            final int res = performDexOptInternalWithDependenciesLI(pkg,
8629                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
8630                    true /* force */);
8631
8632            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8633            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
8634                throw new IllegalStateException("Failed to dexopt: " + res);
8635            }
8636        }
8637    }
8638
8639    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
8640        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8641            Slog.w(TAG, "Unable to update from " + oldPkg.name
8642                    + " to " + newPkg.packageName
8643                    + ": old package not in system partition");
8644            return false;
8645        } else if (mPackages.get(oldPkg.name) != null) {
8646            Slog.w(TAG, "Unable to update from " + oldPkg.name
8647                    + " to " + newPkg.packageName
8648                    + ": old package still exists");
8649            return false;
8650        }
8651        return true;
8652    }
8653
8654    void removeCodePathLI(File codePath) {
8655        if (codePath.isDirectory()) {
8656            try {
8657                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8658            } catch (InstallerException e) {
8659                Slog.w(TAG, "Failed to remove code path", e);
8660            }
8661        } else {
8662            codePath.delete();
8663        }
8664    }
8665
8666    private int[] resolveUserIds(int userId) {
8667        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8668    }
8669
8670    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8671        if (pkg == null) {
8672            Slog.wtf(TAG, "Package was null!", new Throwable());
8673            return;
8674        }
8675        clearAppDataLeafLIF(pkg, userId, flags);
8676        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8677        for (int i = 0; i < childCount; i++) {
8678            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8679        }
8680    }
8681
8682    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8683        final PackageSetting ps;
8684        synchronized (mPackages) {
8685            ps = mSettings.mPackages.get(pkg.packageName);
8686        }
8687        for (int realUserId : resolveUserIds(userId)) {
8688            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8689            try {
8690                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8691                        ceDataInode);
8692            } catch (InstallerException e) {
8693                Slog.w(TAG, String.valueOf(e));
8694            }
8695        }
8696    }
8697
8698    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8699        if (pkg == null) {
8700            Slog.wtf(TAG, "Package was null!", new Throwable());
8701            return;
8702        }
8703        destroyAppDataLeafLIF(pkg, userId, flags);
8704        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8705        for (int i = 0; i < childCount; i++) {
8706            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8707        }
8708    }
8709
8710    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8711        final PackageSetting ps;
8712        synchronized (mPackages) {
8713            ps = mSettings.mPackages.get(pkg.packageName);
8714        }
8715        for (int realUserId : resolveUserIds(userId)) {
8716            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8717            try {
8718                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8719                        ceDataInode);
8720            } catch (InstallerException e) {
8721                Slog.w(TAG, String.valueOf(e));
8722            }
8723            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
8724        }
8725    }
8726
8727    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8728        if (pkg == null) {
8729            Slog.wtf(TAG, "Package was null!", new Throwable());
8730            return;
8731        }
8732        destroyAppProfilesLeafLIF(pkg);
8733        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8734        for (int i = 0; i < childCount; i++) {
8735            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8736        }
8737    }
8738
8739    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8740        try {
8741            mInstaller.destroyAppProfiles(pkg.packageName);
8742        } catch (InstallerException e) {
8743            Slog.w(TAG, String.valueOf(e));
8744        }
8745    }
8746
8747    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8748        if (pkg == null) {
8749            Slog.wtf(TAG, "Package was null!", new Throwable());
8750            return;
8751        }
8752        clearAppProfilesLeafLIF(pkg);
8753        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8754        for (int i = 0; i < childCount; i++) {
8755            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8756        }
8757    }
8758
8759    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8760        try {
8761            mInstaller.clearAppProfiles(pkg.packageName);
8762        } catch (InstallerException e) {
8763            Slog.w(TAG, String.valueOf(e));
8764        }
8765    }
8766
8767    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8768            long lastUpdateTime) {
8769        // Set parent install/update time
8770        PackageSetting ps = (PackageSetting) pkg.mExtras;
8771        if (ps != null) {
8772            ps.firstInstallTime = firstInstallTime;
8773            ps.lastUpdateTime = lastUpdateTime;
8774        }
8775        // Set children install/update time
8776        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8777        for (int i = 0; i < childCount; i++) {
8778            PackageParser.Package childPkg = pkg.childPackages.get(i);
8779            ps = (PackageSetting) childPkg.mExtras;
8780            if (ps != null) {
8781                ps.firstInstallTime = firstInstallTime;
8782                ps.lastUpdateTime = lastUpdateTime;
8783            }
8784        }
8785    }
8786
8787    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8788            PackageParser.Package changingLib) {
8789        if (file.path != null) {
8790            usesLibraryFiles.add(file.path);
8791            return;
8792        }
8793        PackageParser.Package p = mPackages.get(file.apk);
8794        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8795            // If we are doing this while in the middle of updating a library apk,
8796            // then we need to make sure to use that new apk for determining the
8797            // dependencies here.  (We haven't yet finished committing the new apk
8798            // to the package manager state.)
8799            if (p == null || p.packageName.equals(changingLib.packageName)) {
8800                p = changingLib;
8801            }
8802        }
8803        if (p != null) {
8804            usesLibraryFiles.addAll(p.getAllCodePaths());
8805        }
8806    }
8807
8808    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8809            PackageParser.Package changingLib) throws PackageManagerException {
8810        if (pkg == null) {
8811            return;
8812        }
8813        ArraySet<String> usesLibraryFiles = null;
8814        if (pkg.usesLibraries != null) {
8815            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
8816                    null, null, pkg.packageName, changingLib, true, null);
8817        }
8818        if (pkg.usesStaticLibraries != null) {
8819            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
8820                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
8821                    pkg.packageName, changingLib, true, usesLibraryFiles);
8822        }
8823        if (pkg.usesOptionalLibraries != null) {
8824            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
8825                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
8826        }
8827        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
8828            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
8829        } else {
8830            pkg.usesLibraryFiles = null;
8831        }
8832    }
8833
8834    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
8835            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
8836            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
8837            boolean required, @Nullable ArraySet<String> outUsedLibraries)
8838            throws PackageManagerException {
8839        final int libCount = requestedLibraries.size();
8840        for (int i = 0; i < libCount; i++) {
8841            final String libName = requestedLibraries.get(i);
8842            final int libVersion = requiredVersions != null ? requiredVersions[i]
8843                    : SharedLibraryInfo.VERSION_UNDEFINED;
8844            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
8845            if (libEntry == null) {
8846                if (required) {
8847                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8848                            "Package " + packageName + " requires unavailable shared library "
8849                                    + libName + "; failing!");
8850                } else {
8851                    Slog.w(TAG, "Package " + packageName
8852                            + " desires unavailable shared library "
8853                            + libName + "; ignoring!");
8854                }
8855            } else {
8856                if (requiredVersions != null && requiredCertDigests != null) {
8857                    if (libEntry.info.getVersion() != requiredVersions[i]) {
8858                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8859                            "Package " + packageName + " requires unavailable static shared"
8860                                    + " library " + libName + " version "
8861                                    + libEntry.info.getVersion() + "; failing!");
8862                    }
8863
8864                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
8865                    if (libPkg == null) {
8866                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8867                                "Package " + packageName + " requires unavailable static shared"
8868                                        + " library; failing!");
8869                    }
8870
8871                    String expectedCertDigest = requiredCertDigests[i];
8872                    String libCertDigest = PackageUtils.computeCertSha256Digest(
8873                                libPkg.mSignatures[0]);
8874                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
8875                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8876                                "Package " + packageName + " requires differently signed" +
8877                                        " static shared library; failing!");
8878                    }
8879                }
8880
8881                if (outUsedLibraries == null) {
8882                    outUsedLibraries = new ArraySet<>();
8883                }
8884                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
8885            }
8886        }
8887        return outUsedLibraries;
8888    }
8889
8890    private static boolean hasString(List<String> list, List<String> which) {
8891        if (list == null) {
8892            return false;
8893        }
8894        for (int i=list.size()-1; i>=0; i--) {
8895            for (int j=which.size()-1; j>=0; j--) {
8896                if (which.get(j).equals(list.get(i))) {
8897                    return true;
8898                }
8899            }
8900        }
8901        return false;
8902    }
8903
8904    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
8905            PackageParser.Package changingPkg) {
8906        ArrayList<PackageParser.Package> res = null;
8907        for (PackageParser.Package pkg : mPackages.values()) {
8908            if (changingPkg != null
8909                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
8910                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
8911                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
8912                            changingPkg.staticSharedLibName)) {
8913                return null;
8914            }
8915            if (res == null) {
8916                res = new ArrayList<>();
8917            }
8918            res.add(pkg);
8919            try {
8920                updateSharedLibrariesLPr(pkg, changingPkg);
8921            } catch (PackageManagerException e) {
8922                // If a system app update or an app and a required lib missing we
8923                // delete the package and for updated system apps keep the data as
8924                // it is better for the user to reinstall than to be in an limbo
8925                // state. Also libs disappearing under an app should never happen
8926                // - just in case.
8927                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
8928                    final int flags = pkg.isUpdatedSystemApp()
8929                            ? PackageManager.DELETE_KEEP_DATA : 0;
8930                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
8931                            flags , null, true, null);
8932                }
8933                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8934            }
8935        }
8936        return res;
8937    }
8938
8939    /**
8940     * Derive the value of the {@code cpuAbiOverride} based on the provided
8941     * value and an optional stored value from the package settings.
8942     */
8943    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
8944        String cpuAbiOverride = null;
8945
8946        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
8947            cpuAbiOverride = null;
8948        } else if (abiOverride != null) {
8949            cpuAbiOverride = abiOverride;
8950        } else if (settings != null) {
8951            cpuAbiOverride = settings.cpuAbiOverrideString;
8952        }
8953
8954        return cpuAbiOverride;
8955    }
8956
8957    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8958            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8959                    throws PackageManagerException {
8960        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8961        // If the package has children and this is the first dive in the function
8962        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
8963        // whether all packages (parent and children) would be successfully scanned
8964        // before the actual scan since scanning mutates internal state and we want
8965        // to atomically install the package and its children.
8966        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8967            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8968                scanFlags |= SCAN_CHECK_ONLY;
8969            }
8970        } else {
8971            scanFlags &= ~SCAN_CHECK_ONLY;
8972        }
8973
8974        final PackageParser.Package scannedPkg;
8975        try {
8976            // Scan the parent
8977            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
8978            // Scan the children
8979            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8980            for (int i = 0; i < childCount; i++) {
8981                PackageParser.Package childPkg = pkg.childPackages.get(i);
8982                scanPackageLI(childPkg, policyFlags,
8983                        scanFlags, currentTime, user);
8984            }
8985        } finally {
8986            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8987        }
8988
8989        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8990            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
8991        }
8992
8993        return scannedPkg;
8994    }
8995
8996    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8997            int scanFlags, long currentTime, @Nullable UserHandle user)
8998                    throws PackageManagerException {
8999        boolean success = false;
9000        try {
9001            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
9002                    currentTime, user);
9003            success = true;
9004            return res;
9005        } finally {
9006            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
9007                // DELETE_DATA_ON_FAILURES is only used by frozen paths
9008                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
9009                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
9010                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
9011            }
9012        }
9013    }
9014
9015    /**
9016     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
9017     */
9018    private static boolean apkHasCode(String fileName) {
9019        StrictJarFile jarFile = null;
9020        try {
9021            jarFile = new StrictJarFile(fileName,
9022                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
9023            return jarFile.findEntry("classes.dex") != null;
9024        } catch (IOException ignore) {
9025        } finally {
9026            try {
9027                if (jarFile != null) {
9028                    jarFile.close();
9029                }
9030            } catch (IOException ignore) {}
9031        }
9032        return false;
9033    }
9034
9035    /**
9036     * Enforces code policy for the package. This ensures that if an APK has
9037     * declared hasCode="true" in its manifest that the APK actually contains
9038     * code.
9039     *
9040     * @throws PackageManagerException If bytecode could not be found when it should exist
9041     */
9042    private static void assertCodePolicy(PackageParser.Package pkg)
9043            throws PackageManagerException {
9044        final boolean shouldHaveCode =
9045                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
9046        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
9047            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9048                    "Package " + pkg.baseCodePath + " code is missing");
9049        }
9050
9051        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9052            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9053                final boolean splitShouldHaveCode =
9054                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
9055                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
9056                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9057                            "Package " + pkg.splitCodePaths[i] + " code is missing");
9058                }
9059            }
9060        }
9061    }
9062
9063    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
9064            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
9065                    throws PackageManagerException {
9066        if (DEBUG_PACKAGE_SCANNING) {
9067            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9068                Log.d(TAG, "Scanning package " + pkg.packageName);
9069        }
9070
9071        applyPolicy(pkg, policyFlags);
9072
9073        assertPackageIsValid(pkg, policyFlags, scanFlags);
9074
9075        // Initialize package source and resource directories
9076        final File scanFile = new File(pkg.codePath);
9077        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
9078        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
9079
9080        SharedUserSetting suid = null;
9081        PackageSetting pkgSetting = null;
9082
9083        // Getting the package setting may have a side-effect, so if we
9084        // are only checking if scan would succeed, stash a copy of the
9085        // old setting to restore at the end.
9086        PackageSetting nonMutatedPs = null;
9087
9088        // We keep references to the derived CPU Abis from settings in oder to reuse
9089        // them in the case where we're not upgrading or booting for the first time.
9090        String primaryCpuAbiFromSettings = null;
9091        String secondaryCpuAbiFromSettings = null;
9092
9093        // writer
9094        synchronized (mPackages) {
9095            if (pkg.mSharedUserId != null) {
9096                // SIDE EFFECTS; may potentially allocate a new shared user
9097                suid = mSettings.getSharedUserLPw(
9098                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9099                if (DEBUG_PACKAGE_SCANNING) {
9100                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
9101                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
9102                                + "): packages=" + suid.packages);
9103                }
9104            }
9105
9106            // Check if we are renaming from an original package name.
9107            PackageSetting origPackage = null;
9108            String realName = null;
9109            if (pkg.mOriginalPackages != null) {
9110                // This package may need to be renamed to a previously
9111                // installed name.  Let's check on that...
9112                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9113                if (pkg.mOriginalPackages.contains(renamed)) {
9114                    // This package had originally been installed as the
9115                    // original name, and we have already taken care of
9116                    // transitioning to the new one.  Just update the new
9117                    // one to continue using the old name.
9118                    realName = pkg.mRealPackage;
9119                    if (!pkg.packageName.equals(renamed)) {
9120                        // Callers into this function may have already taken
9121                        // care of renaming the package; only do it here if
9122                        // it is not already done.
9123                        pkg.setPackageName(renamed);
9124                    }
9125                } else {
9126                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
9127                        if ((origPackage = mSettings.getPackageLPr(
9128                                pkg.mOriginalPackages.get(i))) != null) {
9129                            // We do have the package already installed under its
9130                            // original name...  should we use it?
9131                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
9132                                // New package is not compatible with original.
9133                                origPackage = null;
9134                                continue;
9135                            } else if (origPackage.sharedUser != null) {
9136                                // Make sure uid is compatible between packages.
9137                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
9138                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
9139                                            + " to " + pkg.packageName + ": old uid "
9140                                            + origPackage.sharedUser.name
9141                                            + " differs from " + pkg.mSharedUserId);
9142                                    origPackage = null;
9143                                    continue;
9144                                }
9145                                // TODO: Add case when shared user id is added [b/28144775]
9146                            } else {
9147                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
9148                                        + pkg.packageName + " to old name " + origPackage.name);
9149                            }
9150                            break;
9151                        }
9152                    }
9153                }
9154            }
9155
9156            if (mTransferedPackages.contains(pkg.packageName)) {
9157                Slog.w(TAG, "Package " + pkg.packageName
9158                        + " was transferred to another, but its .apk remains");
9159            }
9160
9161            // See comments in nonMutatedPs declaration
9162            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9163                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9164                if (foundPs != null) {
9165                    nonMutatedPs = new PackageSetting(foundPs);
9166                }
9167            }
9168
9169            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9170                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9171                if (foundPs != null) {
9172                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9173                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9174                }
9175            }
9176
9177            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9178            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9179                PackageManagerService.reportSettingsProblem(Log.WARN,
9180                        "Package " + pkg.packageName + " shared user changed from "
9181                                + (pkgSetting.sharedUser != null
9182                                        ? pkgSetting.sharedUser.name : "<nothing>")
9183                                + " to "
9184                                + (suid != null ? suid.name : "<nothing>")
9185                                + "; replacing with new");
9186                pkgSetting = null;
9187            }
9188            final PackageSetting oldPkgSetting =
9189                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9190            final PackageSetting disabledPkgSetting =
9191                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9192
9193            String[] usesStaticLibraries = null;
9194            if (pkg.usesStaticLibraries != null) {
9195                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9196                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9197            }
9198
9199            if (pkgSetting == null) {
9200                final String parentPackageName = (pkg.parentPackage != null)
9201                        ? pkg.parentPackage.packageName : null;
9202                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
9203                // REMOVE SharedUserSetting from method; update in a separate call
9204                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9205                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9206                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9207                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9208                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9209                        true /*allowInstall*/, instantApp, parentPackageName,
9210                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
9211                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
9212                // SIDE EFFECTS; updates system state; move elsewhere
9213                if (origPackage != null) {
9214                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9215                }
9216                mSettings.addUserToSettingLPw(pkgSetting);
9217            } else {
9218                // REMOVE SharedUserSetting from method; update in a separate call.
9219                //
9220                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9221                // secondaryCpuAbi are not known at this point so we always update them
9222                // to null here, only to reset them at a later point.
9223                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9224                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9225                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9226                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9227                        UserManagerService.getInstance(), usesStaticLibraries,
9228                        pkg.usesStaticLibrariesVersions);
9229            }
9230            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9231            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9232
9233            // SIDE EFFECTS; modifies system state; move elsewhere
9234            if (pkgSetting.origPackage != null) {
9235                // If we are first transitioning from an original package,
9236                // fix up the new package's name now.  We need to do this after
9237                // looking up the package under its new name, so getPackageLP
9238                // can take care of fiddling things correctly.
9239                pkg.setPackageName(origPackage.name);
9240
9241                // File a report about this.
9242                String msg = "New package " + pkgSetting.realName
9243                        + " renamed to replace old package " + pkgSetting.name;
9244                reportSettingsProblem(Log.WARN, msg);
9245
9246                // Make a note of it.
9247                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9248                    mTransferedPackages.add(origPackage.name);
9249                }
9250
9251                // No longer need to retain this.
9252                pkgSetting.origPackage = null;
9253            }
9254
9255            // SIDE EFFECTS; modifies system state; move elsewhere
9256            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9257                // Make a note of it.
9258                mTransferedPackages.add(pkg.packageName);
9259            }
9260
9261            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9262                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9263            }
9264
9265            if ((scanFlags & SCAN_BOOTING) == 0
9266                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9267                // Check all shared libraries and map to their actual file path.
9268                // We only do this here for apps not on a system dir, because those
9269                // are the only ones that can fail an install due to this.  We
9270                // will take care of the system apps by updating all of their
9271                // library paths after the scan is done. Also during the initial
9272                // scan don't update any libs as we do this wholesale after all
9273                // apps are scanned to avoid dependency based scanning.
9274                updateSharedLibrariesLPr(pkg, null);
9275            }
9276
9277            if (mFoundPolicyFile) {
9278                SELinuxMMAC.assignSeInfoValue(pkg);
9279            }
9280            pkg.applicationInfo.uid = pkgSetting.appId;
9281            pkg.mExtras = pkgSetting;
9282
9283
9284            // Static shared libs have same package with different versions where
9285            // we internally use a synthetic package name to allow multiple versions
9286            // of the same package, therefore we need to compare signatures against
9287            // the package setting for the latest library version.
9288            PackageSetting signatureCheckPs = pkgSetting;
9289            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9290                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9291                if (libraryEntry != null) {
9292                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9293                }
9294            }
9295
9296            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9297                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9298                    // We just determined the app is signed correctly, so bring
9299                    // over the latest parsed certs.
9300                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9301                } else {
9302                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9303                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9304                                "Package " + pkg.packageName + " upgrade keys do not match the "
9305                                + "previously installed version");
9306                    } else {
9307                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9308                        String msg = "System package " + pkg.packageName
9309                                + " signature changed; retaining data.";
9310                        reportSettingsProblem(Log.WARN, msg);
9311                    }
9312                }
9313            } else {
9314                try {
9315                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9316                    verifySignaturesLP(signatureCheckPs, pkg);
9317                    // We just determined the app is signed correctly, so bring
9318                    // over the latest parsed certs.
9319                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9320                } catch (PackageManagerException e) {
9321                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9322                        throw e;
9323                    }
9324                    // The signature has changed, but this package is in the system
9325                    // image...  let's recover!
9326                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9327                    // However...  if this package is part of a shared user, but it
9328                    // doesn't match the signature of the shared user, let's fail.
9329                    // What this means is that you can't change the signatures
9330                    // associated with an overall shared user, which doesn't seem all
9331                    // that unreasonable.
9332                    if (signatureCheckPs.sharedUser != null) {
9333                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9334                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9335                            throw new PackageManagerException(
9336                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9337                                    "Signature mismatch for shared user: "
9338                                            + pkgSetting.sharedUser);
9339                        }
9340                    }
9341                    // File a report about this.
9342                    String msg = "System package " + pkg.packageName
9343                            + " signature changed; retaining data.";
9344                    reportSettingsProblem(Log.WARN, msg);
9345                }
9346            }
9347
9348            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9349                // This package wants to adopt ownership of permissions from
9350                // another package.
9351                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9352                    final String origName = pkg.mAdoptPermissions.get(i);
9353                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9354                    if (orig != null) {
9355                        if (verifyPackageUpdateLPr(orig, pkg)) {
9356                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9357                                    + pkg.packageName);
9358                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9359                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9360                        }
9361                    }
9362                }
9363            }
9364        }
9365
9366        pkg.applicationInfo.processName = fixProcessName(
9367                pkg.applicationInfo.packageName,
9368                pkg.applicationInfo.processName);
9369
9370        if (pkg != mPlatformPackage) {
9371            // Get all of our default paths setup
9372            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9373        }
9374
9375        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9376
9377        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9378            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9379                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9380                derivePackageAbi(
9381                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9382                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9383
9384                // Some system apps still use directory structure for native libraries
9385                // in which case we might end up not detecting abi solely based on apk
9386                // structure. Try to detect abi based on directory structure.
9387                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9388                        pkg.applicationInfo.primaryCpuAbi == null) {
9389                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9390                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9391                }
9392            } else {
9393                // This is not a first boot or an upgrade, don't bother deriving the
9394                // ABI during the scan. Instead, trust the value that was stored in the
9395                // package setting.
9396                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9397                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9398
9399                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9400
9401                if (DEBUG_ABI_SELECTION) {
9402                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9403                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9404                        pkg.applicationInfo.secondaryCpuAbi);
9405                }
9406            }
9407        } else {
9408            if ((scanFlags & SCAN_MOVE) != 0) {
9409                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9410                // but we already have this packages package info in the PackageSetting. We just
9411                // use that and derive the native library path based on the new codepath.
9412                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9413                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9414            }
9415
9416            // Set native library paths again. For moves, the path will be updated based on the
9417            // ABIs we've determined above. For non-moves, the path will be updated based on the
9418            // ABIs we determined during compilation, but the path will depend on the final
9419            // package path (after the rename away from the stage path).
9420            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9421        }
9422
9423        // This is a special case for the "system" package, where the ABI is
9424        // dictated by the zygote configuration (and init.rc). We should keep track
9425        // of this ABI so that we can deal with "normal" applications that run under
9426        // the same UID correctly.
9427        if (mPlatformPackage == pkg) {
9428            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9429                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9430        }
9431
9432        // If there's a mismatch between the abi-override in the package setting
9433        // and the abiOverride specified for the install. Warn about this because we
9434        // would've already compiled the app without taking the package setting into
9435        // account.
9436        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9437            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9438                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9439                        " for package " + pkg.packageName);
9440            }
9441        }
9442
9443        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9444        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9445        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9446
9447        // Copy the derived override back to the parsed package, so that we can
9448        // update the package settings accordingly.
9449        pkg.cpuAbiOverride = cpuAbiOverride;
9450
9451        if (DEBUG_ABI_SELECTION) {
9452            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9453                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9454                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9455        }
9456
9457        // Push the derived path down into PackageSettings so we know what to
9458        // clean up at uninstall time.
9459        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9460
9461        if (DEBUG_ABI_SELECTION) {
9462            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9463                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9464                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9465        }
9466
9467        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9468        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9469            // We don't do this here during boot because we can do it all
9470            // at once after scanning all existing packages.
9471            //
9472            // We also do this *before* we perform dexopt on this package, so that
9473            // we can avoid redundant dexopts, and also to make sure we've got the
9474            // code and package path correct.
9475            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9476        }
9477
9478        if (mFactoryTest && pkg.requestedPermissions.contains(
9479                android.Manifest.permission.FACTORY_TEST)) {
9480            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9481        }
9482
9483        if (isSystemApp(pkg)) {
9484            pkgSetting.isOrphaned = true;
9485        }
9486
9487        // Take care of first install / last update times.
9488        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9489        if (currentTime != 0) {
9490            if (pkgSetting.firstInstallTime == 0) {
9491                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9492            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9493                pkgSetting.lastUpdateTime = currentTime;
9494            }
9495        } else if (pkgSetting.firstInstallTime == 0) {
9496            // We need *something*.  Take time time stamp of the file.
9497            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9498        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9499            if (scanFileTime != pkgSetting.timeStamp) {
9500                // A package on the system image has changed; consider this
9501                // to be an update.
9502                pkgSetting.lastUpdateTime = scanFileTime;
9503            }
9504        }
9505        pkgSetting.setTimeStamp(scanFileTime);
9506
9507        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9508            if (nonMutatedPs != null) {
9509                synchronized (mPackages) {
9510                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9511                }
9512            }
9513        } else {
9514            final int userId = user == null ? 0 : user.getIdentifier();
9515            // Modify state for the given package setting
9516            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9517                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9518            if (pkgSetting.getInstantApp(userId)) {
9519                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9520            }
9521        }
9522        return pkg;
9523    }
9524
9525    /**
9526     * Applies policy to the parsed package based upon the given policy flags.
9527     * Ensures the package is in a good state.
9528     * <p>
9529     * Implementation detail: This method must NOT have any side effect. It would
9530     * ideally be static, but, it requires locks to read system state.
9531     */
9532    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9533        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9534            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9535            if (pkg.applicationInfo.isDirectBootAware()) {
9536                // we're direct boot aware; set for all components
9537                for (PackageParser.Service s : pkg.services) {
9538                    s.info.encryptionAware = s.info.directBootAware = true;
9539                }
9540                for (PackageParser.Provider p : pkg.providers) {
9541                    p.info.encryptionAware = p.info.directBootAware = true;
9542                }
9543                for (PackageParser.Activity a : pkg.activities) {
9544                    a.info.encryptionAware = a.info.directBootAware = true;
9545                }
9546                for (PackageParser.Activity r : pkg.receivers) {
9547                    r.info.encryptionAware = r.info.directBootAware = true;
9548                }
9549            }
9550        } else {
9551            // Only allow system apps to be flagged as core apps.
9552            pkg.coreApp = false;
9553            // clear flags not applicable to regular apps
9554            pkg.applicationInfo.privateFlags &=
9555                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
9556            pkg.applicationInfo.privateFlags &=
9557                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
9558        }
9559        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
9560
9561        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
9562            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9563        }
9564
9565        if (!isSystemApp(pkg)) {
9566            // Only system apps can use these features.
9567            pkg.mOriginalPackages = null;
9568            pkg.mRealPackage = null;
9569            pkg.mAdoptPermissions = null;
9570        }
9571    }
9572
9573    /**
9574     * Asserts the parsed package is valid according to the given policy. If the
9575     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
9576     * <p>
9577     * Implementation detail: This method must NOT have any side effects. It would
9578     * ideally be static, but, it requires locks to read system state.
9579     *
9580     * @throws PackageManagerException If the package fails any of the validation checks
9581     */
9582    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
9583            throws PackageManagerException {
9584        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
9585            assertCodePolicy(pkg);
9586        }
9587
9588        if (pkg.applicationInfo.getCodePath() == null ||
9589                pkg.applicationInfo.getResourcePath() == null) {
9590            // Bail out. The resource and code paths haven't been set.
9591            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9592                    "Code and resource paths haven't been set correctly");
9593        }
9594
9595        // Make sure we're not adding any bogus keyset info
9596        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9597        ksms.assertScannedPackageValid(pkg);
9598
9599        synchronized (mPackages) {
9600            // The special "android" package can only be defined once
9601            if (pkg.packageName.equals("android")) {
9602                if (mAndroidApplication != null) {
9603                    Slog.w(TAG, "*************************************************");
9604                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
9605                    Slog.w(TAG, " codePath=" + pkg.codePath);
9606                    Slog.w(TAG, "*************************************************");
9607                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9608                            "Core android package being redefined.  Skipping.");
9609                }
9610            }
9611
9612            // A package name must be unique; don't allow duplicates
9613            if (mPackages.containsKey(pkg.packageName)) {
9614                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9615                        "Application package " + pkg.packageName
9616                        + " already installed.  Skipping duplicate.");
9617            }
9618
9619            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9620                // Static libs have a synthetic package name containing the version
9621                // but we still want the base name to be unique.
9622                if (mPackages.containsKey(pkg.manifestPackageName)) {
9623                    throw new PackageManagerException(
9624                            "Duplicate static shared lib provider package");
9625                }
9626
9627                // Static shared libraries should have at least O target SDK
9628                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
9629                    throw new PackageManagerException(
9630                            "Packages declaring static-shared libs must target O SDK or higher");
9631                }
9632
9633                // Package declaring static a shared lib cannot be instant apps
9634                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
9635                    throw new PackageManagerException(
9636                            "Packages declaring static-shared libs cannot be instant apps");
9637                }
9638
9639                // Package declaring static a shared lib cannot be renamed since the package
9640                // name is synthetic and apps can't code around package manager internals.
9641                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
9642                    throw new PackageManagerException(
9643                            "Packages declaring static-shared libs cannot be renamed");
9644                }
9645
9646                // Package declaring static a shared lib cannot declare child packages
9647                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
9648                    throw new PackageManagerException(
9649                            "Packages declaring static-shared libs cannot have child packages");
9650                }
9651
9652                // Package declaring static a shared lib cannot declare dynamic libs
9653                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
9654                    throw new PackageManagerException(
9655                            "Packages declaring static-shared libs cannot declare dynamic libs");
9656                }
9657
9658                // Package declaring static a shared lib cannot declare shared users
9659                if (pkg.mSharedUserId != null) {
9660                    throw new PackageManagerException(
9661                            "Packages declaring static-shared libs cannot declare shared users");
9662                }
9663
9664                // Static shared libs cannot declare activities
9665                if (!pkg.activities.isEmpty()) {
9666                    throw new PackageManagerException(
9667                            "Static shared libs cannot declare activities");
9668                }
9669
9670                // Static shared libs cannot declare services
9671                if (!pkg.services.isEmpty()) {
9672                    throw new PackageManagerException(
9673                            "Static shared libs cannot declare services");
9674                }
9675
9676                // Static shared libs cannot declare providers
9677                if (!pkg.providers.isEmpty()) {
9678                    throw new PackageManagerException(
9679                            "Static shared libs cannot declare content providers");
9680                }
9681
9682                // Static shared libs cannot declare receivers
9683                if (!pkg.receivers.isEmpty()) {
9684                    throw new PackageManagerException(
9685                            "Static shared libs cannot declare broadcast receivers");
9686                }
9687
9688                // Static shared libs cannot declare permission groups
9689                if (!pkg.permissionGroups.isEmpty()) {
9690                    throw new PackageManagerException(
9691                            "Static shared libs cannot declare permission groups");
9692                }
9693
9694                // Static shared libs cannot declare permissions
9695                if (!pkg.permissions.isEmpty()) {
9696                    throw new PackageManagerException(
9697                            "Static shared libs cannot declare permissions");
9698                }
9699
9700                // Static shared libs cannot declare protected broadcasts
9701                if (pkg.protectedBroadcasts != null) {
9702                    throw new PackageManagerException(
9703                            "Static shared libs cannot declare protected broadcasts");
9704                }
9705
9706                // Static shared libs cannot be overlay targets
9707                if (pkg.mOverlayTarget != null) {
9708                    throw new PackageManagerException(
9709                            "Static shared libs cannot be overlay targets");
9710                }
9711
9712                // The version codes must be ordered as lib versions
9713                int minVersionCode = Integer.MIN_VALUE;
9714                int maxVersionCode = Integer.MAX_VALUE;
9715
9716                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9717                        pkg.staticSharedLibName);
9718                if (versionedLib != null) {
9719                    final int versionCount = versionedLib.size();
9720                    for (int i = 0; i < versionCount; i++) {
9721                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
9722                        // TODO: We will change version code to long, so in the new API it is long
9723                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
9724                                .getVersionCode();
9725                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
9726                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
9727                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
9728                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
9729                        } else {
9730                            minVersionCode = maxVersionCode = libVersionCode;
9731                            break;
9732                        }
9733                    }
9734                }
9735                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
9736                    throw new PackageManagerException("Static shared"
9737                            + " lib version codes must be ordered as lib versions");
9738                }
9739            }
9740
9741            // Only privileged apps and updated privileged apps can add child packages.
9742            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
9743                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
9744                    throw new PackageManagerException("Only privileged apps can add child "
9745                            + "packages. Ignoring package " + pkg.packageName);
9746                }
9747                final int childCount = pkg.childPackages.size();
9748                for (int i = 0; i < childCount; i++) {
9749                    PackageParser.Package childPkg = pkg.childPackages.get(i);
9750                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
9751                            childPkg.packageName)) {
9752                        throw new PackageManagerException("Can't override child of "
9753                                + "another disabled app. Ignoring package " + pkg.packageName);
9754                    }
9755                }
9756            }
9757
9758            // If we're only installing presumed-existing packages, require that the
9759            // scanned APK is both already known and at the path previously established
9760            // for it.  Previously unknown packages we pick up normally, but if we have an
9761            // a priori expectation about this package's install presence, enforce it.
9762            // With a singular exception for new system packages. When an OTA contains
9763            // a new system package, we allow the codepath to change from a system location
9764            // to the user-installed location. If we don't allow this change, any newer,
9765            // user-installed version of the application will be ignored.
9766            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
9767                if (mExpectingBetter.containsKey(pkg.packageName)) {
9768                    logCriticalInfo(Log.WARN,
9769                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
9770                } else {
9771                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
9772                    if (known != null) {
9773                        if (DEBUG_PACKAGE_SCANNING) {
9774                            Log.d(TAG, "Examining " + pkg.codePath
9775                                    + " and requiring known paths " + known.codePathString
9776                                    + " & " + known.resourcePathString);
9777                        }
9778                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
9779                                || !pkg.applicationInfo.getResourcePath().equals(
9780                                        known.resourcePathString)) {
9781                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
9782                                    "Application package " + pkg.packageName
9783                                    + " found at " + pkg.applicationInfo.getCodePath()
9784                                    + " but expected at " + known.codePathString
9785                                    + "; ignoring.");
9786                        }
9787                    }
9788                }
9789            }
9790
9791            // Verify that this new package doesn't have any content providers
9792            // that conflict with existing packages.  Only do this if the
9793            // package isn't already installed, since we don't want to break
9794            // things that are installed.
9795            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
9796                final int N = pkg.providers.size();
9797                int i;
9798                for (i=0; i<N; i++) {
9799                    PackageParser.Provider p = pkg.providers.get(i);
9800                    if (p.info.authority != null) {
9801                        String names[] = p.info.authority.split(";");
9802                        for (int j = 0; j < names.length; j++) {
9803                            if (mProvidersByAuthority.containsKey(names[j])) {
9804                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9805                                final String otherPackageName =
9806                                        ((other != null && other.getComponentName() != null) ?
9807                                                other.getComponentName().getPackageName() : "?");
9808                                throw new PackageManagerException(
9809                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
9810                                        "Can't install because provider name " + names[j]
9811                                                + " (in package " + pkg.applicationInfo.packageName
9812                                                + ") is already used by " + otherPackageName);
9813                            }
9814                        }
9815                    }
9816                }
9817            }
9818        }
9819    }
9820
9821    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
9822            int type, String declaringPackageName, int declaringVersionCode) {
9823        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9824        if (versionedLib == null) {
9825            versionedLib = new SparseArray<>();
9826            mSharedLibraries.put(name, versionedLib);
9827            if (type == SharedLibraryInfo.TYPE_STATIC) {
9828                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
9829            }
9830        } else if (versionedLib.indexOfKey(version) >= 0) {
9831            return false;
9832        }
9833        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
9834                version, type, declaringPackageName, declaringVersionCode);
9835        versionedLib.put(version, libEntry);
9836        return true;
9837    }
9838
9839    private boolean removeSharedLibraryLPw(String name, int version) {
9840        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9841        if (versionedLib == null) {
9842            return false;
9843        }
9844        final int libIdx = versionedLib.indexOfKey(version);
9845        if (libIdx < 0) {
9846            return false;
9847        }
9848        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
9849        versionedLib.remove(version);
9850        if (versionedLib.size() <= 0) {
9851            mSharedLibraries.remove(name);
9852            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
9853                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
9854                        .getPackageName());
9855            }
9856        }
9857        return true;
9858    }
9859
9860    /**
9861     * Adds a scanned package to the system. When this method is finished, the package will
9862     * be available for query, resolution, etc...
9863     */
9864    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
9865            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
9866        final String pkgName = pkg.packageName;
9867        if (mCustomResolverComponentName != null &&
9868                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
9869            setUpCustomResolverActivity(pkg);
9870        }
9871
9872        if (pkg.packageName.equals("android")) {
9873            synchronized (mPackages) {
9874                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9875                    // Set up information for our fall-back user intent resolution activity.
9876                    mPlatformPackage = pkg;
9877                    pkg.mVersionCode = mSdkVersion;
9878                    mAndroidApplication = pkg.applicationInfo;
9879                    if (!mResolverReplaced) {
9880                        mResolveActivity.applicationInfo = mAndroidApplication;
9881                        mResolveActivity.name = ResolverActivity.class.getName();
9882                        mResolveActivity.packageName = mAndroidApplication.packageName;
9883                        mResolveActivity.processName = "system:ui";
9884                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9885                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
9886                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
9887                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
9888                        mResolveActivity.exported = true;
9889                        mResolveActivity.enabled = true;
9890                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
9891                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
9892                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
9893                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
9894                                | ActivityInfo.CONFIG_ORIENTATION
9895                                | ActivityInfo.CONFIG_KEYBOARD
9896                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
9897                        mResolveInfo.activityInfo = mResolveActivity;
9898                        mResolveInfo.priority = 0;
9899                        mResolveInfo.preferredOrder = 0;
9900                        mResolveInfo.match = 0;
9901                        mResolveComponentName = new ComponentName(
9902                                mAndroidApplication.packageName, mResolveActivity.name);
9903                    }
9904                }
9905            }
9906        }
9907
9908        ArrayList<PackageParser.Package> clientLibPkgs = null;
9909        // writer
9910        synchronized (mPackages) {
9911            boolean hasStaticSharedLibs = false;
9912
9913            // Any app can add new static shared libraries
9914            if (pkg.staticSharedLibName != null) {
9915                // Static shared libs don't allow renaming as they have synthetic package
9916                // names to allow install of multiple versions, so use name from manifest.
9917                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
9918                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
9919                        pkg.manifestPackageName, pkg.mVersionCode)) {
9920                    hasStaticSharedLibs = true;
9921                } else {
9922                    Slog.w(TAG, "Package " + pkg.packageName + " library "
9923                                + pkg.staticSharedLibName + " already exists; skipping");
9924                }
9925                // Static shared libs cannot be updated once installed since they
9926                // use synthetic package name which includes the version code, so
9927                // not need to update other packages's shared lib dependencies.
9928            }
9929
9930            if (!hasStaticSharedLibs
9931                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9932                // Only system apps can add new dynamic shared libraries.
9933                if (pkg.libraryNames != null) {
9934                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
9935                        String name = pkg.libraryNames.get(i);
9936                        boolean allowed = false;
9937                        if (pkg.isUpdatedSystemApp()) {
9938                            // New library entries can only be added through the
9939                            // system image.  This is important to get rid of a lot
9940                            // of nasty edge cases: for example if we allowed a non-
9941                            // system update of the app to add a library, then uninstalling
9942                            // the update would make the library go away, and assumptions
9943                            // we made such as through app install filtering would now
9944                            // have allowed apps on the device which aren't compatible
9945                            // with it.  Better to just have the restriction here, be
9946                            // conservative, and create many fewer cases that can negatively
9947                            // impact the user experience.
9948                            final PackageSetting sysPs = mSettings
9949                                    .getDisabledSystemPkgLPr(pkg.packageName);
9950                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
9951                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
9952                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
9953                                        allowed = true;
9954                                        break;
9955                                    }
9956                                }
9957                            }
9958                        } else {
9959                            allowed = true;
9960                        }
9961                        if (allowed) {
9962                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
9963                                    SharedLibraryInfo.VERSION_UNDEFINED,
9964                                    SharedLibraryInfo.TYPE_DYNAMIC,
9965                                    pkg.packageName, pkg.mVersionCode)) {
9966                                Slog.w(TAG, "Package " + pkg.packageName + " library "
9967                                        + name + " already exists; skipping");
9968                            }
9969                        } else {
9970                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
9971                                    + name + " that is not declared on system image; skipping");
9972                        }
9973                    }
9974
9975                    if ((scanFlags & SCAN_BOOTING) == 0) {
9976                        // If we are not booting, we need to update any applications
9977                        // that are clients of our shared library.  If we are booting,
9978                        // this will all be done once the scan is complete.
9979                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
9980                    }
9981                }
9982            }
9983        }
9984
9985        if ((scanFlags & SCAN_BOOTING) != 0) {
9986            // No apps can run during boot scan, so they don't need to be frozen
9987        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
9988            // Caller asked to not kill app, so it's probably not frozen
9989        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
9990            // Caller asked us to ignore frozen check for some reason; they
9991            // probably didn't know the package name
9992        } else {
9993            // We're doing major surgery on this package, so it better be frozen
9994            // right now to keep it from launching
9995            checkPackageFrozen(pkgName);
9996        }
9997
9998        // Also need to kill any apps that are dependent on the library.
9999        if (clientLibPkgs != null) {
10000            for (int i=0; i<clientLibPkgs.size(); i++) {
10001                PackageParser.Package clientPkg = clientLibPkgs.get(i);
10002                killApplication(clientPkg.applicationInfo.packageName,
10003                        clientPkg.applicationInfo.uid, "update lib");
10004            }
10005        }
10006
10007        // writer
10008        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
10009
10010        synchronized (mPackages) {
10011            // We don't expect installation to fail beyond this point
10012
10013            // Add the new setting to mSettings
10014            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
10015            // Add the new setting to mPackages
10016            mPackages.put(pkg.applicationInfo.packageName, pkg);
10017            // Make sure we don't accidentally delete its data.
10018            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
10019            while (iter.hasNext()) {
10020                PackageCleanItem item = iter.next();
10021                if (pkgName.equals(item.packageName)) {
10022                    iter.remove();
10023                }
10024            }
10025
10026            // Add the package's KeySets to the global KeySetManagerService
10027            KeySetManagerService ksms = mSettings.mKeySetManagerService;
10028            ksms.addScannedPackageLPw(pkg);
10029
10030            int N = pkg.providers.size();
10031            StringBuilder r = null;
10032            int i;
10033            for (i=0; i<N; i++) {
10034                PackageParser.Provider p = pkg.providers.get(i);
10035                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
10036                        p.info.processName);
10037                mProviders.addProvider(p);
10038                p.syncable = p.info.isSyncable;
10039                if (p.info.authority != null) {
10040                    String names[] = p.info.authority.split(";");
10041                    p.info.authority = null;
10042                    for (int j = 0; j < names.length; j++) {
10043                        if (j == 1 && p.syncable) {
10044                            // We only want the first authority for a provider to possibly be
10045                            // syncable, so if we already added this provider using a different
10046                            // authority clear the syncable flag. We copy the provider before
10047                            // changing it because the mProviders object contains a reference
10048                            // to a provider that we don't want to change.
10049                            // Only do this for the second authority since the resulting provider
10050                            // object can be the same for all future authorities for this provider.
10051                            p = new PackageParser.Provider(p);
10052                            p.syncable = false;
10053                        }
10054                        if (!mProvidersByAuthority.containsKey(names[j])) {
10055                            mProvidersByAuthority.put(names[j], p);
10056                            if (p.info.authority == null) {
10057                                p.info.authority = names[j];
10058                            } else {
10059                                p.info.authority = p.info.authority + ";" + names[j];
10060                            }
10061                            if (DEBUG_PACKAGE_SCANNING) {
10062                                if (chatty)
10063                                    Log.d(TAG, "Registered content provider: " + names[j]
10064                                            + ", className = " + p.info.name + ", isSyncable = "
10065                                            + p.info.isSyncable);
10066                            }
10067                        } else {
10068                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10069                            Slog.w(TAG, "Skipping provider name " + names[j] +
10070                                    " (in package " + pkg.applicationInfo.packageName +
10071                                    "): name already used by "
10072                                    + ((other != null && other.getComponentName() != null)
10073                                            ? other.getComponentName().getPackageName() : "?"));
10074                        }
10075                    }
10076                }
10077                if (chatty) {
10078                    if (r == null) {
10079                        r = new StringBuilder(256);
10080                    } else {
10081                        r.append(' ');
10082                    }
10083                    r.append(p.info.name);
10084                }
10085            }
10086            if (r != null) {
10087                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
10088            }
10089
10090            N = pkg.services.size();
10091            r = null;
10092            for (i=0; i<N; i++) {
10093                PackageParser.Service s = pkg.services.get(i);
10094                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
10095                        s.info.processName);
10096                mServices.addService(s);
10097                if (chatty) {
10098                    if (r == null) {
10099                        r = new StringBuilder(256);
10100                    } else {
10101                        r.append(' ');
10102                    }
10103                    r.append(s.info.name);
10104                }
10105            }
10106            if (r != null) {
10107                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
10108            }
10109
10110            N = pkg.receivers.size();
10111            r = null;
10112            for (i=0; i<N; i++) {
10113                PackageParser.Activity a = pkg.receivers.get(i);
10114                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10115                        a.info.processName);
10116                mReceivers.addActivity(a, "receiver");
10117                if (chatty) {
10118                    if (r == null) {
10119                        r = new StringBuilder(256);
10120                    } else {
10121                        r.append(' ');
10122                    }
10123                    r.append(a.info.name);
10124                }
10125            }
10126            if (r != null) {
10127                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
10128            }
10129
10130            N = pkg.activities.size();
10131            r = null;
10132            for (i=0; i<N; i++) {
10133                PackageParser.Activity a = pkg.activities.get(i);
10134                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
10135                        a.info.processName);
10136                mActivities.addActivity(a, "activity");
10137                if (chatty) {
10138                    if (r == null) {
10139                        r = new StringBuilder(256);
10140                    } else {
10141                        r.append(' ');
10142                    }
10143                    r.append(a.info.name);
10144                }
10145            }
10146            if (r != null) {
10147                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
10148            }
10149
10150            N = pkg.permissionGroups.size();
10151            r = null;
10152            for (i=0; i<N; i++) {
10153                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10154                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10155                final String curPackageName = cur == null ? null : cur.info.packageName;
10156                // Dont allow ephemeral apps to define new permission groups.
10157                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10158                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10159                            + pg.info.packageName
10160                            + " ignored: instant apps cannot define new permission groups.");
10161                    continue;
10162                }
10163                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10164                if (cur == null || isPackageUpdate) {
10165                    mPermissionGroups.put(pg.info.name, pg);
10166                    if (chatty) {
10167                        if (r == null) {
10168                            r = new StringBuilder(256);
10169                        } else {
10170                            r.append(' ');
10171                        }
10172                        if (isPackageUpdate) {
10173                            r.append("UPD:");
10174                        }
10175                        r.append(pg.info.name);
10176                    }
10177                } else {
10178                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10179                            + pg.info.packageName + " ignored: original from "
10180                            + cur.info.packageName);
10181                    if (chatty) {
10182                        if (r == null) {
10183                            r = new StringBuilder(256);
10184                        } else {
10185                            r.append(' ');
10186                        }
10187                        r.append("DUP:");
10188                        r.append(pg.info.name);
10189                    }
10190                }
10191            }
10192            if (r != null) {
10193                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10194            }
10195
10196            N = pkg.permissions.size();
10197            r = null;
10198            for (i=0; i<N; i++) {
10199                PackageParser.Permission p = pkg.permissions.get(i);
10200
10201                // Dont allow ephemeral apps to define new permissions.
10202                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10203                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10204                            + p.info.packageName
10205                            + " ignored: instant apps cannot define new permissions.");
10206                    continue;
10207                }
10208
10209                // Assume by default that we did not install this permission into the system.
10210                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10211
10212                // Now that permission groups have a special meaning, we ignore permission
10213                // groups for legacy apps to prevent unexpected behavior. In particular,
10214                // permissions for one app being granted to someone just becase they happen
10215                // to be in a group defined by another app (before this had no implications).
10216                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10217                    p.group = mPermissionGroups.get(p.info.group);
10218                    // Warn for a permission in an unknown group.
10219                    if (p.info.group != null && p.group == null) {
10220                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10221                                + p.info.packageName + " in an unknown group " + p.info.group);
10222                    }
10223                }
10224
10225                ArrayMap<String, BasePermission> permissionMap =
10226                        p.tree ? mSettings.mPermissionTrees
10227                                : mSettings.mPermissions;
10228                BasePermission bp = permissionMap.get(p.info.name);
10229
10230                // Allow system apps to redefine non-system permissions
10231                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10232                    final boolean currentOwnerIsSystem = (bp.perm != null
10233                            && isSystemApp(bp.perm.owner));
10234                    if (isSystemApp(p.owner)) {
10235                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10236                            // It's a built-in permission and no owner, take ownership now
10237                            bp.packageSetting = pkgSetting;
10238                            bp.perm = p;
10239                            bp.uid = pkg.applicationInfo.uid;
10240                            bp.sourcePackage = p.info.packageName;
10241                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10242                        } else if (!currentOwnerIsSystem) {
10243                            String msg = "New decl " + p.owner + " of permission  "
10244                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10245                            reportSettingsProblem(Log.WARN, msg);
10246                            bp = null;
10247                        }
10248                    }
10249                }
10250
10251                if (bp == null) {
10252                    bp = new BasePermission(p.info.name, p.info.packageName,
10253                            BasePermission.TYPE_NORMAL);
10254                    permissionMap.put(p.info.name, bp);
10255                }
10256
10257                if (bp.perm == null) {
10258                    if (bp.sourcePackage == null
10259                            || bp.sourcePackage.equals(p.info.packageName)) {
10260                        BasePermission tree = findPermissionTreeLP(p.info.name);
10261                        if (tree == null
10262                                || tree.sourcePackage.equals(p.info.packageName)) {
10263                            bp.packageSetting = pkgSetting;
10264                            bp.perm = p;
10265                            bp.uid = pkg.applicationInfo.uid;
10266                            bp.sourcePackage = p.info.packageName;
10267                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10268                            if (chatty) {
10269                                if (r == null) {
10270                                    r = new StringBuilder(256);
10271                                } else {
10272                                    r.append(' ');
10273                                }
10274                                r.append(p.info.name);
10275                            }
10276                        } else {
10277                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10278                                    + p.info.packageName + " ignored: base tree "
10279                                    + tree.name + " is from package "
10280                                    + tree.sourcePackage);
10281                        }
10282                    } else {
10283                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10284                                + p.info.packageName + " ignored: original from "
10285                                + bp.sourcePackage);
10286                    }
10287                } else if (chatty) {
10288                    if (r == null) {
10289                        r = new StringBuilder(256);
10290                    } else {
10291                        r.append(' ');
10292                    }
10293                    r.append("DUP:");
10294                    r.append(p.info.name);
10295                }
10296                if (bp.perm == p) {
10297                    bp.protectionLevel = p.info.protectionLevel;
10298                }
10299            }
10300
10301            if (r != null) {
10302                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10303            }
10304
10305            N = pkg.instrumentation.size();
10306            r = null;
10307            for (i=0; i<N; i++) {
10308                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10309                a.info.packageName = pkg.applicationInfo.packageName;
10310                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10311                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10312                a.info.splitNames = pkg.splitNames;
10313                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10314                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10315                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10316                a.info.dataDir = pkg.applicationInfo.dataDir;
10317                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10318                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10319                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10320                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10321                mInstrumentation.put(a.getComponentName(), a);
10322                if (chatty) {
10323                    if (r == null) {
10324                        r = new StringBuilder(256);
10325                    } else {
10326                        r.append(' ');
10327                    }
10328                    r.append(a.info.name);
10329                }
10330            }
10331            if (r != null) {
10332                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10333            }
10334
10335            if (pkg.protectedBroadcasts != null) {
10336                N = pkg.protectedBroadcasts.size();
10337                for (i=0; i<N; i++) {
10338                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10339                }
10340            }
10341        }
10342
10343        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10344    }
10345
10346    /**
10347     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10348     * is derived purely on the basis of the contents of {@code scanFile} and
10349     * {@code cpuAbiOverride}.
10350     *
10351     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10352     */
10353    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10354                                 String cpuAbiOverride, boolean extractLibs,
10355                                 File appLib32InstallDir)
10356            throws PackageManagerException {
10357        // Give ourselves some initial paths; we'll come back for another
10358        // pass once we've determined ABI below.
10359        setNativeLibraryPaths(pkg, appLib32InstallDir);
10360
10361        // We would never need to extract libs for forward-locked and external packages,
10362        // since the container service will do it for us. We shouldn't attempt to
10363        // extract libs from system app when it was not updated.
10364        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10365                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10366            extractLibs = false;
10367        }
10368
10369        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10370        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10371
10372        NativeLibraryHelper.Handle handle = null;
10373        try {
10374            handle = NativeLibraryHelper.Handle.create(pkg);
10375            // TODO(multiArch): This can be null for apps that didn't go through the
10376            // usual installation process. We can calculate it again, like we
10377            // do during install time.
10378            //
10379            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10380            // unnecessary.
10381            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10382
10383            // Null out the abis so that they can be recalculated.
10384            pkg.applicationInfo.primaryCpuAbi = null;
10385            pkg.applicationInfo.secondaryCpuAbi = null;
10386            if (isMultiArch(pkg.applicationInfo)) {
10387                // Warn if we've set an abiOverride for multi-lib packages..
10388                // By definition, we need to copy both 32 and 64 bit libraries for
10389                // such packages.
10390                if (pkg.cpuAbiOverride != null
10391                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10392                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10393                }
10394
10395                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10396                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10397                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10398                    if (extractLibs) {
10399                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10400                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10401                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10402                                useIsaSpecificSubdirs);
10403                    } else {
10404                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10405                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10406                    }
10407                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10408                }
10409
10410                maybeThrowExceptionForMultiArchCopy(
10411                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10412
10413                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10414                    if (extractLibs) {
10415                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10416                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10417                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10418                                useIsaSpecificSubdirs);
10419                    } else {
10420                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10421                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10422                    }
10423                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10424                }
10425
10426                maybeThrowExceptionForMultiArchCopy(
10427                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10428
10429                if (abi64 >= 0) {
10430                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10431                }
10432
10433                if (abi32 >= 0) {
10434                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10435                    if (abi64 >= 0) {
10436                        if (pkg.use32bitAbi) {
10437                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10438                            pkg.applicationInfo.primaryCpuAbi = abi;
10439                        } else {
10440                            pkg.applicationInfo.secondaryCpuAbi = abi;
10441                        }
10442                    } else {
10443                        pkg.applicationInfo.primaryCpuAbi = abi;
10444                    }
10445                }
10446
10447            } else {
10448                String[] abiList = (cpuAbiOverride != null) ?
10449                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10450
10451                // Enable gross and lame hacks for apps that are built with old
10452                // SDK tools. We must scan their APKs for renderscript bitcode and
10453                // not launch them if it's present. Don't bother checking on devices
10454                // that don't have 64 bit support.
10455                boolean needsRenderScriptOverride = false;
10456                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10457                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10458                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10459                    needsRenderScriptOverride = true;
10460                }
10461
10462                final int copyRet;
10463                if (extractLibs) {
10464                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10465                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10466                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10467                } else {
10468                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10469                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10470                }
10471                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10472
10473                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10474                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10475                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10476                }
10477
10478                if (copyRet >= 0) {
10479                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10480                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10481                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10482                } else if (needsRenderScriptOverride) {
10483                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10484                }
10485            }
10486        } catch (IOException ioe) {
10487            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10488        } finally {
10489            IoUtils.closeQuietly(handle);
10490        }
10491
10492        // Now that we've calculated the ABIs and determined if it's an internal app,
10493        // we will go ahead and populate the nativeLibraryPath.
10494        setNativeLibraryPaths(pkg, appLib32InstallDir);
10495    }
10496
10497    /**
10498     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10499     * i.e, so that all packages can be run inside a single process if required.
10500     *
10501     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10502     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10503     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10504     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10505     * updating a package that belongs to a shared user.
10506     *
10507     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10508     * adds unnecessary complexity.
10509     */
10510    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10511            PackageParser.Package scannedPackage) {
10512        String requiredInstructionSet = null;
10513        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10514            requiredInstructionSet = VMRuntime.getInstructionSet(
10515                     scannedPackage.applicationInfo.primaryCpuAbi);
10516        }
10517
10518        PackageSetting requirer = null;
10519        for (PackageSetting ps : packagesForUser) {
10520            // If packagesForUser contains scannedPackage, we skip it. This will happen
10521            // when scannedPackage is an update of an existing package. Without this check,
10522            // we will never be able to change the ABI of any package belonging to a shared
10523            // user, even if it's compatible with other packages.
10524            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10525                if (ps.primaryCpuAbiString == null) {
10526                    continue;
10527                }
10528
10529                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10530                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10531                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10532                    // this but there's not much we can do.
10533                    String errorMessage = "Instruction set mismatch, "
10534                            + ((requirer == null) ? "[caller]" : requirer)
10535                            + " requires " + requiredInstructionSet + " whereas " + ps
10536                            + " requires " + instructionSet;
10537                    Slog.w(TAG, errorMessage);
10538                }
10539
10540                if (requiredInstructionSet == null) {
10541                    requiredInstructionSet = instructionSet;
10542                    requirer = ps;
10543                }
10544            }
10545        }
10546
10547        if (requiredInstructionSet != null) {
10548            String adjustedAbi;
10549            if (requirer != null) {
10550                // requirer != null implies that either scannedPackage was null or that scannedPackage
10551                // did not require an ABI, in which case we have to adjust scannedPackage to match
10552                // the ABI of the set (which is the same as requirer's ABI)
10553                adjustedAbi = requirer.primaryCpuAbiString;
10554                if (scannedPackage != null) {
10555                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10556                }
10557            } else {
10558                // requirer == null implies that we're updating all ABIs in the set to
10559                // match scannedPackage.
10560                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10561            }
10562
10563            for (PackageSetting ps : packagesForUser) {
10564                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10565                    if (ps.primaryCpuAbiString != null) {
10566                        continue;
10567                    }
10568
10569                    ps.primaryCpuAbiString = adjustedAbi;
10570                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
10571                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
10572                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
10573                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
10574                                + " (requirer="
10575                                + (requirer != null ? requirer.pkg : "null")
10576                                + ", scannedPackage="
10577                                + (scannedPackage != null ? scannedPackage : "null")
10578                                + ")");
10579                        try {
10580                            mInstaller.rmdex(ps.codePathString,
10581                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
10582                        } catch (InstallerException ignored) {
10583                        }
10584                    }
10585                }
10586            }
10587        }
10588    }
10589
10590    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
10591        synchronized (mPackages) {
10592            mResolverReplaced = true;
10593            // Set up information for custom user intent resolution activity.
10594            mResolveActivity.applicationInfo = pkg.applicationInfo;
10595            mResolveActivity.name = mCustomResolverComponentName.getClassName();
10596            mResolveActivity.packageName = pkg.applicationInfo.packageName;
10597            mResolveActivity.processName = pkg.applicationInfo.packageName;
10598            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10599            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
10600                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10601            mResolveActivity.theme = 0;
10602            mResolveActivity.exported = true;
10603            mResolveActivity.enabled = true;
10604            mResolveInfo.activityInfo = mResolveActivity;
10605            mResolveInfo.priority = 0;
10606            mResolveInfo.preferredOrder = 0;
10607            mResolveInfo.match = 0;
10608            mResolveComponentName = mCustomResolverComponentName;
10609            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
10610                    mResolveComponentName);
10611        }
10612    }
10613
10614    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
10615        if (installerActivity == null) {
10616            if (DEBUG_EPHEMERAL) {
10617                Slog.d(TAG, "Clear ephemeral installer activity");
10618            }
10619            mInstantAppInstallerActivity = null;
10620            return;
10621        }
10622
10623        if (DEBUG_EPHEMERAL) {
10624            Slog.d(TAG, "Set ephemeral installer activity: "
10625                    + installerActivity.getComponentName());
10626        }
10627        // Set up information for ephemeral installer activity
10628        mInstantAppInstallerActivity = installerActivity;
10629        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
10630                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10631        mInstantAppInstallerActivity.exported = true;
10632        mInstantAppInstallerActivity.enabled = true;
10633        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
10634        mInstantAppInstallerInfo.priority = 0;
10635        mInstantAppInstallerInfo.preferredOrder = 1;
10636        mInstantAppInstallerInfo.isDefault = true;
10637        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
10638                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
10639    }
10640
10641    private static String calculateBundledApkRoot(final String codePathString) {
10642        final File codePath = new File(codePathString);
10643        final File codeRoot;
10644        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
10645            codeRoot = Environment.getRootDirectory();
10646        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
10647            codeRoot = Environment.getOemDirectory();
10648        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
10649            codeRoot = Environment.getVendorDirectory();
10650        } else {
10651            // Unrecognized code path; take its top real segment as the apk root:
10652            // e.g. /something/app/blah.apk => /something
10653            try {
10654                File f = codePath.getCanonicalFile();
10655                File parent = f.getParentFile();    // non-null because codePath is a file
10656                File tmp;
10657                while ((tmp = parent.getParentFile()) != null) {
10658                    f = parent;
10659                    parent = tmp;
10660                }
10661                codeRoot = f;
10662                Slog.w(TAG, "Unrecognized code path "
10663                        + codePath + " - using " + codeRoot);
10664            } catch (IOException e) {
10665                // Can't canonicalize the code path -- shenanigans?
10666                Slog.w(TAG, "Can't canonicalize code path " + codePath);
10667                return Environment.getRootDirectory().getPath();
10668            }
10669        }
10670        return codeRoot.getPath();
10671    }
10672
10673    /**
10674     * Derive and set the location of native libraries for the given package,
10675     * which varies depending on where and how the package was installed.
10676     */
10677    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
10678        final ApplicationInfo info = pkg.applicationInfo;
10679        final String codePath = pkg.codePath;
10680        final File codeFile = new File(codePath);
10681        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
10682        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
10683
10684        info.nativeLibraryRootDir = null;
10685        info.nativeLibraryRootRequiresIsa = false;
10686        info.nativeLibraryDir = null;
10687        info.secondaryNativeLibraryDir = null;
10688
10689        if (isApkFile(codeFile)) {
10690            // Monolithic install
10691            if (bundledApp) {
10692                // If "/system/lib64/apkname" exists, assume that is the per-package
10693                // native library directory to use; otherwise use "/system/lib/apkname".
10694                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
10695                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
10696                        getPrimaryInstructionSet(info));
10697
10698                // This is a bundled system app so choose the path based on the ABI.
10699                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
10700                // is just the default path.
10701                final String apkName = deriveCodePathName(codePath);
10702                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
10703                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
10704                        apkName).getAbsolutePath();
10705
10706                if (info.secondaryCpuAbi != null) {
10707                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
10708                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
10709                            secondaryLibDir, apkName).getAbsolutePath();
10710                }
10711            } else if (asecApp) {
10712                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
10713                        .getAbsolutePath();
10714            } else {
10715                final String apkName = deriveCodePathName(codePath);
10716                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
10717                        .getAbsolutePath();
10718            }
10719
10720            info.nativeLibraryRootRequiresIsa = false;
10721            info.nativeLibraryDir = info.nativeLibraryRootDir;
10722        } else {
10723            // Cluster install
10724            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10725            info.nativeLibraryRootRequiresIsa = true;
10726
10727            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10728                    getPrimaryInstructionSet(info)).getAbsolutePath();
10729
10730            if (info.secondaryCpuAbi != null) {
10731                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10732                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10733            }
10734        }
10735    }
10736
10737    /**
10738     * Calculate the abis and roots for a bundled app. These can uniquely
10739     * be determined from the contents of the system partition, i.e whether
10740     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10741     * of this information, and instead assume that the system was built
10742     * sensibly.
10743     */
10744    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10745                                           PackageSetting pkgSetting) {
10746        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10747
10748        // If "/system/lib64/apkname" exists, assume that is the per-package
10749        // native library directory to use; otherwise use "/system/lib/apkname".
10750        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10751        setBundledAppAbi(pkg, apkRoot, apkName);
10752        // pkgSetting might be null during rescan following uninstall of updates
10753        // to a bundled app, so accommodate that possibility.  The settings in
10754        // that case will be established later from the parsed package.
10755        //
10756        // If the settings aren't null, sync them up with what we've just derived.
10757        // note that apkRoot isn't stored in the package settings.
10758        if (pkgSetting != null) {
10759            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10760            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10761        }
10762    }
10763
10764    /**
10765     * Deduces the ABI of a bundled app and sets the relevant fields on the
10766     * parsed pkg object.
10767     *
10768     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
10769     *        under which system libraries are installed.
10770     * @param apkName the name of the installed package.
10771     */
10772    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
10773        final File codeFile = new File(pkg.codePath);
10774
10775        final boolean has64BitLibs;
10776        final boolean has32BitLibs;
10777        if (isApkFile(codeFile)) {
10778            // Monolithic install
10779            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
10780            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
10781        } else {
10782            // Cluster install
10783            final File rootDir = new File(codeFile, LIB_DIR_NAME);
10784            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
10785                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
10786                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
10787                has64BitLibs = (new File(rootDir, isa)).exists();
10788            } else {
10789                has64BitLibs = false;
10790            }
10791            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
10792                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
10793                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
10794                has32BitLibs = (new File(rootDir, isa)).exists();
10795            } else {
10796                has32BitLibs = false;
10797            }
10798        }
10799
10800        if (has64BitLibs && !has32BitLibs) {
10801            // The package has 64 bit libs, but not 32 bit libs. Its primary
10802            // ABI should be 64 bit. We can safely assume here that the bundled
10803            // native libraries correspond to the most preferred ABI in the list.
10804
10805            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10806            pkg.applicationInfo.secondaryCpuAbi = null;
10807        } else if (has32BitLibs && !has64BitLibs) {
10808            // The package has 32 bit libs but not 64 bit libs. Its primary
10809            // ABI should be 32 bit.
10810
10811            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10812            pkg.applicationInfo.secondaryCpuAbi = null;
10813        } else if (has32BitLibs && has64BitLibs) {
10814            // The application has both 64 and 32 bit bundled libraries. We check
10815            // here that the app declares multiArch support, and warn if it doesn't.
10816            //
10817            // We will be lenient here and record both ABIs. The primary will be the
10818            // ABI that's higher on the list, i.e, a device that's configured to prefer
10819            // 64 bit apps will see a 64 bit primary ABI,
10820
10821            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
10822                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
10823            }
10824
10825            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
10826                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10827                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10828            } else {
10829                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10830                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10831            }
10832        } else {
10833            pkg.applicationInfo.primaryCpuAbi = null;
10834            pkg.applicationInfo.secondaryCpuAbi = null;
10835        }
10836    }
10837
10838    private void killApplication(String pkgName, int appId, String reason) {
10839        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
10840    }
10841
10842    private void killApplication(String pkgName, int appId, int userId, String reason) {
10843        // Request the ActivityManager to kill the process(only for existing packages)
10844        // so that we do not end up in a confused state while the user is still using the older
10845        // version of the application while the new one gets installed.
10846        final long token = Binder.clearCallingIdentity();
10847        try {
10848            IActivityManager am = ActivityManager.getService();
10849            if (am != null) {
10850                try {
10851                    am.killApplication(pkgName, appId, userId, reason);
10852                } catch (RemoteException e) {
10853                }
10854            }
10855        } finally {
10856            Binder.restoreCallingIdentity(token);
10857        }
10858    }
10859
10860    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10861        // Remove the parent package setting
10862        PackageSetting ps = (PackageSetting) pkg.mExtras;
10863        if (ps != null) {
10864            removePackageLI(ps, chatty);
10865        }
10866        // Remove the child package setting
10867        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10868        for (int i = 0; i < childCount; i++) {
10869            PackageParser.Package childPkg = pkg.childPackages.get(i);
10870            ps = (PackageSetting) childPkg.mExtras;
10871            if (ps != null) {
10872                removePackageLI(ps, chatty);
10873            }
10874        }
10875    }
10876
10877    void removePackageLI(PackageSetting ps, boolean chatty) {
10878        if (DEBUG_INSTALL) {
10879            if (chatty)
10880                Log.d(TAG, "Removing package " + ps.name);
10881        }
10882
10883        // writer
10884        synchronized (mPackages) {
10885            mPackages.remove(ps.name);
10886            final PackageParser.Package pkg = ps.pkg;
10887            if (pkg != null) {
10888                cleanPackageDataStructuresLILPw(pkg, chatty);
10889            }
10890        }
10891    }
10892
10893    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
10894        if (DEBUG_INSTALL) {
10895            if (chatty)
10896                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
10897        }
10898
10899        // writer
10900        synchronized (mPackages) {
10901            // Remove the parent package
10902            mPackages.remove(pkg.applicationInfo.packageName);
10903            cleanPackageDataStructuresLILPw(pkg, chatty);
10904
10905            // Remove the child packages
10906            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10907            for (int i = 0; i < childCount; i++) {
10908                PackageParser.Package childPkg = pkg.childPackages.get(i);
10909                mPackages.remove(childPkg.applicationInfo.packageName);
10910                cleanPackageDataStructuresLILPw(childPkg, chatty);
10911            }
10912        }
10913    }
10914
10915    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
10916        int N = pkg.providers.size();
10917        StringBuilder r = null;
10918        int i;
10919        for (i=0; i<N; i++) {
10920            PackageParser.Provider p = pkg.providers.get(i);
10921            mProviders.removeProvider(p);
10922            if (p.info.authority == null) {
10923
10924                /* There was another ContentProvider with this authority when
10925                 * this app was installed so this authority is null,
10926                 * Ignore it as we don't have to unregister the provider.
10927                 */
10928                continue;
10929            }
10930            String names[] = p.info.authority.split(";");
10931            for (int j = 0; j < names.length; j++) {
10932                if (mProvidersByAuthority.get(names[j]) == p) {
10933                    mProvidersByAuthority.remove(names[j]);
10934                    if (DEBUG_REMOVE) {
10935                        if (chatty)
10936                            Log.d(TAG, "Unregistered content provider: " + names[j]
10937                                    + ", className = " + p.info.name + ", isSyncable = "
10938                                    + p.info.isSyncable);
10939                    }
10940                }
10941            }
10942            if (DEBUG_REMOVE && chatty) {
10943                if (r == null) {
10944                    r = new StringBuilder(256);
10945                } else {
10946                    r.append(' ');
10947                }
10948                r.append(p.info.name);
10949            }
10950        }
10951        if (r != null) {
10952            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
10953        }
10954
10955        N = pkg.services.size();
10956        r = null;
10957        for (i=0; i<N; i++) {
10958            PackageParser.Service s = pkg.services.get(i);
10959            mServices.removeService(s);
10960            if (chatty) {
10961                if (r == null) {
10962                    r = new StringBuilder(256);
10963                } else {
10964                    r.append(' ');
10965                }
10966                r.append(s.info.name);
10967            }
10968        }
10969        if (r != null) {
10970            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
10971        }
10972
10973        N = pkg.receivers.size();
10974        r = null;
10975        for (i=0; i<N; i++) {
10976            PackageParser.Activity a = pkg.receivers.get(i);
10977            mReceivers.removeActivity(a, "receiver");
10978            if (DEBUG_REMOVE && chatty) {
10979                if (r == null) {
10980                    r = new StringBuilder(256);
10981                } else {
10982                    r.append(' ');
10983                }
10984                r.append(a.info.name);
10985            }
10986        }
10987        if (r != null) {
10988            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
10989        }
10990
10991        N = pkg.activities.size();
10992        r = null;
10993        for (i=0; i<N; i++) {
10994            PackageParser.Activity a = pkg.activities.get(i);
10995            mActivities.removeActivity(a, "activity");
10996            if (DEBUG_REMOVE && chatty) {
10997                if (r == null) {
10998                    r = new StringBuilder(256);
10999                } else {
11000                    r.append(' ');
11001                }
11002                r.append(a.info.name);
11003            }
11004        }
11005        if (r != null) {
11006            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
11007        }
11008
11009        N = pkg.permissions.size();
11010        r = null;
11011        for (i=0; i<N; i++) {
11012            PackageParser.Permission p = pkg.permissions.get(i);
11013            BasePermission bp = mSettings.mPermissions.get(p.info.name);
11014            if (bp == null) {
11015                bp = mSettings.mPermissionTrees.get(p.info.name);
11016            }
11017            if (bp != null && bp.perm == p) {
11018                bp.perm = null;
11019                if (DEBUG_REMOVE && chatty) {
11020                    if (r == null) {
11021                        r = new StringBuilder(256);
11022                    } else {
11023                        r.append(' ');
11024                    }
11025                    r.append(p.info.name);
11026                }
11027            }
11028            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11029                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
11030                if (appOpPkgs != null) {
11031                    appOpPkgs.remove(pkg.packageName);
11032                }
11033            }
11034        }
11035        if (r != null) {
11036            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11037        }
11038
11039        N = pkg.requestedPermissions.size();
11040        r = null;
11041        for (i=0; i<N; i++) {
11042            String perm = pkg.requestedPermissions.get(i);
11043            BasePermission bp = mSettings.mPermissions.get(perm);
11044            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11045                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
11046                if (appOpPkgs != null) {
11047                    appOpPkgs.remove(pkg.packageName);
11048                    if (appOpPkgs.isEmpty()) {
11049                        mAppOpPermissionPackages.remove(perm);
11050                    }
11051                }
11052            }
11053        }
11054        if (r != null) {
11055            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11056        }
11057
11058        N = pkg.instrumentation.size();
11059        r = null;
11060        for (i=0; i<N; i++) {
11061            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11062            mInstrumentation.remove(a.getComponentName());
11063            if (DEBUG_REMOVE && chatty) {
11064                if (r == null) {
11065                    r = new StringBuilder(256);
11066                } else {
11067                    r.append(' ');
11068                }
11069                r.append(a.info.name);
11070            }
11071        }
11072        if (r != null) {
11073            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11074        }
11075
11076        r = null;
11077        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11078            // Only system apps can hold shared libraries.
11079            if (pkg.libraryNames != null) {
11080                for (i = 0; i < pkg.libraryNames.size(); i++) {
11081                    String name = pkg.libraryNames.get(i);
11082                    if (removeSharedLibraryLPw(name, 0)) {
11083                        if (DEBUG_REMOVE && chatty) {
11084                            if (r == null) {
11085                                r = new StringBuilder(256);
11086                            } else {
11087                                r.append(' ');
11088                            }
11089                            r.append(name);
11090                        }
11091                    }
11092                }
11093            }
11094        }
11095
11096        r = null;
11097
11098        // Any package can hold static shared libraries.
11099        if (pkg.staticSharedLibName != null) {
11100            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11101                if (DEBUG_REMOVE && chatty) {
11102                    if (r == null) {
11103                        r = new StringBuilder(256);
11104                    } else {
11105                        r.append(' ');
11106                    }
11107                    r.append(pkg.staticSharedLibName);
11108                }
11109            }
11110        }
11111
11112        if (r != null) {
11113            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11114        }
11115    }
11116
11117    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11118        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11119            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11120                return true;
11121            }
11122        }
11123        return false;
11124    }
11125
11126    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11127    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11128    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11129
11130    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11131        // Update the parent permissions
11132        updatePermissionsLPw(pkg.packageName, pkg, flags);
11133        // Update the child permissions
11134        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11135        for (int i = 0; i < childCount; i++) {
11136            PackageParser.Package childPkg = pkg.childPackages.get(i);
11137            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11138        }
11139    }
11140
11141    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11142            int flags) {
11143        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11144        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11145    }
11146
11147    private void updatePermissionsLPw(String changingPkg,
11148            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11149        // Make sure there are no dangling permission trees.
11150        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11151        while (it.hasNext()) {
11152            final BasePermission bp = it.next();
11153            if (bp.packageSetting == null) {
11154                // We may not yet have parsed the package, so just see if
11155                // we still know about its settings.
11156                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11157            }
11158            if (bp.packageSetting == null) {
11159                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11160                        + " from package " + bp.sourcePackage);
11161                it.remove();
11162            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11163                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11164                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11165                            + " from package " + bp.sourcePackage);
11166                    flags |= UPDATE_PERMISSIONS_ALL;
11167                    it.remove();
11168                }
11169            }
11170        }
11171
11172        // Make sure all dynamic permissions have been assigned to a package,
11173        // and make sure there are no dangling permissions.
11174        it = mSettings.mPermissions.values().iterator();
11175        while (it.hasNext()) {
11176            final BasePermission bp = it.next();
11177            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11178                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11179                        + bp.name + " pkg=" + bp.sourcePackage
11180                        + " info=" + bp.pendingInfo);
11181                if (bp.packageSetting == null && bp.pendingInfo != null) {
11182                    final BasePermission tree = findPermissionTreeLP(bp.name);
11183                    if (tree != null && tree.perm != null) {
11184                        bp.packageSetting = tree.packageSetting;
11185                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11186                                new PermissionInfo(bp.pendingInfo));
11187                        bp.perm.info.packageName = tree.perm.info.packageName;
11188                        bp.perm.info.name = bp.name;
11189                        bp.uid = tree.uid;
11190                    }
11191                }
11192            }
11193            if (bp.packageSetting == null) {
11194                // We may not yet have parsed the package, so just see if
11195                // we still know about its settings.
11196                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11197            }
11198            if (bp.packageSetting == null) {
11199                Slog.w(TAG, "Removing dangling permission: " + bp.name
11200                        + " from package " + bp.sourcePackage);
11201                it.remove();
11202            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11203                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11204                    Slog.i(TAG, "Removing old permission: " + bp.name
11205                            + " from package " + bp.sourcePackage);
11206                    flags |= UPDATE_PERMISSIONS_ALL;
11207                    it.remove();
11208                }
11209            }
11210        }
11211
11212        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11213        // Now update the permissions for all packages, in particular
11214        // replace the granted permissions of the system packages.
11215        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11216            for (PackageParser.Package pkg : mPackages.values()) {
11217                if (pkg != pkgInfo) {
11218                    // Only replace for packages on requested volume
11219                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11220                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11221                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11222                    grantPermissionsLPw(pkg, replace, changingPkg);
11223                }
11224            }
11225        }
11226
11227        if (pkgInfo != null) {
11228            // Only replace for packages on requested volume
11229            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11230            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11231                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11232            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11233        }
11234        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11235    }
11236
11237    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11238            String packageOfInterest) {
11239        // IMPORTANT: There are two types of permissions: install and runtime.
11240        // Install time permissions are granted when the app is installed to
11241        // all device users and users added in the future. Runtime permissions
11242        // are granted at runtime explicitly to specific users. Normal and signature
11243        // protected permissions are install time permissions. Dangerous permissions
11244        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11245        // otherwise they are runtime permissions. This function does not manage
11246        // runtime permissions except for the case an app targeting Lollipop MR1
11247        // being upgraded to target a newer SDK, in which case dangerous permissions
11248        // are transformed from install time to runtime ones.
11249
11250        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11251        if (ps == null) {
11252            return;
11253        }
11254
11255        PermissionsState permissionsState = ps.getPermissionsState();
11256        PermissionsState origPermissions = permissionsState;
11257
11258        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11259
11260        boolean runtimePermissionsRevoked = false;
11261        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11262
11263        boolean changedInstallPermission = false;
11264
11265        if (replace) {
11266            ps.installPermissionsFixed = false;
11267            if (!ps.isSharedUser()) {
11268                origPermissions = new PermissionsState(permissionsState);
11269                permissionsState.reset();
11270            } else {
11271                // We need to know only about runtime permission changes since the
11272                // calling code always writes the install permissions state but
11273                // the runtime ones are written only if changed. The only cases of
11274                // changed runtime permissions here are promotion of an install to
11275                // runtime and revocation of a runtime from a shared user.
11276                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11277                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11278                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11279                    runtimePermissionsRevoked = true;
11280                }
11281            }
11282        }
11283
11284        permissionsState.setGlobalGids(mGlobalGids);
11285
11286        final int N = pkg.requestedPermissions.size();
11287        for (int i=0; i<N; i++) {
11288            final String name = pkg.requestedPermissions.get(i);
11289            final BasePermission bp = mSettings.mPermissions.get(name);
11290
11291            if (DEBUG_INSTALL) {
11292                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11293            }
11294
11295            if (bp == null || bp.packageSetting == null) {
11296                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11297                    Slog.w(TAG, "Unknown permission " + name
11298                            + " in package " + pkg.packageName);
11299                }
11300                continue;
11301            }
11302
11303
11304            // Limit ephemeral apps to ephemeral allowed permissions.
11305            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11306                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11307                        + pkg.packageName);
11308                continue;
11309            }
11310
11311            final String perm = bp.name;
11312            boolean allowedSig = false;
11313            int grant = GRANT_DENIED;
11314
11315            // Keep track of app op permissions.
11316            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11317                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11318                if (pkgs == null) {
11319                    pkgs = new ArraySet<>();
11320                    mAppOpPermissionPackages.put(bp.name, pkgs);
11321                }
11322                pkgs.add(pkg.packageName);
11323            }
11324
11325            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11326            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11327                    >= Build.VERSION_CODES.M;
11328            switch (level) {
11329                case PermissionInfo.PROTECTION_NORMAL: {
11330                    // For all apps normal permissions are install time ones.
11331                    grant = GRANT_INSTALL;
11332                } break;
11333
11334                case PermissionInfo.PROTECTION_DANGEROUS: {
11335                    // If a permission review is required for legacy apps we represent
11336                    // their permissions as always granted runtime ones since we need
11337                    // to keep the review required permission flag per user while an
11338                    // install permission's state is shared across all users.
11339                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11340                        // For legacy apps dangerous permissions are install time ones.
11341                        grant = GRANT_INSTALL;
11342                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11343                        // For legacy apps that became modern, install becomes runtime.
11344                        grant = GRANT_UPGRADE;
11345                    } else if (mPromoteSystemApps
11346                            && isSystemApp(ps)
11347                            && mExistingSystemPackages.contains(ps.name)) {
11348                        // For legacy system apps, install becomes runtime.
11349                        // We cannot check hasInstallPermission() for system apps since those
11350                        // permissions were granted implicitly and not persisted pre-M.
11351                        grant = GRANT_UPGRADE;
11352                    } else {
11353                        // For modern apps keep runtime permissions unchanged.
11354                        grant = GRANT_RUNTIME;
11355                    }
11356                } break;
11357
11358                case PermissionInfo.PROTECTION_SIGNATURE: {
11359                    // For all apps signature permissions are install time ones.
11360                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11361                    if (allowedSig) {
11362                        grant = GRANT_INSTALL;
11363                    }
11364                } break;
11365            }
11366
11367            if (DEBUG_INSTALL) {
11368                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11369            }
11370
11371            if (grant != GRANT_DENIED) {
11372                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11373                    // If this is an existing, non-system package, then
11374                    // we can't add any new permissions to it.
11375                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11376                        // Except...  if this is a permission that was added
11377                        // to the platform (note: need to only do this when
11378                        // updating the platform).
11379                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11380                            grant = GRANT_DENIED;
11381                        }
11382                    }
11383                }
11384
11385                switch (grant) {
11386                    case GRANT_INSTALL: {
11387                        // Revoke this as runtime permission to handle the case of
11388                        // a runtime permission being downgraded to an install one.
11389                        // Also in permission review mode we keep dangerous permissions
11390                        // for legacy apps
11391                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11392                            if (origPermissions.getRuntimePermissionState(
11393                                    bp.name, userId) != null) {
11394                                // Revoke the runtime permission and clear the flags.
11395                                origPermissions.revokeRuntimePermission(bp, userId);
11396                                origPermissions.updatePermissionFlags(bp, userId,
11397                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11398                                // If we revoked a permission permission, we have to write.
11399                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11400                                        changedRuntimePermissionUserIds, userId);
11401                            }
11402                        }
11403                        // Grant an install permission.
11404                        if (permissionsState.grantInstallPermission(bp) !=
11405                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11406                            changedInstallPermission = true;
11407                        }
11408                    } break;
11409
11410                    case GRANT_RUNTIME: {
11411                        // Grant previously granted runtime permissions.
11412                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11413                            PermissionState permissionState = origPermissions
11414                                    .getRuntimePermissionState(bp.name, userId);
11415                            int flags = permissionState != null
11416                                    ? permissionState.getFlags() : 0;
11417                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11418                                // Don't propagate the permission in a permission review mode if
11419                                // the former was revoked, i.e. marked to not propagate on upgrade.
11420                                // Note that in a permission review mode install permissions are
11421                                // represented as constantly granted runtime ones since we need to
11422                                // keep a per user state associated with the permission. Also the
11423                                // revoke on upgrade flag is no longer applicable and is reset.
11424                                final boolean revokeOnUpgrade = (flags & PackageManager
11425                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11426                                if (revokeOnUpgrade) {
11427                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11428                                    // Since we changed the flags, we have to write.
11429                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11430                                            changedRuntimePermissionUserIds, userId);
11431                                }
11432                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11433                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11434                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11435                                        // If we cannot put the permission as it was,
11436                                        // we have to write.
11437                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11438                                                changedRuntimePermissionUserIds, userId);
11439                                    }
11440                                }
11441
11442                                // If the app supports runtime permissions no need for a review.
11443                                if (mPermissionReviewRequired
11444                                        && appSupportsRuntimePermissions
11445                                        && (flags & PackageManager
11446                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11447                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11448                                    // Since we changed the flags, we have to write.
11449                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11450                                            changedRuntimePermissionUserIds, userId);
11451                                }
11452                            } else if (mPermissionReviewRequired
11453                                    && !appSupportsRuntimePermissions) {
11454                                // For legacy apps that need a permission review, every new
11455                                // runtime permission is granted but it is pending a review.
11456                                // We also need to review only platform defined runtime
11457                                // permissions as these are the only ones the platform knows
11458                                // how to disable the API to simulate revocation as legacy
11459                                // apps don't expect to run with revoked permissions.
11460                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11461                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11462                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11463                                        // We changed the flags, hence have to write.
11464                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11465                                                changedRuntimePermissionUserIds, userId);
11466                                    }
11467                                }
11468                                if (permissionsState.grantRuntimePermission(bp, userId)
11469                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11470                                    // We changed the permission, hence have to write.
11471                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11472                                            changedRuntimePermissionUserIds, userId);
11473                                }
11474                            }
11475                            // Propagate the permission flags.
11476                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11477                        }
11478                    } break;
11479
11480                    case GRANT_UPGRADE: {
11481                        // Grant runtime permissions for a previously held install permission.
11482                        PermissionState permissionState = origPermissions
11483                                .getInstallPermissionState(bp.name);
11484                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11485
11486                        if (origPermissions.revokeInstallPermission(bp)
11487                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11488                            // We will be transferring the permission flags, so clear them.
11489                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11490                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11491                            changedInstallPermission = true;
11492                        }
11493
11494                        // If the permission is not to be promoted to runtime we ignore it and
11495                        // also its other flags as they are not applicable to install permissions.
11496                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11497                            for (int userId : currentUserIds) {
11498                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11499                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11500                                    // Transfer the permission flags.
11501                                    permissionsState.updatePermissionFlags(bp, userId,
11502                                            flags, flags);
11503                                    // If we granted the permission, we have to write.
11504                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11505                                            changedRuntimePermissionUserIds, userId);
11506                                }
11507                            }
11508                        }
11509                    } break;
11510
11511                    default: {
11512                        if (packageOfInterest == null
11513                                || packageOfInterest.equals(pkg.packageName)) {
11514                            Slog.w(TAG, "Not granting permission " + perm
11515                                    + " to package " + pkg.packageName
11516                                    + " because it was previously installed without");
11517                        }
11518                    } break;
11519                }
11520            } else {
11521                if (permissionsState.revokeInstallPermission(bp) !=
11522                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11523                    // Also drop the permission flags.
11524                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11525                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11526                    changedInstallPermission = true;
11527                    Slog.i(TAG, "Un-granting permission " + perm
11528                            + " from package " + pkg.packageName
11529                            + " (protectionLevel=" + bp.protectionLevel
11530                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11531                            + ")");
11532                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11533                    // Don't print warning for app op permissions, since it is fine for them
11534                    // not to be granted, there is a UI for the user to decide.
11535                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11536                        Slog.w(TAG, "Not granting permission " + perm
11537                                + " to package " + pkg.packageName
11538                                + " (protectionLevel=" + bp.protectionLevel
11539                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11540                                + ")");
11541                    }
11542                }
11543            }
11544        }
11545
11546        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11547                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11548            // This is the first that we have heard about this package, so the
11549            // permissions we have now selected are fixed until explicitly
11550            // changed.
11551            ps.installPermissionsFixed = true;
11552        }
11553
11554        // Persist the runtime permissions state for users with changes. If permissions
11555        // were revoked because no app in the shared user declares them we have to
11556        // write synchronously to avoid losing runtime permissions state.
11557        for (int userId : changedRuntimePermissionUserIds) {
11558            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11559        }
11560    }
11561
11562    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
11563        boolean allowed = false;
11564        final int NP = PackageParser.NEW_PERMISSIONS.length;
11565        for (int ip=0; ip<NP; ip++) {
11566            final PackageParser.NewPermissionInfo npi
11567                    = PackageParser.NEW_PERMISSIONS[ip];
11568            if (npi.name.equals(perm)
11569                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
11570                allowed = true;
11571                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
11572                        + pkg.packageName);
11573                break;
11574            }
11575        }
11576        return allowed;
11577    }
11578
11579    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
11580            BasePermission bp, PermissionsState origPermissions) {
11581        boolean privilegedPermission = (bp.protectionLevel
11582                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
11583        boolean privappPermissionsDisable =
11584                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
11585        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
11586        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
11587        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
11588                && !platformPackage && platformPermission) {
11589            ArraySet<String> wlPermissions = SystemConfig.getInstance()
11590                    .getPrivAppPermissions(pkg.packageName);
11591            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
11592            if (!whitelisted) {
11593                Slog.w(TAG, "Privileged permission " + perm + " for package "
11594                        + pkg.packageName + " - not in privapp-permissions whitelist");
11595                // Only report violations for apps on system image
11596                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
11597                    if (mPrivappPermissionsViolations == null) {
11598                        mPrivappPermissionsViolations = new ArraySet<>();
11599                    }
11600                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
11601                }
11602                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
11603                    return false;
11604                }
11605            }
11606        }
11607        boolean allowed = (compareSignatures(
11608                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
11609                        == PackageManager.SIGNATURE_MATCH)
11610                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
11611                        == PackageManager.SIGNATURE_MATCH);
11612        if (!allowed && privilegedPermission) {
11613            if (isSystemApp(pkg)) {
11614                // For updated system applications, a system permission
11615                // is granted only if it had been defined by the original application.
11616                if (pkg.isUpdatedSystemApp()) {
11617                    final PackageSetting sysPs = mSettings
11618                            .getDisabledSystemPkgLPr(pkg.packageName);
11619                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
11620                        // If the original was granted this permission, we take
11621                        // that grant decision as read and propagate it to the
11622                        // update.
11623                        if (sysPs.isPrivileged()) {
11624                            allowed = true;
11625                        }
11626                    } else {
11627                        // The system apk may have been updated with an older
11628                        // version of the one on the data partition, but which
11629                        // granted a new system permission that it didn't have
11630                        // before.  In this case we do want to allow the app to
11631                        // now get the new permission if the ancestral apk is
11632                        // privileged to get it.
11633                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
11634                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
11635                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
11636                                    allowed = true;
11637                                    break;
11638                                }
11639                            }
11640                        }
11641                        // Also if a privileged parent package on the system image or any of
11642                        // its children requested a privileged permission, the updated child
11643                        // packages can also get the permission.
11644                        if (pkg.parentPackage != null) {
11645                            final PackageSetting disabledSysParentPs = mSettings
11646                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
11647                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
11648                                    && disabledSysParentPs.isPrivileged()) {
11649                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
11650                                    allowed = true;
11651                                } else if (disabledSysParentPs.pkg.childPackages != null) {
11652                                    final int count = disabledSysParentPs.pkg.childPackages.size();
11653                                    for (int i = 0; i < count; i++) {
11654                                        PackageParser.Package disabledSysChildPkg =
11655                                                disabledSysParentPs.pkg.childPackages.get(i);
11656                                        if (isPackageRequestingPermission(disabledSysChildPkg,
11657                                                perm)) {
11658                                            allowed = true;
11659                                            break;
11660                                        }
11661                                    }
11662                                }
11663                            }
11664                        }
11665                    }
11666                } else {
11667                    allowed = isPrivilegedApp(pkg);
11668                }
11669            }
11670        }
11671        if (!allowed) {
11672            if (!allowed && (bp.protectionLevel
11673                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
11674                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
11675                // If this was a previously normal/dangerous permission that got moved
11676                // to a system permission as part of the runtime permission redesign, then
11677                // we still want to blindly grant it to old apps.
11678                allowed = true;
11679            }
11680            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
11681                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
11682                // If this permission is to be granted to the system installer and
11683                // this app is an installer, then it gets the permission.
11684                allowed = true;
11685            }
11686            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
11687                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
11688                // If this permission is to be granted to the system verifier and
11689                // this app is a verifier, then it gets the permission.
11690                allowed = true;
11691            }
11692            if (!allowed && (bp.protectionLevel
11693                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
11694                    && isSystemApp(pkg)) {
11695                // Any pre-installed system app is allowed to get this permission.
11696                allowed = true;
11697            }
11698            if (!allowed && (bp.protectionLevel
11699                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
11700                // For development permissions, a development permission
11701                // is granted only if it was already granted.
11702                allowed = origPermissions.hasInstallPermission(perm);
11703            }
11704            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
11705                    && pkg.packageName.equals(mSetupWizardPackage)) {
11706                // If this permission is to be granted to the system setup wizard and
11707                // this app is a setup wizard, then it gets the permission.
11708                allowed = true;
11709            }
11710        }
11711        return allowed;
11712    }
11713
11714    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
11715        final int permCount = pkg.requestedPermissions.size();
11716        for (int j = 0; j < permCount; j++) {
11717            String requestedPermission = pkg.requestedPermissions.get(j);
11718            if (permission.equals(requestedPermission)) {
11719                return true;
11720            }
11721        }
11722        return false;
11723    }
11724
11725    final class ActivityIntentResolver
11726            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11727        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11728                boolean defaultOnly, int userId) {
11729            if (!sUserManager.exists(userId)) return null;
11730            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
11731            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11732        }
11733
11734        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11735                int userId) {
11736            if (!sUserManager.exists(userId)) return null;
11737            mFlags = flags;
11738            return super.queryIntent(intent, resolvedType,
11739                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11740                    userId);
11741        }
11742
11743        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11744                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11745            if (!sUserManager.exists(userId)) return null;
11746            if (packageActivities == null) {
11747                return null;
11748            }
11749            mFlags = flags;
11750            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11751            final int N = packageActivities.size();
11752            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11753                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11754
11755            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11756            for (int i = 0; i < N; ++i) {
11757                intentFilters = packageActivities.get(i).intents;
11758                if (intentFilters != null && intentFilters.size() > 0) {
11759                    PackageParser.ActivityIntentInfo[] array =
11760                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11761                    intentFilters.toArray(array);
11762                    listCut.add(array);
11763                }
11764            }
11765            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11766        }
11767
11768        /**
11769         * Finds a privileged activity that matches the specified activity names.
11770         */
11771        private PackageParser.Activity findMatchingActivity(
11772                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11773            for (PackageParser.Activity sysActivity : activityList) {
11774                if (sysActivity.info.name.equals(activityInfo.name)) {
11775                    return sysActivity;
11776                }
11777                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11778                    return sysActivity;
11779                }
11780                if (sysActivity.info.targetActivity != null) {
11781                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11782                        return sysActivity;
11783                    }
11784                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11785                        return sysActivity;
11786                    }
11787                }
11788            }
11789            return null;
11790        }
11791
11792        public class IterGenerator<E> {
11793            public Iterator<E> generate(ActivityIntentInfo info) {
11794                return null;
11795            }
11796        }
11797
11798        public class ActionIterGenerator extends IterGenerator<String> {
11799            @Override
11800            public Iterator<String> generate(ActivityIntentInfo info) {
11801                return info.actionsIterator();
11802            }
11803        }
11804
11805        public class CategoriesIterGenerator extends IterGenerator<String> {
11806            @Override
11807            public Iterator<String> generate(ActivityIntentInfo info) {
11808                return info.categoriesIterator();
11809            }
11810        }
11811
11812        public class SchemesIterGenerator extends IterGenerator<String> {
11813            @Override
11814            public Iterator<String> generate(ActivityIntentInfo info) {
11815                return info.schemesIterator();
11816            }
11817        }
11818
11819        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11820            @Override
11821            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11822                return info.authoritiesIterator();
11823            }
11824        }
11825
11826        /**
11827         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11828         * MODIFIED. Do not pass in a list that should not be changed.
11829         */
11830        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11831                IterGenerator<T> generator, Iterator<T> searchIterator) {
11832            // loop through the set of actions; every one must be found in the intent filter
11833            while (searchIterator.hasNext()) {
11834                // we must have at least one filter in the list to consider a match
11835                if (intentList.size() == 0) {
11836                    break;
11837                }
11838
11839                final T searchAction = searchIterator.next();
11840
11841                // loop through the set of intent filters
11842                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11843                while (intentIter.hasNext()) {
11844                    final ActivityIntentInfo intentInfo = intentIter.next();
11845                    boolean selectionFound = false;
11846
11847                    // loop through the intent filter's selection criteria; at least one
11848                    // of them must match the searched criteria
11849                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11850                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11851                        final T intentSelection = intentSelectionIter.next();
11852                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11853                            selectionFound = true;
11854                            break;
11855                        }
11856                    }
11857
11858                    // the selection criteria wasn't found in this filter's set; this filter
11859                    // is not a potential match
11860                    if (!selectionFound) {
11861                        intentIter.remove();
11862                    }
11863                }
11864            }
11865        }
11866
11867        private boolean isProtectedAction(ActivityIntentInfo filter) {
11868            final Iterator<String> actionsIter = filter.actionsIterator();
11869            while (actionsIter != null && actionsIter.hasNext()) {
11870                final String filterAction = actionsIter.next();
11871                if (PROTECTED_ACTIONS.contains(filterAction)) {
11872                    return true;
11873                }
11874            }
11875            return false;
11876        }
11877
11878        /**
11879         * Adjusts the priority of the given intent filter according to policy.
11880         * <p>
11881         * <ul>
11882         * <li>The priority for non privileged applications is capped to '0'</li>
11883         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11884         * <li>The priority for unbundled updates to privileged applications is capped to the
11885         *      priority defined on the system partition</li>
11886         * </ul>
11887         * <p>
11888         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11889         * allowed to obtain any priority on any action.
11890         */
11891        private void adjustPriority(
11892                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11893            // nothing to do; priority is fine as-is
11894            if (intent.getPriority() <= 0) {
11895                return;
11896            }
11897
11898            final ActivityInfo activityInfo = intent.activity.info;
11899            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11900
11901            final boolean privilegedApp =
11902                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11903            if (!privilegedApp) {
11904                // non-privileged applications can never define a priority >0
11905                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
11906                        + " package: " + applicationInfo.packageName
11907                        + " activity: " + intent.activity.className
11908                        + " origPrio: " + intent.getPriority());
11909                intent.setPriority(0);
11910                return;
11911            }
11912
11913            if (systemActivities == null) {
11914                // the system package is not disabled; we're parsing the system partition
11915                if (isProtectedAction(intent)) {
11916                    if (mDeferProtectedFilters) {
11917                        // We can't deal with these just yet. No component should ever obtain a
11918                        // >0 priority for a protected actions, with ONE exception -- the setup
11919                        // wizard. The setup wizard, however, cannot be known until we're able to
11920                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
11921                        // until all intent filters have been processed. Chicken, meet egg.
11922                        // Let the filter temporarily have a high priority and rectify the
11923                        // priorities after all system packages have been scanned.
11924                        mProtectedFilters.add(intent);
11925                        if (DEBUG_FILTERS) {
11926                            Slog.i(TAG, "Protected action; save for later;"
11927                                    + " package: " + applicationInfo.packageName
11928                                    + " activity: " + intent.activity.className
11929                                    + " origPrio: " + intent.getPriority());
11930                        }
11931                        return;
11932                    } else {
11933                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
11934                            Slog.i(TAG, "No setup wizard;"
11935                                + " All protected intents capped to priority 0");
11936                        }
11937                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
11938                            if (DEBUG_FILTERS) {
11939                                Slog.i(TAG, "Found setup wizard;"
11940                                    + " allow priority " + intent.getPriority() + ";"
11941                                    + " package: " + intent.activity.info.packageName
11942                                    + " activity: " + intent.activity.className
11943                                    + " priority: " + intent.getPriority());
11944                            }
11945                            // setup wizard gets whatever it wants
11946                            return;
11947                        }
11948                        Slog.w(TAG, "Protected action; cap priority to 0;"
11949                                + " package: " + intent.activity.info.packageName
11950                                + " activity: " + intent.activity.className
11951                                + " origPrio: " + intent.getPriority());
11952                        intent.setPriority(0);
11953                        return;
11954                    }
11955                }
11956                // privileged apps on the system image get whatever priority they request
11957                return;
11958            }
11959
11960            // privileged app unbundled update ... try to find the same activity
11961            final PackageParser.Activity foundActivity =
11962                    findMatchingActivity(systemActivities, activityInfo);
11963            if (foundActivity == null) {
11964                // this is a new activity; it cannot obtain >0 priority
11965                if (DEBUG_FILTERS) {
11966                    Slog.i(TAG, "New activity; cap priority to 0;"
11967                            + " package: " + applicationInfo.packageName
11968                            + " activity: " + intent.activity.className
11969                            + " origPrio: " + intent.getPriority());
11970                }
11971                intent.setPriority(0);
11972                return;
11973            }
11974
11975            // found activity, now check for filter equivalence
11976
11977            // a shallow copy is enough; we modify the list, not its contents
11978            final List<ActivityIntentInfo> intentListCopy =
11979                    new ArrayList<>(foundActivity.intents);
11980            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
11981
11982            // find matching action subsets
11983            final Iterator<String> actionsIterator = intent.actionsIterator();
11984            if (actionsIterator != null) {
11985                getIntentListSubset(
11986                        intentListCopy, new ActionIterGenerator(), actionsIterator);
11987                if (intentListCopy.size() == 0) {
11988                    // no more intents to match; we're not equivalent
11989                    if (DEBUG_FILTERS) {
11990                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
11991                                + " package: " + applicationInfo.packageName
11992                                + " activity: " + intent.activity.className
11993                                + " origPrio: " + intent.getPriority());
11994                    }
11995                    intent.setPriority(0);
11996                    return;
11997                }
11998            }
11999
12000            // find matching category subsets
12001            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12002            if (categoriesIterator != null) {
12003                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12004                        categoriesIterator);
12005                if (intentListCopy.size() == 0) {
12006                    // no more intents to match; we're not equivalent
12007                    if (DEBUG_FILTERS) {
12008                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12009                                + " package: " + applicationInfo.packageName
12010                                + " activity: " + intent.activity.className
12011                                + " origPrio: " + intent.getPriority());
12012                    }
12013                    intent.setPriority(0);
12014                    return;
12015                }
12016            }
12017
12018            // find matching schemes subsets
12019            final Iterator<String> schemesIterator = intent.schemesIterator();
12020            if (schemesIterator != null) {
12021                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12022                        schemesIterator);
12023                if (intentListCopy.size() == 0) {
12024                    // no more intents to match; we're not equivalent
12025                    if (DEBUG_FILTERS) {
12026                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12027                                + " package: " + applicationInfo.packageName
12028                                + " activity: " + intent.activity.className
12029                                + " origPrio: " + intent.getPriority());
12030                    }
12031                    intent.setPriority(0);
12032                    return;
12033                }
12034            }
12035
12036            // find matching authorities subsets
12037            final Iterator<IntentFilter.AuthorityEntry>
12038                    authoritiesIterator = intent.authoritiesIterator();
12039            if (authoritiesIterator != null) {
12040                getIntentListSubset(intentListCopy,
12041                        new AuthoritiesIterGenerator(),
12042                        authoritiesIterator);
12043                if (intentListCopy.size() == 0) {
12044                    // no more intents to match; we're not equivalent
12045                    if (DEBUG_FILTERS) {
12046                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12047                                + " package: " + applicationInfo.packageName
12048                                + " activity: " + intent.activity.className
12049                                + " origPrio: " + intent.getPriority());
12050                    }
12051                    intent.setPriority(0);
12052                    return;
12053                }
12054            }
12055
12056            // we found matching filter(s); app gets the max priority of all intents
12057            int cappedPriority = 0;
12058            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12059                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12060            }
12061            if (intent.getPriority() > cappedPriority) {
12062                if (DEBUG_FILTERS) {
12063                    Slog.i(TAG, "Found matching filter(s);"
12064                            + " cap priority to " + cappedPriority + ";"
12065                            + " package: " + applicationInfo.packageName
12066                            + " activity: " + intent.activity.className
12067                            + " origPrio: " + intent.getPriority());
12068                }
12069                intent.setPriority(cappedPriority);
12070                return;
12071            }
12072            // all this for nothing; the requested priority was <= what was on the system
12073        }
12074
12075        public final void addActivity(PackageParser.Activity a, String type) {
12076            mActivities.put(a.getComponentName(), a);
12077            if (DEBUG_SHOW_INFO)
12078                Log.v(
12079                TAG, "  " + type + " " +
12080                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12081            if (DEBUG_SHOW_INFO)
12082                Log.v(TAG, "    Class=" + a.info.name);
12083            final int NI = a.intents.size();
12084            for (int j=0; j<NI; j++) {
12085                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12086                if ("activity".equals(type)) {
12087                    final PackageSetting ps =
12088                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12089                    final List<PackageParser.Activity> systemActivities =
12090                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12091                    adjustPriority(systemActivities, intent);
12092                }
12093                if (DEBUG_SHOW_INFO) {
12094                    Log.v(TAG, "    IntentFilter:");
12095                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12096                }
12097                if (!intent.debugCheck()) {
12098                    Log.w(TAG, "==> For Activity " + a.info.name);
12099                }
12100                addFilter(intent);
12101            }
12102        }
12103
12104        public final void removeActivity(PackageParser.Activity a, String type) {
12105            mActivities.remove(a.getComponentName());
12106            if (DEBUG_SHOW_INFO) {
12107                Log.v(TAG, "  " + type + " "
12108                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12109                                : a.info.name) + ":");
12110                Log.v(TAG, "    Class=" + a.info.name);
12111            }
12112            final int NI = a.intents.size();
12113            for (int j=0; j<NI; j++) {
12114                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12115                if (DEBUG_SHOW_INFO) {
12116                    Log.v(TAG, "    IntentFilter:");
12117                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12118                }
12119                removeFilter(intent);
12120            }
12121        }
12122
12123        @Override
12124        protected boolean allowFilterResult(
12125                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12126            ActivityInfo filterAi = filter.activity.info;
12127            for (int i=dest.size()-1; i>=0; i--) {
12128                ActivityInfo destAi = dest.get(i).activityInfo;
12129                if (destAi.name == filterAi.name
12130                        && destAi.packageName == filterAi.packageName) {
12131                    return false;
12132                }
12133            }
12134            return true;
12135        }
12136
12137        @Override
12138        protected ActivityIntentInfo[] newArray(int size) {
12139            return new ActivityIntentInfo[size];
12140        }
12141
12142        @Override
12143        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12144            if (!sUserManager.exists(userId)) return true;
12145            PackageParser.Package p = filter.activity.owner;
12146            if (p != null) {
12147                PackageSetting ps = (PackageSetting)p.mExtras;
12148                if (ps != null) {
12149                    // System apps are never considered stopped for purposes of
12150                    // filtering, because there may be no way for the user to
12151                    // actually re-launch them.
12152                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12153                            && ps.getStopped(userId);
12154                }
12155            }
12156            return false;
12157        }
12158
12159        @Override
12160        protected boolean isPackageForFilter(String packageName,
12161                PackageParser.ActivityIntentInfo info) {
12162            return packageName.equals(info.activity.owner.packageName);
12163        }
12164
12165        @Override
12166        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12167                int match, int userId) {
12168            if (!sUserManager.exists(userId)) return null;
12169            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12170                return null;
12171            }
12172            final PackageParser.Activity activity = info.activity;
12173            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12174            if (ps == null) {
12175                return null;
12176            }
12177            final PackageUserState userState = ps.readUserState(userId);
12178            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
12179                    userState, userId);
12180            if (ai == null) {
12181                return null;
12182            }
12183            final boolean matchVisibleToInstantApp =
12184                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12185            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12186            // throw out filters that aren't visible to ephemeral apps
12187            if (matchVisibleToInstantApp
12188                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12189                return null;
12190            }
12191            // throw out ephemeral filters if we're not explicitly requesting them
12192            if (!isInstantApp && userState.instantApp) {
12193                return null;
12194            }
12195            // throw out instant app filters if updates are available; will trigger
12196            // instant app resolution
12197            if (userState.instantApp && ps.isUpdateAvailable()) {
12198                return null;
12199            }
12200            final ResolveInfo res = new ResolveInfo();
12201            res.activityInfo = ai;
12202            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12203                res.filter = info;
12204            }
12205            if (info != null) {
12206                res.handleAllWebDataURI = info.handleAllWebDataURI();
12207            }
12208            res.priority = info.getPriority();
12209            res.preferredOrder = activity.owner.mPreferredOrder;
12210            //System.out.println("Result: " + res.activityInfo.className +
12211            //                   " = " + res.priority);
12212            res.match = match;
12213            res.isDefault = info.hasDefault;
12214            res.labelRes = info.labelRes;
12215            res.nonLocalizedLabel = info.nonLocalizedLabel;
12216            if (userNeedsBadging(userId)) {
12217                res.noResourceId = true;
12218            } else {
12219                res.icon = info.icon;
12220            }
12221            res.iconResourceId = info.icon;
12222            res.system = res.activityInfo.applicationInfo.isSystemApp();
12223            res.instantAppAvailable = userState.instantApp;
12224            return res;
12225        }
12226
12227        @Override
12228        protected void sortResults(List<ResolveInfo> results) {
12229            Collections.sort(results, mResolvePrioritySorter);
12230        }
12231
12232        @Override
12233        protected void dumpFilter(PrintWriter out, String prefix,
12234                PackageParser.ActivityIntentInfo filter) {
12235            out.print(prefix); out.print(
12236                    Integer.toHexString(System.identityHashCode(filter.activity)));
12237                    out.print(' ');
12238                    filter.activity.printComponentShortName(out);
12239                    out.print(" filter ");
12240                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12241        }
12242
12243        @Override
12244        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12245            return filter.activity;
12246        }
12247
12248        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12249            PackageParser.Activity activity = (PackageParser.Activity)label;
12250            out.print(prefix); out.print(
12251                    Integer.toHexString(System.identityHashCode(activity)));
12252                    out.print(' ');
12253                    activity.printComponentShortName(out);
12254            if (count > 1) {
12255                out.print(" ("); out.print(count); out.print(" filters)");
12256            }
12257            out.println();
12258        }
12259
12260        // Keys are String (activity class name), values are Activity.
12261        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12262                = new ArrayMap<ComponentName, PackageParser.Activity>();
12263        private int mFlags;
12264    }
12265
12266    private final class ServiceIntentResolver
12267            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12268        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12269                boolean defaultOnly, int userId) {
12270            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12271            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12272        }
12273
12274        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12275                int userId) {
12276            if (!sUserManager.exists(userId)) return null;
12277            mFlags = flags;
12278            return super.queryIntent(intent, resolvedType,
12279                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12280                    userId);
12281        }
12282
12283        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12284                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12285            if (!sUserManager.exists(userId)) return null;
12286            if (packageServices == null) {
12287                return null;
12288            }
12289            mFlags = flags;
12290            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12291            final int N = packageServices.size();
12292            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12293                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12294
12295            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12296            for (int i = 0; i < N; ++i) {
12297                intentFilters = packageServices.get(i).intents;
12298                if (intentFilters != null && intentFilters.size() > 0) {
12299                    PackageParser.ServiceIntentInfo[] array =
12300                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12301                    intentFilters.toArray(array);
12302                    listCut.add(array);
12303                }
12304            }
12305            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12306        }
12307
12308        public final void addService(PackageParser.Service s) {
12309            mServices.put(s.getComponentName(), s);
12310            if (DEBUG_SHOW_INFO) {
12311                Log.v(TAG, "  "
12312                        + (s.info.nonLocalizedLabel != null
12313                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12314                Log.v(TAG, "    Class=" + s.info.name);
12315            }
12316            final int NI = s.intents.size();
12317            int j;
12318            for (j=0; j<NI; j++) {
12319                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12320                if (DEBUG_SHOW_INFO) {
12321                    Log.v(TAG, "    IntentFilter:");
12322                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12323                }
12324                if (!intent.debugCheck()) {
12325                    Log.w(TAG, "==> For Service " + s.info.name);
12326                }
12327                addFilter(intent);
12328            }
12329        }
12330
12331        public final void removeService(PackageParser.Service s) {
12332            mServices.remove(s.getComponentName());
12333            if (DEBUG_SHOW_INFO) {
12334                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12335                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12336                Log.v(TAG, "    Class=" + s.info.name);
12337            }
12338            final int NI = s.intents.size();
12339            int j;
12340            for (j=0; j<NI; j++) {
12341                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12342                if (DEBUG_SHOW_INFO) {
12343                    Log.v(TAG, "    IntentFilter:");
12344                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12345                }
12346                removeFilter(intent);
12347            }
12348        }
12349
12350        @Override
12351        protected boolean allowFilterResult(
12352                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12353            ServiceInfo filterSi = filter.service.info;
12354            for (int i=dest.size()-1; i>=0; i--) {
12355                ServiceInfo destAi = dest.get(i).serviceInfo;
12356                if (destAi.name == filterSi.name
12357                        && destAi.packageName == filterSi.packageName) {
12358                    return false;
12359                }
12360            }
12361            return true;
12362        }
12363
12364        @Override
12365        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12366            return new PackageParser.ServiceIntentInfo[size];
12367        }
12368
12369        @Override
12370        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12371            if (!sUserManager.exists(userId)) return true;
12372            PackageParser.Package p = filter.service.owner;
12373            if (p != null) {
12374                PackageSetting ps = (PackageSetting)p.mExtras;
12375                if (ps != null) {
12376                    // System apps are never considered stopped for purposes of
12377                    // filtering, because there may be no way for the user to
12378                    // actually re-launch them.
12379                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12380                            && ps.getStopped(userId);
12381                }
12382            }
12383            return false;
12384        }
12385
12386        @Override
12387        protected boolean isPackageForFilter(String packageName,
12388                PackageParser.ServiceIntentInfo info) {
12389            return packageName.equals(info.service.owner.packageName);
12390        }
12391
12392        @Override
12393        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12394                int match, int userId) {
12395            if (!sUserManager.exists(userId)) return null;
12396            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12397            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12398                return null;
12399            }
12400            final PackageParser.Service service = info.service;
12401            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12402            if (ps == null) {
12403                return null;
12404            }
12405            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12406                    ps.readUserState(userId), userId);
12407            if (si == null) {
12408                return null;
12409            }
12410            final ResolveInfo res = new ResolveInfo();
12411            res.serviceInfo = si;
12412            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12413                res.filter = filter;
12414            }
12415            res.priority = info.getPriority();
12416            res.preferredOrder = service.owner.mPreferredOrder;
12417            res.match = match;
12418            res.isDefault = info.hasDefault;
12419            res.labelRes = info.labelRes;
12420            res.nonLocalizedLabel = info.nonLocalizedLabel;
12421            res.icon = info.icon;
12422            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12423            return res;
12424        }
12425
12426        @Override
12427        protected void sortResults(List<ResolveInfo> results) {
12428            Collections.sort(results, mResolvePrioritySorter);
12429        }
12430
12431        @Override
12432        protected void dumpFilter(PrintWriter out, String prefix,
12433                PackageParser.ServiceIntentInfo filter) {
12434            out.print(prefix); out.print(
12435                    Integer.toHexString(System.identityHashCode(filter.service)));
12436                    out.print(' ');
12437                    filter.service.printComponentShortName(out);
12438                    out.print(" filter ");
12439                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12440        }
12441
12442        @Override
12443        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12444            return filter.service;
12445        }
12446
12447        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12448            PackageParser.Service service = (PackageParser.Service)label;
12449            out.print(prefix); out.print(
12450                    Integer.toHexString(System.identityHashCode(service)));
12451                    out.print(' ');
12452                    service.printComponentShortName(out);
12453            if (count > 1) {
12454                out.print(" ("); out.print(count); out.print(" filters)");
12455            }
12456            out.println();
12457        }
12458
12459//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12460//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12461//            final List<ResolveInfo> retList = Lists.newArrayList();
12462//            while (i.hasNext()) {
12463//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12464//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12465//                    retList.add(resolveInfo);
12466//                }
12467//            }
12468//            return retList;
12469//        }
12470
12471        // Keys are String (activity class name), values are Activity.
12472        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12473                = new ArrayMap<ComponentName, PackageParser.Service>();
12474        private int mFlags;
12475    }
12476
12477    private final class ProviderIntentResolver
12478            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12479        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12480                boolean defaultOnly, int userId) {
12481            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12482            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12483        }
12484
12485        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12486                int userId) {
12487            if (!sUserManager.exists(userId))
12488                return null;
12489            mFlags = flags;
12490            return super.queryIntent(intent, resolvedType,
12491                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12492                    userId);
12493        }
12494
12495        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12496                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12497            if (!sUserManager.exists(userId))
12498                return null;
12499            if (packageProviders == null) {
12500                return null;
12501            }
12502            mFlags = flags;
12503            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12504            final int N = packageProviders.size();
12505            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12506                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12507
12508            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12509            for (int i = 0; i < N; ++i) {
12510                intentFilters = packageProviders.get(i).intents;
12511                if (intentFilters != null && intentFilters.size() > 0) {
12512                    PackageParser.ProviderIntentInfo[] array =
12513                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12514                    intentFilters.toArray(array);
12515                    listCut.add(array);
12516                }
12517            }
12518            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12519        }
12520
12521        public final void addProvider(PackageParser.Provider p) {
12522            if (mProviders.containsKey(p.getComponentName())) {
12523                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12524                return;
12525            }
12526
12527            mProviders.put(p.getComponentName(), p);
12528            if (DEBUG_SHOW_INFO) {
12529                Log.v(TAG, "  "
12530                        + (p.info.nonLocalizedLabel != null
12531                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12532                Log.v(TAG, "    Class=" + p.info.name);
12533            }
12534            final int NI = p.intents.size();
12535            int j;
12536            for (j = 0; j < NI; j++) {
12537                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12538                if (DEBUG_SHOW_INFO) {
12539                    Log.v(TAG, "    IntentFilter:");
12540                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12541                }
12542                if (!intent.debugCheck()) {
12543                    Log.w(TAG, "==> For Provider " + p.info.name);
12544                }
12545                addFilter(intent);
12546            }
12547        }
12548
12549        public final void removeProvider(PackageParser.Provider p) {
12550            mProviders.remove(p.getComponentName());
12551            if (DEBUG_SHOW_INFO) {
12552                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12553                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12554                Log.v(TAG, "    Class=" + p.info.name);
12555            }
12556            final int NI = p.intents.size();
12557            int j;
12558            for (j = 0; j < NI; j++) {
12559                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12560                if (DEBUG_SHOW_INFO) {
12561                    Log.v(TAG, "    IntentFilter:");
12562                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12563                }
12564                removeFilter(intent);
12565            }
12566        }
12567
12568        @Override
12569        protected boolean allowFilterResult(
12570                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12571            ProviderInfo filterPi = filter.provider.info;
12572            for (int i = dest.size() - 1; i >= 0; i--) {
12573                ProviderInfo destPi = dest.get(i).providerInfo;
12574                if (destPi.name == filterPi.name
12575                        && destPi.packageName == filterPi.packageName) {
12576                    return false;
12577                }
12578            }
12579            return true;
12580        }
12581
12582        @Override
12583        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12584            return new PackageParser.ProviderIntentInfo[size];
12585        }
12586
12587        @Override
12588        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12589            if (!sUserManager.exists(userId))
12590                return true;
12591            PackageParser.Package p = filter.provider.owner;
12592            if (p != null) {
12593                PackageSetting ps = (PackageSetting) p.mExtras;
12594                if (ps != null) {
12595                    // System apps are never considered stopped for purposes of
12596                    // filtering, because there may be no way for the user to
12597                    // actually re-launch them.
12598                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12599                            && ps.getStopped(userId);
12600                }
12601            }
12602            return false;
12603        }
12604
12605        @Override
12606        protected boolean isPackageForFilter(String packageName,
12607                PackageParser.ProviderIntentInfo info) {
12608            return packageName.equals(info.provider.owner.packageName);
12609        }
12610
12611        @Override
12612        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12613                int match, int userId) {
12614            if (!sUserManager.exists(userId))
12615                return null;
12616            final PackageParser.ProviderIntentInfo info = filter;
12617            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12618                return null;
12619            }
12620            final PackageParser.Provider provider = info.provider;
12621            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12622            if (ps == null) {
12623                return null;
12624            }
12625            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12626                    ps.readUserState(userId), userId);
12627            if (pi == null) {
12628                return null;
12629            }
12630            final ResolveInfo res = new ResolveInfo();
12631            res.providerInfo = pi;
12632            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12633                res.filter = filter;
12634            }
12635            res.priority = info.getPriority();
12636            res.preferredOrder = provider.owner.mPreferredOrder;
12637            res.match = match;
12638            res.isDefault = info.hasDefault;
12639            res.labelRes = info.labelRes;
12640            res.nonLocalizedLabel = info.nonLocalizedLabel;
12641            res.icon = info.icon;
12642            res.system = res.providerInfo.applicationInfo.isSystemApp();
12643            return res;
12644        }
12645
12646        @Override
12647        protected void sortResults(List<ResolveInfo> results) {
12648            Collections.sort(results, mResolvePrioritySorter);
12649        }
12650
12651        @Override
12652        protected void dumpFilter(PrintWriter out, String prefix,
12653                PackageParser.ProviderIntentInfo filter) {
12654            out.print(prefix);
12655            out.print(
12656                    Integer.toHexString(System.identityHashCode(filter.provider)));
12657            out.print(' ');
12658            filter.provider.printComponentShortName(out);
12659            out.print(" filter ");
12660            out.println(Integer.toHexString(System.identityHashCode(filter)));
12661        }
12662
12663        @Override
12664        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12665            return filter.provider;
12666        }
12667
12668        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12669            PackageParser.Provider provider = (PackageParser.Provider)label;
12670            out.print(prefix); out.print(
12671                    Integer.toHexString(System.identityHashCode(provider)));
12672                    out.print(' ');
12673                    provider.printComponentShortName(out);
12674            if (count > 1) {
12675                out.print(" ("); out.print(count); out.print(" filters)");
12676            }
12677            out.println();
12678        }
12679
12680        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12681                = new ArrayMap<ComponentName, PackageParser.Provider>();
12682        private int mFlags;
12683    }
12684
12685    static final class EphemeralIntentResolver
12686            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
12687        /**
12688         * The result that has the highest defined order. Ordering applies on a
12689         * per-package basis. Mapping is from package name to Pair of order and
12690         * EphemeralResolveInfo.
12691         * <p>
12692         * NOTE: This is implemented as a field variable for convenience and efficiency.
12693         * By having a field variable, we're able to track filter ordering as soon as
12694         * a non-zero order is defined. Otherwise, multiple loops across the result set
12695         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12696         * this needs to be contained entirely within {@link #filterResults}.
12697         */
12698        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
12699
12700        @Override
12701        protected AuxiliaryResolveInfo[] newArray(int size) {
12702            return new AuxiliaryResolveInfo[size];
12703        }
12704
12705        @Override
12706        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
12707            return true;
12708        }
12709
12710        @Override
12711        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
12712                int userId) {
12713            if (!sUserManager.exists(userId)) {
12714                return null;
12715            }
12716            final String packageName = responseObj.resolveInfo.getPackageName();
12717            final Integer order = responseObj.getOrder();
12718            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
12719                    mOrderResult.get(packageName);
12720            // ordering is enabled and this item's order isn't high enough
12721            if (lastOrderResult != null && lastOrderResult.first >= order) {
12722                return null;
12723            }
12724            final InstantAppResolveInfo res = responseObj.resolveInfo;
12725            if (order > 0) {
12726                // non-zero order, enable ordering
12727                mOrderResult.put(packageName, new Pair<>(order, res));
12728            }
12729            return responseObj;
12730        }
12731
12732        @Override
12733        protected void filterResults(List<AuxiliaryResolveInfo> results) {
12734            // only do work if ordering is enabled [most of the time it won't be]
12735            if (mOrderResult.size() == 0) {
12736                return;
12737            }
12738            int resultSize = results.size();
12739            for (int i = 0; i < resultSize; i++) {
12740                final InstantAppResolveInfo info = results.get(i).resolveInfo;
12741                final String packageName = info.getPackageName();
12742                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
12743                if (savedInfo == null) {
12744                    // package doesn't having ordering
12745                    continue;
12746                }
12747                if (savedInfo.second == info) {
12748                    // circled back to the highest ordered item; remove from order list
12749                    mOrderResult.remove(savedInfo);
12750                    if (mOrderResult.size() == 0) {
12751                        // no more ordered items
12752                        break;
12753                    }
12754                    continue;
12755                }
12756                // item has a worse order, remove it from the result list
12757                results.remove(i);
12758                resultSize--;
12759                i--;
12760            }
12761        }
12762    }
12763
12764    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12765            new Comparator<ResolveInfo>() {
12766        public int compare(ResolveInfo r1, ResolveInfo r2) {
12767            int v1 = r1.priority;
12768            int v2 = r2.priority;
12769            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12770            if (v1 != v2) {
12771                return (v1 > v2) ? -1 : 1;
12772            }
12773            v1 = r1.preferredOrder;
12774            v2 = r2.preferredOrder;
12775            if (v1 != v2) {
12776                return (v1 > v2) ? -1 : 1;
12777            }
12778            if (r1.isDefault != r2.isDefault) {
12779                return r1.isDefault ? -1 : 1;
12780            }
12781            v1 = r1.match;
12782            v2 = r2.match;
12783            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12784            if (v1 != v2) {
12785                return (v1 > v2) ? -1 : 1;
12786            }
12787            if (r1.system != r2.system) {
12788                return r1.system ? -1 : 1;
12789            }
12790            if (r1.activityInfo != null) {
12791                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12792            }
12793            if (r1.serviceInfo != null) {
12794                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12795            }
12796            if (r1.providerInfo != null) {
12797                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12798            }
12799            return 0;
12800        }
12801    };
12802
12803    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12804            new Comparator<ProviderInfo>() {
12805        public int compare(ProviderInfo p1, ProviderInfo p2) {
12806            final int v1 = p1.initOrder;
12807            final int v2 = p2.initOrder;
12808            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12809        }
12810    };
12811
12812    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12813            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12814            final int[] userIds) {
12815        mHandler.post(new Runnable() {
12816            @Override
12817            public void run() {
12818                try {
12819                    final IActivityManager am = ActivityManager.getService();
12820                    if (am == null) return;
12821                    final int[] resolvedUserIds;
12822                    if (userIds == null) {
12823                        resolvedUserIds = am.getRunningUserIds();
12824                    } else {
12825                        resolvedUserIds = userIds;
12826                    }
12827                    for (int id : resolvedUserIds) {
12828                        final Intent intent = new Intent(action,
12829                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12830                        if (extras != null) {
12831                            intent.putExtras(extras);
12832                        }
12833                        if (targetPkg != null) {
12834                            intent.setPackage(targetPkg);
12835                        }
12836                        // Modify the UID when posting to other users
12837                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12838                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12839                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12840                            intent.putExtra(Intent.EXTRA_UID, uid);
12841                        }
12842                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12843                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12844                        if (DEBUG_BROADCASTS) {
12845                            RuntimeException here = new RuntimeException("here");
12846                            here.fillInStackTrace();
12847                            Slog.d(TAG, "Sending to user " + id + ": "
12848                                    + intent.toShortString(false, true, false, false)
12849                                    + " " + intent.getExtras(), here);
12850                        }
12851                        am.broadcastIntent(null, intent, null, finishedReceiver,
12852                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12853                                null, finishedReceiver != null, false, id);
12854                    }
12855                } catch (RemoteException ex) {
12856                }
12857            }
12858        });
12859    }
12860
12861    /**
12862     * Check if the external storage media is available. This is true if there
12863     * is a mounted external storage medium or if the external storage is
12864     * emulated.
12865     */
12866    private boolean isExternalMediaAvailable() {
12867        return mMediaMounted || Environment.isExternalStorageEmulated();
12868    }
12869
12870    @Override
12871    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12872        // writer
12873        synchronized (mPackages) {
12874            if (!isExternalMediaAvailable()) {
12875                // If the external storage is no longer mounted at this point,
12876                // the caller may not have been able to delete all of this
12877                // packages files and can not delete any more.  Bail.
12878                return null;
12879            }
12880            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12881            if (lastPackage != null) {
12882                pkgs.remove(lastPackage);
12883            }
12884            if (pkgs.size() > 0) {
12885                return pkgs.get(0);
12886            }
12887        }
12888        return null;
12889    }
12890
12891    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
12892        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12893                userId, andCode ? 1 : 0, packageName);
12894        if (mSystemReady) {
12895            msg.sendToTarget();
12896        } else {
12897            if (mPostSystemReadyMessages == null) {
12898                mPostSystemReadyMessages = new ArrayList<>();
12899            }
12900            mPostSystemReadyMessages.add(msg);
12901        }
12902    }
12903
12904    void startCleaningPackages() {
12905        // reader
12906        if (!isExternalMediaAvailable()) {
12907            return;
12908        }
12909        synchronized (mPackages) {
12910            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
12911                return;
12912            }
12913        }
12914        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
12915        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
12916        IActivityManager am = ActivityManager.getService();
12917        if (am != null) {
12918            try {
12919                getDeviceIdleController().addPowerSaveTempWhitelistApp(Process.SYSTEM_UID,
12920                        DEFAULT_CONTAINER_PACKAGE, DEFAULT_CONTAINER_WHITELIST_DURATION,
12921                        UserHandle.USER_SYSTEM, false, "cleaning packages");
12922                am.startService(null, intent, null, -1, null, false, mContext.getOpPackageName(),
12923                        UserHandle.USER_SYSTEM);
12924            } catch (RemoteException e) {
12925            }
12926        }
12927    }
12928
12929    @Override
12930    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
12931            int installFlags, String installerPackageName, int userId) {
12932        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
12933
12934        final int callingUid = Binder.getCallingUid();
12935        enforceCrossUserPermission(callingUid, userId,
12936                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
12937
12938        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12939            try {
12940                if (observer != null) {
12941                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
12942                }
12943            } catch (RemoteException re) {
12944            }
12945            return;
12946        }
12947
12948        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
12949            installFlags |= PackageManager.INSTALL_FROM_ADB;
12950
12951        } else {
12952            // Caller holds INSTALL_PACKAGES permission, so we're less strict
12953            // about installerPackageName.
12954
12955            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
12956            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
12957        }
12958
12959        UserHandle user;
12960        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
12961            user = UserHandle.ALL;
12962        } else {
12963            user = new UserHandle(userId);
12964        }
12965
12966        // Only system components can circumvent runtime permissions when installing.
12967        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
12968                && mContext.checkCallingOrSelfPermission(Manifest.permission
12969                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
12970            throw new SecurityException("You need the "
12971                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
12972                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
12973        }
12974
12975        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
12976                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12977            throw new IllegalArgumentException(
12978                    "New installs into ASEC containers no longer supported");
12979        }
12980
12981        final File originFile = new File(originPath);
12982        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
12983
12984        final Message msg = mHandler.obtainMessage(INIT_COPY);
12985        final VerificationInfo verificationInfo = new VerificationInfo(
12986                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
12987        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
12988                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
12989                null /*packageAbiOverride*/, null /*grantedPermissions*/,
12990                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
12991        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
12992        msg.obj = params;
12993
12994        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
12995                System.identityHashCode(msg.obj));
12996        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12997                System.identityHashCode(msg.obj));
12998
12999        mHandler.sendMessage(msg);
13000    }
13001
13002
13003    /**
13004     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13005     * it is acting on behalf on an enterprise or the user).
13006     *
13007     * Note that the ordering of the conditionals in this method is important. The checks we perform
13008     * are as follows, in this order:
13009     *
13010     * 1) If the install is being performed by a system app, we can trust the app to have set the
13011     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13012     *    what it is.
13013     * 2) If the install is being performed by a device or profile owner app, the install reason
13014     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13015     *    set the install reason correctly. If the app targets an older SDK version where install
13016     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13017     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13018     * 3) In all other cases, the install is being performed by a regular app that is neither part
13019     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13020     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13021     *    set to enterprise policy and if so, change it to unknown instead.
13022     */
13023    private int fixUpInstallReason(String installerPackageName, int installerUid,
13024            int installReason) {
13025        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13026                == PERMISSION_GRANTED) {
13027            // If the install is being performed by a system app, we trust that app to have set the
13028            // install reason correctly.
13029            return installReason;
13030        }
13031
13032        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13033            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13034        if (dpm != null) {
13035            ComponentName owner = null;
13036            try {
13037                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13038                if (owner == null) {
13039                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13040                }
13041            } catch (RemoteException e) {
13042            }
13043            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13044                // If the install is being performed by a device or profile owner, the install
13045                // reason should be enterprise policy.
13046                return PackageManager.INSTALL_REASON_POLICY;
13047            }
13048        }
13049
13050        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13051            // If the install is being performed by a regular app (i.e. neither system app nor
13052            // device or profile owner), we have no reason to believe that the app is acting on
13053            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13054            // change it to unknown instead.
13055            return PackageManager.INSTALL_REASON_UNKNOWN;
13056        }
13057
13058        // If the install is being performed by a regular app and the install reason was set to any
13059        // value but enterprise policy, leave the install reason unchanged.
13060        return installReason;
13061    }
13062
13063    void installStage(String packageName, File stagedDir, String stagedCid,
13064            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13065            String installerPackageName, int installerUid, UserHandle user,
13066            Certificate[][] certificates) {
13067        if (DEBUG_EPHEMERAL) {
13068            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13069                Slog.d(TAG, "Ephemeral install of " + packageName);
13070            }
13071        }
13072        final VerificationInfo verificationInfo = new VerificationInfo(
13073                sessionParams.originatingUri, sessionParams.referrerUri,
13074                sessionParams.originatingUid, installerUid);
13075
13076        final OriginInfo origin;
13077        if (stagedDir != null) {
13078            origin = OriginInfo.fromStagedFile(stagedDir);
13079        } else {
13080            origin = OriginInfo.fromStagedContainer(stagedCid);
13081        }
13082
13083        final Message msg = mHandler.obtainMessage(INIT_COPY);
13084        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13085                sessionParams.installReason);
13086        final InstallParams params = new InstallParams(origin, null, observer,
13087                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13088                verificationInfo, user, sessionParams.abiOverride,
13089                sessionParams.grantedRuntimePermissions, certificates, installReason);
13090        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13091        msg.obj = params;
13092
13093        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13094                System.identityHashCode(msg.obj));
13095        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13096                System.identityHashCode(msg.obj));
13097
13098        mHandler.sendMessage(msg);
13099    }
13100
13101    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13102            int userId) {
13103        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13104        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13105    }
13106
13107    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
13108            int appId, int... userIds) {
13109        if (ArrayUtils.isEmpty(userIds)) {
13110            return;
13111        }
13112        Bundle extras = new Bundle(1);
13113        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13114        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13115
13116        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13117                packageName, extras, 0, null, null, userIds);
13118        if (isSystem) {
13119            mHandler.post(() -> {
13120                        for (int userId : userIds) {
13121                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13122                        }
13123                    }
13124            );
13125        }
13126    }
13127
13128    /**
13129     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13130     * automatically without needing an explicit launch.
13131     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13132     */
13133    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13134        // If user is not running, the app didn't miss any broadcast
13135        if (!mUserManagerInternal.isUserRunning(userId)) {
13136            return;
13137        }
13138        final IActivityManager am = ActivityManager.getService();
13139        try {
13140            // Deliver LOCKED_BOOT_COMPLETED first
13141            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13142                    .setPackage(packageName);
13143            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13144            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13145                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13146
13147            // Deliver BOOT_COMPLETED only if user is unlocked
13148            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13149                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13150                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13151                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13152            }
13153        } catch (RemoteException e) {
13154            throw e.rethrowFromSystemServer();
13155        }
13156    }
13157
13158    @Override
13159    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13160            int userId) {
13161        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13162        PackageSetting pkgSetting;
13163        final int uid = Binder.getCallingUid();
13164        enforceCrossUserPermission(uid, userId,
13165                true /* requireFullPermission */, true /* checkShell */,
13166                "setApplicationHiddenSetting for user " + userId);
13167
13168        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13169            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13170            return false;
13171        }
13172
13173        long callingId = Binder.clearCallingIdentity();
13174        try {
13175            boolean sendAdded = false;
13176            boolean sendRemoved = false;
13177            // writer
13178            synchronized (mPackages) {
13179                pkgSetting = mSettings.mPackages.get(packageName);
13180                if (pkgSetting == null) {
13181                    return false;
13182                }
13183                // Do not allow "android" is being disabled
13184                if ("android".equals(packageName)) {
13185                    Slog.w(TAG, "Cannot hide package: android");
13186                    return false;
13187                }
13188                // Cannot hide static shared libs as they are considered
13189                // a part of the using app (emulating static linking). Also
13190                // static libs are installed always on internal storage.
13191                PackageParser.Package pkg = mPackages.get(packageName);
13192                if (pkg != null && pkg.staticSharedLibName != null) {
13193                    Slog.w(TAG, "Cannot hide package: " + packageName
13194                            + " providing static shared library: "
13195                            + pkg.staticSharedLibName);
13196                    return false;
13197                }
13198                // Only allow protected packages to hide themselves.
13199                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13200                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13201                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13202                    return false;
13203                }
13204
13205                if (pkgSetting.getHidden(userId) != hidden) {
13206                    pkgSetting.setHidden(hidden, userId);
13207                    mSettings.writePackageRestrictionsLPr(userId);
13208                    if (hidden) {
13209                        sendRemoved = true;
13210                    } else {
13211                        sendAdded = true;
13212                    }
13213                }
13214            }
13215            if (sendAdded) {
13216                sendPackageAddedForUser(packageName, pkgSetting, userId);
13217                return true;
13218            }
13219            if (sendRemoved) {
13220                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13221                        "hiding pkg");
13222                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13223                return true;
13224            }
13225        } finally {
13226            Binder.restoreCallingIdentity(callingId);
13227        }
13228        return false;
13229    }
13230
13231    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13232            int userId) {
13233        final PackageRemovedInfo info = new PackageRemovedInfo();
13234        info.removedPackage = packageName;
13235        info.removedUsers = new int[] {userId};
13236        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13237        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13238    }
13239
13240    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13241        if (pkgList.length > 0) {
13242            Bundle extras = new Bundle(1);
13243            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13244
13245            sendPackageBroadcast(
13246                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13247                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13248                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13249                    new int[] {userId});
13250        }
13251    }
13252
13253    /**
13254     * Returns true if application is not found or there was an error. Otherwise it returns
13255     * the hidden state of the package for the given user.
13256     */
13257    @Override
13258    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13259        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13260        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13261                true /* requireFullPermission */, false /* checkShell */,
13262                "getApplicationHidden for user " + userId);
13263        PackageSetting pkgSetting;
13264        long callingId = Binder.clearCallingIdentity();
13265        try {
13266            // writer
13267            synchronized (mPackages) {
13268                pkgSetting = mSettings.mPackages.get(packageName);
13269                if (pkgSetting == null) {
13270                    return true;
13271                }
13272                return pkgSetting.getHidden(userId);
13273            }
13274        } finally {
13275            Binder.restoreCallingIdentity(callingId);
13276        }
13277    }
13278
13279    /**
13280     * @hide
13281     */
13282    @Override
13283    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13284            int installReason) {
13285        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13286                null);
13287        PackageSetting pkgSetting;
13288        final int uid = Binder.getCallingUid();
13289        enforceCrossUserPermission(uid, userId,
13290                true /* requireFullPermission */, true /* checkShell */,
13291                "installExistingPackage for user " + userId);
13292        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13293            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13294        }
13295
13296        long callingId = Binder.clearCallingIdentity();
13297        try {
13298            boolean installed = false;
13299            final boolean instantApp =
13300                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13301            final boolean fullApp =
13302                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13303
13304            // writer
13305            synchronized (mPackages) {
13306                pkgSetting = mSettings.mPackages.get(packageName);
13307                if (pkgSetting == null) {
13308                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13309                }
13310                if (!pkgSetting.getInstalled(userId)) {
13311                    pkgSetting.setInstalled(true, userId);
13312                    pkgSetting.setHidden(false, userId);
13313                    pkgSetting.setInstallReason(installReason, userId);
13314                    mSettings.writePackageRestrictionsLPr(userId);
13315                    mSettings.writeKernelMappingLPr(pkgSetting);
13316                    installed = true;
13317                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13318                    // upgrade app from instant to full; we don't allow app downgrade
13319                    installed = true;
13320                }
13321                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13322            }
13323
13324            if (installed) {
13325                if (pkgSetting.pkg != null) {
13326                    synchronized (mInstallLock) {
13327                        // We don't need to freeze for a brand new install
13328                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13329                    }
13330                }
13331                sendPackageAddedForUser(packageName, pkgSetting, userId);
13332                synchronized (mPackages) {
13333                    updateSequenceNumberLP(packageName, new int[]{ userId });
13334                }
13335            }
13336        } finally {
13337            Binder.restoreCallingIdentity(callingId);
13338        }
13339
13340        return PackageManager.INSTALL_SUCCEEDED;
13341    }
13342
13343    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13344            boolean instantApp, boolean fullApp) {
13345        // no state specified; do nothing
13346        if (!instantApp && !fullApp) {
13347            return;
13348        }
13349        if (userId != UserHandle.USER_ALL) {
13350            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13351                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13352            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13353                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13354            }
13355        } else {
13356            for (int currentUserId : sUserManager.getUserIds()) {
13357                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13358                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13359                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13360                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13361                }
13362            }
13363        }
13364    }
13365
13366    boolean isUserRestricted(int userId, String restrictionKey) {
13367        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13368        if (restrictions.getBoolean(restrictionKey, false)) {
13369            Log.w(TAG, "User is restricted: " + restrictionKey);
13370            return true;
13371        }
13372        return false;
13373    }
13374
13375    @Override
13376    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13377            int userId) {
13378        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13379        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13380                true /* requireFullPermission */, true /* checkShell */,
13381                "setPackagesSuspended for user " + userId);
13382
13383        if (ArrayUtils.isEmpty(packageNames)) {
13384            return packageNames;
13385        }
13386
13387        // List of package names for whom the suspended state has changed.
13388        List<String> changedPackages = new ArrayList<>(packageNames.length);
13389        // List of package names for whom the suspended state is not set as requested in this
13390        // method.
13391        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13392        long callingId = Binder.clearCallingIdentity();
13393        try {
13394            for (int i = 0; i < packageNames.length; i++) {
13395                String packageName = packageNames[i];
13396                boolean changed = false;
13397                final int appId;
13398                synchronized (mPackages) {
13399                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13400                    if (pkgSetting == null) {
13401                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13402                                + "\". Skipping suspending/un-suspending.");
13403                        unactionedPackages.add(packageName);
13404                        continue;
13405                    }
13406                    appId = pkgSetting.appId;
13407                    if (pkgSetting.getSuspended(userId) != suspended) {
13408                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13409                            unactionedPackages.add(packageName);
13410                            continue;
13411                        }
13412                        pkgSetting.setSuspended(suspended, userId);
13413                        mSettings.writePackageRestrictionsLPr(userId);
13414                        changed = true;
13415                        changedPackages.add(packageName);
13416                    }
13417                }
13418
13419                if (changed && suspended) {
13420                    killApplication(packageName, UserHandle.getUid(userId, appId),
13421                            "suspending package");
13422                }
13423            }
13424        } finally {
13425            Binder.restoreCallingIdentity(callingId);
13426        }
13427
13428        if (!changedPackages.isEmpty()) {
13429            sendPackagesSuspendedForUser(changedPackages.toArray(
13430                    new String[changedPackages.size()]), userId, suspended);
13431        }
13432
13433        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13434    }
13435
13436    @Override
13437    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13438        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13439                true /* requireFullPermission */, false /* checkShell */,
13440                "isPackageSuspendedForUser for user " + userId);
13441        synchronized (mPackages) {
13442            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13443            if (pkgSetting == null) {
13444                throw new IllegalArgumentException("Unknown target package: " + packageName);
13445            }
13446            return pkgSetting.getSuspended(userId);
13447        }
13448    }
13449
13450    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13451        if (isPackageDeviceAdmin(packageName, userId)) {
13452            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13453                    + "\": has an active device admin");
13454            return false;
13455        }
13456
13457        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13458        if (packageName.equals(activeLauncherPackageName)) {
13459            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13460                    + "\": contains the active launcher");
13461            return false;
13462        }
13463
13464        if (packageName.equals(mRequiredInstallerPackage)) {
13465            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13466                    + "\": required for package installation");
13467            return false;
13468        }
13469
13470        if (packageName.equals(mRequiredUninstallerPackage)) {
13471            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13472                    + "\": required for package uninstallation");
13473            return false;
13474        }
13475
13476        if (packageName.equals(mRequiredVerifierPackage)) {
13477            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13478                    + "\": required for package verification");
13479            return false;
13480        }
13481
13482        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13483            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13484                    + "\": is the default dialer");
13485            return false;
13486        }
13487
13488        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13489            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13490                    + "\": protected package");
13491            return false;
13492        }
13493
13494        // Cannot suspend static shared libs as they are considered
13495        // a part of the using app (emulating static linking). Also
13496        // static libs are installed always on internal storage.
13497        PackageParser.Package pkg = mPackages.get(packageName);
13498        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13499            Slog.w(TAG, "Cannot suspend package: " + packageName
13500                    + " providing static shared library: "
13501                    + pkg.staticSharedLibName);
13502            return false;
13503        }
13504
13505        return true;
13506    }
13507
13508    private String getActiveLauncherPackageName(int userId) {
13509        Intent intent = new Intent(Intent.ACTION_MAIN);
13510        intent.addCategory(Intent.CATEGORY_HOME);
13511        ResolveInfo resolveInfo = resolveIntent(
13512                intent,
13513                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13514                PackageManager.MATCH_DEFAULT_ONLY,
13515                userId);
13516
13517        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13518    }
13519
13520    private String getDefaultDialerPackageName(int userId) {
13521        synchronized (mPackages) {
13522            return mSettings.getDefaultDialerPackageNameLPw(userId);
13523        }
13524    }
13525
13526    @Override
13527    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13528        mContext.enforceCallingOrSelfPermission(
13529                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13530                "Only package verification agents can verify applications");
13531
13532        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13533        final PackageVerificationResponse response = new PackageVerificationResponse(
13534                verificationCode, Binder.getCallingUid());
13535        msg.arg1 = id;
13536        msg.obj = response;
13537        mHandler.sendMessage(msg);
13538    }
13539
13540    @Override
13541    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13542            long millisecondsToDelay) {
13543        mContext.enforceCallingOrSelfPermission(
13544                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13545                "Only package verification agents can extend verification timeouts");
13546
13547        final PackageVerificationState state = mPendingVerification.get(id);
13548        final PackageVerificationResponse response = new PackageVerificationResponse(
13549                verificationCodeAtTimeout, Binder.getCallingUid());
13550
13551        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13552            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13553        }
13554        if (millisecondsToDelay < 0) {
13555            millisecondsToDelay = 0;
13556        }
13557        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13558                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13559            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13560        }
13561
13562        if ((state != null) && !state.timeoutExtended()) {
13563            state.extendTimeout();
13564
13565            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13566            msg.arg1 = id;
13567            msg.obj = response;
13568            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13569        }
13570    }
13571
13572    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13573            int verificationCode, UserHandle user) {
13574        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13575        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13576        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13577        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13578        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13579
13580        mContext.sendBroadcastAsUser(intent, user,
13581                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13582    }
13583
13584    private ComponentName matchComponentForVerifier(String packageName,
13585            List<ResolveInfo> receivers) {
13586        ActivityInfo targetReceiver = null;
13587
13588        final int NR = receivers.size();
13589        for (int i = 0; i < NR; i++) {
13590            final ResolveInfo info = receivers.get(i);
13591            if (info.activityInfo == null) {
13592                continue;
13593            }
13594
13595            if (packageName.equals(info.activityInfo.packageName)) {
13596                targetReceiver = info.activityInfo;
13597                break;
13598            }
13599        }
13600
13601        if (targetReceiver == null) {
13602            return null;
13603        }
13604
13605        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13606    }
13607
13608    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13609            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13610        if (pkgInfo.verifiers.length == 0) {
13611            return null;
13612        }
13613
13614        final int N = pkgInfo.verifiers.length;
13615        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13616        for (int i = 0; i < N; i++) {
13617            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13618
13619            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13620                    receivers);
13621            if (comp == null) {
13622                continue;
13623            }
13624
13625            final int verifierUid = getUidForVerifier(verifierInfo);
13626            if (verifierUid == -1) {
13627                continue;
13628            }
13629
13630            if (DEBUG_VERIFY) {
13631                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13632                        + " with the correct signature");
13633            }
13634            sufficientVerifiers.add(comp);
13635            verificationState.addSufficientVerifier(verifierUid);
13636        }
13637
13638        return sufficientVerifiers;
13639    }
13640
13641    private int getUidForVerifier(VerifierInfo verifierInfo) {
13642        synchronized (mPackages) {
13643            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13644            if (pkg == null) {
13645                return -1;
13646            } else if (pkg.mSignatures.length != 1) {
13647                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13648                        + " has more than one signature; ignoring");
13649                return -1;
13650            }
13651
13652            /*
13653             * If the public key of the package's signature does not match
13654             * our expected public key, then this is a different package and
13655             * we should skip.
13656             */
13657
13658            final byte[] expectedPublicKey;
13659            try {
13660                final Signature verifierSig = pkg.mSignatures[0];
13661                final PublicKey publicKey = verifierSig.getPublicKey();
13662                expectedPublicKey = publicKey.getEncoded();
13663            } catch (CertificateException e) {
13664                return -1;
13665            }
13666
13667            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13668
13669            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13670                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13671                        + " does not have the expected public key; ignoring");
13672                return -1;
13673            }
13674
13675            return pkg.applicationInfo.uid;
13676        }
13677    }
13678
13679    @Override
13680    public void finishPackageInstall(int token, boolean didLaunch) {
13681        enforceSystemOrRoot("Only the system is allowed to finish installs");
13682
13683        if (DEBUG_INSTALL) {
13684            Slog.v(TAG, "BM finishing package install for " + token);
13685        }
13686        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13687
13688        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13689        mHandler.sendMessage(msg);
13690    }
13691
13692    /**
13693     * Get the verification agent timeout.
13694     *
13695     * @return verification timeout in milliseconds
13696     */
13697    private long getVerificationTimeout() {
13698        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13699                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13700                DEFAULT_VERIFICATION_TIMEOUT);
13701    }
13702
13703    /**
13704     * Get the default verification agent response code.
13705     *
13706     * @return default verification response code
13707     */
13708    private int getDefaultVerificationResponse() {
13709        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13710                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13711                DEFAULT_VERIFICATION_RESPONSE);
13712    }
13713
13714    /**
13715     * Check whether or not package verification has been enabled.
13716     *
13717     * @return true if verification should be performed
13718     */
13719    private boolean isVerificationEnabled(int userId, int installFlags) {
13720        if (!DEFAULT_VERIFY_ENABLE) {
13721            return false;
13722        }
13723
13724        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13725
13726        // Check if installing from ADB
13727        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13728            // Do not run verification in a test harness environment
13729            if (ActivityManager.isRunningInTestHarness()) {
13730                return false;
13731            }
13732            if (ensureVerifyAppsEnabled) {
13733                return true;
13734            }
13735            // Check if the developer does not want package verification for ADB installs
13736            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13737                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13738                return false;
13739            }
13740        }
13741
13742        if (ensureVerifyAppsEnabled) {
13743            return true;
13744        }
13745
13746        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13747                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13748    }
13749
13750    @Override
13751    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13752            throws RemoteException {
13753        mContext.enforceCallingOrSelfPermission(
13754                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13755                "Only intentfilter verification agents can verify applications");
13756
13757        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13758        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13759                Binder.getCallingUid(), verificationCode, failedDomains);
13760        msg.arg1 = id;
13761        msg.obj = response;
13762        mHandler.sendMessage(msg);
13763    }
13764
13765    @Override
13766    public int getIntentVerificationStatus(String packageName, int userId) {
13767        synchronized (mPackages) {
13768            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13769        }
13770    }
13771
13772    @Override
13773    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13774        mContext.enforceCallingOrSelfPermission(
13775                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13776
13777        boolean result = false;
13778        synchronized (mPackages) {
13779            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13780        }
13781        if (result) {
13782            scheduleWritePackageRestrictionsLocked(userId);
13783        }
13784        return result;
13785    }
13786
13787    @Override
13788    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13789            String packageName) {
13790        synchronized (mPackages) {
13791            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13792        }
13793    }
13794
13795    @Override
13796    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13797        if (TextUtils.isEmpty(packageName)) {
13798            return ParceledListSlice.emptyList();
13799        }
13800        synchronized (mPackages) {
13801            PackageParser.Package pkg = mPackages.get(packageName);
13802            if (pkg == null || pkg.activities == null) {
13803                return ParceledListSlice.emptyList();
13804            }
13805            final int count = pkg.activities.size();
13806            ArrayList<IntentFilter> result = new ArrayList<>();
13807            for (int n=0; n<count; n++) {
13808                PackageParser.Activity activity = pkg.activities.get(n);
13809                if (activity.intents != null && activity.intents.size() > 0) {
13810                    result.addAll(activity.intents);
13811                }
13812            }
13813            return new ParceledListSlice<>(result);
13814        }
13815    }
13816
13817    @Override
13818    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13819        mContext.enforceCallingOrSelfPermission(
13820                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13821
13822        synchronized (mPackages) {
13823            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13824            if (packageName != null) {
13825                result |= updateIntentVerificationStatus(packageName,
13826                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
13827                        userId);
13828                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
13829                        packageName, userId);
13830            }
13831            return result;
13832        }
13833    }
13834
13835    @Override
13836    public String getDefaultBrowserPackageName(int userId) {
13837        synchronized (mPackages) {
13838            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13839        }
13840    }
13841
13842    /**
13843     * Get the "allow unknown sources" setting.
13844     *
13845     * @return the current "allow unknown sources" setting
13846     */
13847    private int getUnknownSourcesSettings() {
13848        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13849                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13850                -1);
13851    }
13852
13853    @Override
13854    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13855        final int uid = Binder.getCallingUid();
13856        // writer
13857        synchronized (mPackages) {
13858            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13859            if (targetPackageSetting == null) {
13860                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13861            }
13862
13863            PackageSetting installerPackageSetting;
13864            if (installerPackageName != null) {
13865                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13866                if (installerPackageSetting == null) {
13867                    throw new IllegalArgumentException("Unknown installer package: "
13868                            + installerPackageName);
13869                }
13870            } else {
13871                installerPackageSetting = null;
13872            }
13873
13874            Signature[] callerSignature;
13875            Object obj = mSettings.getUserIdLPr(uid);
13876            if (obj != null) {
13877                if (obj instanceof SharedUserSetting) {
13878                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13879                } else if (obj instanceof PackageSetting) {
13880                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
13881                } else {
13882                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
13883                }
13884            } else {
13885                throw new SecurityException("Unknown calling UID: " + uid);
13886            }
13887
13888            // Verify: can't set installerPackageName to a package that is
13889            // not signed with the same cert as the caller.
13890            if (installerPackageSetting != null) {
13891                if (compareSignatures(callerSignature,
13892                        installerPackageSetting.signatures.mSignatures)
13893                        != PackageManager.SIGNATURE_MATCH) {
13894                    throw new SecurityException(
13895                            "Caller does not have same cert as new installer package "
13896                            + installerPackageName);
13897                }
13898            }
13899
13900            // Verify: if target already has an installer package, it must
13901            // be signed with the same cert as the caller.
13902            if (targetPackageSetting.installerPackageName != null) {
13903                PackageSetting setting = mSettings.mPackages.get(
13904                        targetPackageSetting.installerPackageName);
13905                // If the currently set package isn't valid, then it's always
13906                // okay to change it.
13907                if (setting != null) {
13908                    if (compareSignatures(callerSignature,
13909                            setting.signatures.mSignatures)
13910                            != PackageManager.SIGNATURE_MATCH) {
13911                        throw new SecurityException(
13912                                "Caller does not have same cert as old installer package "
13913                                + targetPackageSetting.installerPackageName);
13914                    }
13915                }
13916            }
13917
13918            // Okay!
13919            targetPackageSetting.installerPackageName = installerPackageName;
13920            if (installerPackageName != null) {
13921                mSettings.mInstallerPackages.add(installerPackageName);
13922            }
13923            scheduleWriteSettingsLocked();
13924        }
13925    }
13926
13927    @Override
13928    public void setApplicationCategoryHint(String packageName, int categoryHint,
13929            String callerPackageName) {
13930        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
13931                callerPackageName);
13932        synchronized (mPackages) {
13933            PackageSetting ps = mSettings.mPackages.get(packageName);
13934            if (ps == null) {
13935                throw new IllegalArgumentException("Unknown target package " + packageName);
13936            }
13937
13938            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
13939                throw new IllegalArgumentException("Calling package " + callerPackageName
13940                        + " is not installer for " + packageName);
13941            }
13942
13943            if (ps.categoryHint != categoryHint) {
13944                ps.categoryHint = categoryHint;
13945                scheduleWriteSettingsLocked();
13946            }
13947        }
13948    }
13949
13950    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
13951        // Queue up an async operation since the package installation may take a little while.
13952        mHandler.post(new Runnable() {
13953            public void run() {
13954                mHandler.removeCallbacks(this);
13955                 // Result object to be returned
13956                PackageInstalledInfo res = new PackageInstalledInfo();
13957                res.setReturnCode(currentStatus);
13958                res.uid = -1;
13959                res.pkg = null;
13960                res.removedInfo = null;
13961                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13962                    args.doPreInstall(res.returnCode);
13963                    synchronized (mInstallLock) {
13964                        installPackageTracedLI(args, res);
13965                    }
13966                    args.doPostInstall(res.returnCode, res.uid);
13967                }
13968
13969                // A restore should be performed at this point if (a) the install
13970                // succeeded, (b) the operation is not an update, and (c) the new
13971                // package has not opted out of backup participation.
13972                final boolean update = res.removedInfo != null
13973                        && res.removedInfo.removedPackage != null;
13974                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
13975                boolean doRestore = !update
13976                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
13977
13978                // Set up the post-install work request bookkeeping.  This will be used
13979                // and cleaned up by the post-install event handling regardless of whether
13980                // there's a restore pass performed.  Token values are >= 1.
13981                int token;
13982                if (mNextInstallToken < 0) mNextInstallToken = 1;
13983                token = mNextInstallToken++;
13984
13985                PostInstallData data = new PostInstallData(args, res);
13986                mRunningInstalls.put(token, data);
13987                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
13988
13989                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
13990                    // Pass responsibility to the Backup Manager.  It will perform a
13991                    // restore if appropriate, then pass responsibility back to the
13992                    // Package Manager to run the post-install observer callbacks
13993                    // and broadcasts.
13994                    IBackupManager bm = IBackupManager.Stub.asInterface(
13995                            ServiceManager.getService(Context.BACKUP_SERVICE));
13996                    if (bm != null) {
13997                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
13998                                + " to BM for possible restore");
13999                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14000                        try {
14001                            // TODO: http://b/22388012
14002                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14003                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14004                            } else {
14005                                doRestore = false;
14006                            }
14007                        } catch (RemoteException e) {
14008                            // can't happen; the backup manager is local
14009                        } catch (Exception e) {
14010                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14011                            doRestore = false;
14012                        }
14013                    } else {
14014                        Slog.e(TAG, "Backup Manager not found!");
14015                        doRestore = false;
14016                    }
14017                }
14018
14019                if (!doRestore) {
14020                    // No restore possible, or the Backup Manager was mysteriously not
14021                    // available -- just fire the post-install work request directly.
14022                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14023
14024                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14025
14026                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14027                    mHandler.sendMessage(msg);
14028                }
14029            }
14030        });
14031    }
14032
14033    /**
14034     * Callback from PackageSettings whenever an app is first transitioned out of the
14035     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14036     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14037     * here whether the app is the target of an ongoing install, and only send the
14038     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14039     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14040     * handling.
14041     */
14042    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
14043        // Serialize this with the rest of the install-process message chain.  In the
14044        // restore-at-install case, this Runnable will necessarily run before the
14045        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14046        // are coherent.  In the non-restore case, the app has already completed install
14047        // and been launched through some other means, so it is not in a problematic
14048        // state for observers to see the FIRST_LAUNCH signal.
14049        mHandler.post(new Runnable() {
14050            @Override
14051            public void run() {
14052                for (int i = 0; i < mRunningInstalls.size(); i++) {
14053                    final PostInstallData data = mRunningInstalls.valueAt(i);
14054                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14055                        continue;
14056                    }
14057                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
14058                        // right package; but is it for the right user?
14059                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14060                            if (userId == data.res.newUsers[uIndex]) {
14061                                if (DEBUG_BACKUP) {
14062                                    Slog.i(TAG, "Package " + pkgName
14063                                            + " being restored so deferring FIRST_LAUNCH");
14064                                }
14065                                return;
14066                            }
14067                        }
14068                    }
14069                }
14070                // didn't find it, so not being restored
14071                if (DEBUG_BACKUP) {
14072                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
14073                }
14074                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
14075            }
14076        });
14077    }
14078
14079    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
14080        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14081                installerPkg, null, userIds);
14082    }
14083
14084    private abstract class HandlerParams {
14085        private static final int MAX_RETRIES = 4;
14086
14087        /**
14088         * Number of times startCopy() has been attempted and had a non-fatal
14089         * error.
14090         */
14091        private int mRetries = 0;
14092
14093        /** User handle for the user requesting the information or installation. */
14094        private final UserHandle mUser;
14095        String traceMethod;
14096        int traceCookie;
14097
14098        HandlerParams(UserHandle user) {
14099            mUser = user;
14100        }
14101
14102        UserHandle getUser() {
14103            return mUser;
14104        }
14105
14106        HandlerParams setTraceMethod(String traceMethod) {
14107            this.traceMethod = traceMethod;
14108            return this;
14109        }
14110
14111        HandlerParams setTraceCookie(int traceCookie) {
14112            this.traceCookie = traceCookie;
14113            return this;
14114        }
14115
14116        final boolean startCopy() {
14117            boolean res;
14118            try {
14119                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14120
14121                if (++mRetries > MAX_RETRIES) {
14122                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14123                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14124                    handleServiceError();
14125                    return false;
14126                } else {
14127                    handleStartCopy();
14128                    res = true;
14129                }
14130            } catch (RemoteException e) {
14131                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14132                mHandler.sendEmptyMessage(MCS_RECONNECT);
14133                res = false;
14134            }
14135            handleReturnCode();
14136            return res;
14137        }
14138
14139        final void serviceError() {
14140            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14141            handleServiceError();
14142            handleReturnCode();
14143        }
14144
14145        abstract void handleStartCopy() throws RemoteException;
14146        abstract void handleServiceError();
14147        abstract void handleReturnCode();
14148    }
14149
14150    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14151        for (File path : paths) {
14152            try {
14153                mcs.clearDirectory(path.getAbsolutePath());
14154            } catch (RemoteException e) {
14155            }
14156        }
14157    }
14158
14159    static class OriginInfo {
14160        /**
14161         * Location where install is coming from, before it has been
14162         * copied/renamed into place. This could be a single monolithic APK
14163         * file, or a cluster directory. This location may be untrusted.
14164         */
14165        final File file;
14166        final String cid;
14167
14168        /**
14169         * Flag indicating that {@link #file} or {@link #cid} has already been
14170         * staged, meaning downstream users don't need to defensively copy the
14171         * contents.
14172         */
14173        final boolean staged;
14174
14175        /**
14176         * Flag indicating that {@link #file} or {@link #cid} is an already
14177         * installed app that is being moved.
14178         */
14179        final boolean existing;
14180
14181        final String resolvedPath;
14182        final File resolvedFile;
14183
14184        static OriginInfo fromNothing() {
14185            return new OriginInfo(null, null, false, false);
14186        }
14187
14188        static OriginInfo fromUntrustedFile(File file) {
14189            return new OriginInfo(file, null, false, false);
14190        }
14191
14192        static OriginInfo fromExistingFile(File file) {
14193            return new OriginInfo(file, null, false, true);
14194        }
14195
14196        static OriginInfo fromStagedFile(File file) {
14197            return new OriginInfo(file, null, true, false);
14198        }
14199
14200        static OriginInfo fromStagedContainer(String cid) {
14201            return new OriginInfo(null, cid, true, false);
14202        }
14203
14204        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14205            this.file = file;
14206            this.cid = cid;
14207            this.staged = staged;
14208            this.existing = existing;
14209
14210            if (cid != null) {
14211                resolvedPath = PackageHelper.getSdDir(cid);
14212                resolvedFile = new File(resolvedPath);
14213            } else if (file != null) {
14214                resolvedPath = file.getAbsolutePath();
14215                resolvedFile = file;
14216            } else {
14217                resolvedPath = null;
14218                resolvedFile = null;
14219            }
14220        }
14221    }
14222
14223    static class MoveInfo {
14224        final int moveId;
14225        final String fromUuid;
14226        final String toUuid;
14227        final String packageName;
14228        final String dataAppName;
14229        final int appId;
14230        final String seinfo;
14231        final int targetSdkVersion;
14232
14233        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14234                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14235            this.moveId = moveId;
14236            this.fromUuid = fromUuid;
14237            this.toUuid = toUuid;
14238            this.packageName = packageName;
14239            this.dataAppName = dataAppName;
14240            this.appId = appId;
14241            this.seinfo = seinfo;
14242            this.targetSdkVersion = targetSdkVersion;
14243        }
14244    }
14245
14246    static class VerificationInfo {
14247        /** A constant used to indicate that a uid value is not present. */
14248        public static final int NO_UID = -1;
14249
14250        /** URI referencing where the package was downloaded from. */
14251        final Uri originatingUri;
14252
14253        /** HTTP referrer URI associated with the originatingURI. */
14254        final Uri referrer;
14255
14256        /** UID of the application that the install request originated from. */
14257        final int originatingUid;
14258
14259        /** UID of application requesting the install */
14260        final int installerUid;
14261
14262        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14263            this.originatingUri = originatingUri;
14264            this.referrer = referrer;
14265            this.originatingUid = originatingUid;
14266            this.installerUid = installerUid;
14267        }
14268    }
14269
14270    class InstallParams extends HandlerParams {
14271        final OriginInfo origin;
14272        final MoveInfo move;
14273        final IPackageInstallObserver2 observer;
14274        int installFlags;
14275        final String installerPackageName;
14276        final String volumeUuid;
14277        private InstallArgs mArgs;
14278        private int mRet;
14279        final String packageAbiOverride;
14280        final String[] grantedRuntimePermissions;
14281        final VerificationInfo verificationInfo;
14282        final Certificate[][] certificates;
14283        final int installReason;
14284
14285        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14286                int installFlags, String installerPackageName, String volumeUuid,
14287                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14288                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14289            super(user);
14290            this.origin = origin;
14291            this.move = move;
14292            this.observer = observer;
14293            this.installFlags = installFlags;
14294            this.installerPackageName = installerPackageName;
14295            this.volumeUuid = volumeUuid;
14296            this.verificationInfo = verificationInfo;
14297            this.packageAbiOverride = packageAbiOverride;
14298            this.grantedRuntimePermissions = grantedPermissions;
14299            this.certificates = certificates;
14300            this.installReason = installReason;
14301        }
14302
14303        @Override
14304        public String toString() {
14305            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14306                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14307        }
14308
14309        private int installLocationPolicy(PackageInfoLite pkgLite) {
14310            String packageName = pkgLite.packageName;
14311            int installLocation = pkgLite.installLocation;
14312            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14313            // reader
14314            synchronized (mPackages) {
14315                // Currently installed package which the new package is attempting to replace or
14316                // null if no such package is installed.
14317                PackageParser.Package installedPkg = mPackages.get(packageName);
14318                // Package which currently owns the data which the new package will own if installed.
14319                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14320                // will be null whereas dataOwnerPkg will contain information about the package
14321                // which was uninstalled while keeping its data.
14322                PackageParser.Package dataOwnerPkg = installedPkg;
14323                if (dataOwnerPkg  == null) {
14324                    PackageSetting ps = mSettings.mPackages.get(packageName);
14325                    if (ps != null) {
14326                        dataOwnerPkg = ps.pkg;
14327                    }
14328                }
14329
14330                if (dataOwnerPkg != null) {
14331                    // If installed, the package will get access to data left on the device by its
14332                    // predecessor. As a security measure, this is permited only if this is not a
14333                    // version downgrade or if the predecessor package is marked as debuggable and
14334                    // a downgrade is explicitly requested.
14335                    //
14336                    // On debuggable platform builds, downgrades are permitted even for
14337                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14338                    // not offer security guarantees and thus it's OK to disable some security
14339                    // mechanisms to make debugging/testing easier on those builds. However, even on
14340                    // debuggable builds downgrades of packages are permitted only if requested via
14341                    // installFlags. This is because we aim to keep the behavior of debuggable
14342                    // platform builds as close as possible to the behavior of non-debuggable
14343                    // platform builds.
14344                    final boolean downgradeRequested =
14345                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14346                    final boolean packageDebuggable =
14347                                (dataOwnerPkg.applicationInfo.flags
14348                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14349                    final boolean downgradePermitted =
14350                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14351                    if (!downgradePermitted) {
14352                        try {
14353                            checkDowngrade(dataOwnerPkg, pkgLite);
14354                        } catch (PackageManagerException e) {
14355                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14356                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14357                        }
14358                    }
14359                }
14360
14361                if (installedPkg != null) {
14362                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14363                        // Check for updated system application.
14364                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14365                            if (onSd) {
14366                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14367                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14368                            }
14369                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14370                        } else {
14371                            if (onSd) {
14372                                // Install flag overrides everything.
14373                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14374                            }
14375                            // If current upgrade specifies particular preference
14376                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14377                                // Application explicitly specified internal.
14378                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14379                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14380                                // App explictly prefers external. Let policy decide
14381                            } else {
14382                                // Prefer previous location
14383                                if (isExternal(installedPkg)) {
14384                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14385                                }
14386                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14387                            }
14388                        }
14389                    } else {
14390                        // Invalid install. Return error code
14391                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14392                    }
14393                }
14394            }
14395            // All the special cases have been taken care of.
14396            // Return result based on recommended install location.
14397            if (onSd) {
14398                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14399            }
14400            return pkgLite.recommendedInstallLocation;
14401        }
14402
14403        /*
14404         * Invoke remote method to get package information and install
14405         * location values. Override install location based on default
14406         * policy if needed and then create install arguments based
14407         * on the install location.
14408         */
14409        public void handleStartCopy() throws RemoteException {
14410            int ret = PackageManager.INSTALL_SUCCEEDED;
14411
14412            // If we're already staged, we've firmly committed to an install location
14413            if (origin.staged) {
14414                if (origin.file != null) {
14415                    installFlags |= PackageManager.INSTALL_INTERNAL;
14416                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14417                } else if (origin.cid != null) {
14418                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14419                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14420                } else {
14421                    throw new IllegalStateException("Invalid stage location");
14422                }
14423            }
14424
14425            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14426            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14427            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14428            PackageInfoLite pkgLite = null;
14429
14430            if (onInt && onSd) {
14431                // Check if both bits are set.
14432                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14433                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14434            } else if (onSd && ephemeral) {
14435                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14436                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14437            } else {
14438                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14439                        packageAbiOverride);
14440
14441                if (DEBUG_EPHEMERAL && ephemeral) {
14442                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14443                }
14444
14445                /*
14446                 * If we have too little free space, try to free cache
14447                 * before giving up.
14448                 */
14449                if (!origin.staged && pkgLite.recommendedInstallLocation
14450                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14451                    // TODO: focus freeing disk space on the target device
14452                    final StorageManager storage = StorageManager.from(mContext);
14453                    final long lowThreshold = storage.getStorageLowBytes(
14454                            Environment.getDataDirectory());
14455
14456                    final long sizeBytes = mContainerService.calculateInstalledSize(
14457                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14458
14459                    try {
14460                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14461                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14462                                installFlags, packageAbiOverride);
14463                    } catch (InstallerException e) {
14464                        Slog.w(TAG, "Failed to free cache", e);
14465                    }
14466
14467                    /*
14468                     * The cache free must have deleted the file we
14469                     * downloaded to install.
14470                     *
14471                     * TODO: fix the "freeCache" call to not delete
14472                     *       the file we care about.
14473                     */
14474                    if (pkgLite.recommendedInstallLocation
14475                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14476                        pkgLite.recommendedInstallLocation
14477                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14478                    }
14479                }
14480            }
14481
14482            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14483                int loc = pkgLite.recommendedInstallLocation;
14484                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14485                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14486                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14487                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14488                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14489                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14490                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14491                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14492                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14493                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14494                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14495                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14496                } else {
14497                    // Override with defaults if needed.
14498                    loc = installLocationPolicy(pkgLite);
14499                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14500                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14501                    } else if (!onSd && !onInt) {
14502                        // Override install location with flags
14503                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14504                            // Set the flag to install on external media.
14505                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14506                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14507                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14508                            if (DEBUG_EPHEMERAL) {
14509                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14510                            }
14511                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
14512                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14513                                    |PackageManager.INSTALL_INTERNAL);
14514                        } else {
14515                            // Make sure the flag for installing on external
14516                            // media is unset
14517                            installFlags |= PackageManager.INSTALL_INTERNAL;
14518                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14519                        }
14520                    }
14521                }
14522            }
14523
14524            final InstallArgs args = createInstallArgs(this);
14525            mArgs = args;
14526
14527            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14528                // TODO: http://b/22976637
14529                // Apps installed for "all" users use the device owner to verify the app
14530                UserHandle verifierUser = getUser();
14531                if (verifierUser == UserHandle.ALL) {
14532                    verifierUser = UserHandle.SYSTEM;
14533                }
14534
14535                /*
14536                 * Determine if we have any installed package verifiers. If we
14537                 * do, then we'll defer to them to verify the packages.
14538                 */
14539                final int requiredUid = mRequiredVerifierPackage == null ? -1
14540                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14541                                verifierUser.getIdentifier());
14542                if (!origin.existing && requiredUid != -1
14543                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
14544                    final Intent verification = new Intent(
14545                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14546                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14547                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14548                            PACKAGE_MIME_TYPE);
14549                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14550
14551                    // Query all live verifiers based on current user state
14552                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14553                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
14554
14555                    if (DEBUG_VERIFY) {
14556                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14557                                + verification.toString() + " with " + pkgLite.verifiers.length
14558                                + " optional verifiers");
14559                    }
14560
14561                    final int verificationId = mPendingVerificationToken++;
14562
14563                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14564
14565                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14566                            installerPackageName);
14567
14568                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14569                            installFlags);
14570
14571                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14572                            pkgLite.packageName);
14573
14574                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14575                            pkgLite.versionCode);
14576
14577                    if (verificationInfo != null) {
14578                        if (verificationInfo.originatingUri != null) {
14579                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14580                                    verificationInfo.originatingUri);
14581                        }
14582                        if (verificationInfo.referrer != null) {
14583                            verification.putExtra(Intent.EXTRA_REFERRER,
14584                                    verificationInfo.referrer);
14585                        }
14586                        if (verificationInfo.originatingUid >= 0) {
14587                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14588                                    verificationInfo.originatingUid);
14589                        }
14590                        if (verificationInfo.installerUid >= 0) {
14591                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14592                                    verificationInfo.installerUid);
14593                        }
14594                    }
14595
14596                    final PackageVerificationState verificationState = new PackageVerificationState(
14597                            requiredUid, args);
14598
14599                    mPendingVerification.append(verificationId, verificationState);
14600
14601                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14602                            receivers, verificationState);
14603
14604                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
14605                    final long idleDuration = getVerificationTimeout();
14606
14607                    /*
14608                     * If any sufficient verifiers were listed in the package
14609                     * manifest, attempt to ask them.
14610                     */
14611                    if (sufficientVerifiers != null) {
14612                        final int N = sufficientVerifiers.size();
14613                        if (N == 0) {
14614                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14615                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14616                        } else {
14617                            for (int i = 0; i < N; i++) {
14618                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14619                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14620                                        verifierComponent.getPackageName(), idleDuration,
14621                                        verifierUser.getIdentifier(), false, "package verifier");
14622
14623                                final Intent sufficientIntent = new Intent(verification);
14624                                sufficientIntent.setComponent(verifierComponent);
14625                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14626                            }
14627                        }
14628                    }
14629
14630                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14631                            mRequiredVerifierPackage, receivers);
14632                    if (ret == PackageManager.INSTALL_SUCCEEDED
14633                            && mRequiredVerifierPackage != null) {
14634                        Trace.asyncTraceBegin(
14635                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14636                        /*
14637                         * Send the intent to the required verification agent,
14638                         * but only start the verification timeout after the
14639                         * target BroadcastReceivers have run.
14640                         */
14641                        verification.setComponent(requiredVerifierComponent);
14642                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
14643                                mRequiredVerifierPackage, idleDuration,
14644                                verifierUser.getIdentifier(), false, "package verifier");
14645                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14646                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14647                                new BroadcastReceiver() {
14648                                    @Override
14649                                    public void onReceive(Context context, Intent intent) {
14650                                        final Message msg = mHandler
14651                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14652                                        msg.arg1 = verificationId;
14653                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14654                                    }
14655                                }, null, 0, null, null);
14656
14657                        /*
14658                         * We don't want the copy to proceed until verification
14659                         * succeeds, so null out this field.
14660                         */
14661                        mArgs = null;
14662                    }
14663                } else {
14664                    /*
14665                     * No package verification is enabled, so immediately start
14666                     * the remote call to initiate copy using temporary file.
14667                     */
14668                    ret = args.copyApk(mContainerService, true);
14669                }
14670            }
14671
14672            mRet = ret;
14673        }
14674
14675        @Override
14676        void handleReturnCode() {
14677            // If mArgs is null, then MCS couldn't be reached. When it
14678            // reconnects, it will try again to install. At that point, this
14679            // will succeed.
14680            if (mArgs != null) {
14681                processPendingInstall(mArgs, mRet);
14682            }
14683        }
14684
14685        @Override
14686        void handleServiceError() {
14687            mArgs = createInstallArgs(this);
14688            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14689        }
14690
14691        public boolean isForwardLocked() {
14692            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14693        }
14694    }
14695
14696    /**
14697     * Used during creation of InstallArgs
14698     *
14699     * @param installFlags package installation flags
14700     * @return true if should be installed on external storage
14701     */
14702    private static boolean installOnExternalAsec(int installFlags) {
14703        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
14704            return false;
14705        }
14706        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14707            return true;
14708        }
14709        return false;
14710    }
14711
14712    /**
14713     * Used during creation of InstallArgs
14714     *
14715     * @param installFlags package installation flags
14716     * @return true if should be installed as forward locked
14717     */
14718    private static boolean installForwardLocked(int installFlags) {
14719        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14720    }
14721
14722    private InstallArgs createInstallArgs(InstallParams params) {
14723        if (params.move != null) {
14724            return new MoveInstallArgs(params);
14725        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
14726            return new AsecInstallArgs(params);
14727        } else {
14728            return new FileInstallArgs(params);
14729        }
14730    }
14731
14732    /**
14733     * Create args that describe an existing installed package. Typically used
14734     * when cleaning up old installs, or used as a move source.
14735     */
14736    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14737            String resourcePath, String[] instructionSets) {
14738        final boolean isInAsec;
14739        if (installOnExternalAsec(installFlags)) {
14740            /* Apps on SD card are always in ASEC containers. */
14741            isInAsec = true;
14742        } else if (installForwardLocked(installFlags)
14743                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
14744            /*
14745             * Forward-locked apps are only in ASEC containers if they're the
14746             * new style
14747             */
14748            isInAsec = true;
14749        } else {
14750            isInAsec = false;
14751        }
14752
14753        if (isInAsec) {
14754            return new AsecInstallArgs(codePath, instructionSets,
14755                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
14756        } else {
14757            return new FileInstallArgs(codePath, resourcePath, instructionSets);
14758        }
14759    }
14760
14761    static abstract class InstallArgs {
14762        /** @see InstallParams#origin */
14763        final OriginInfo origin;
14764        /** @see InstallParams#move */
14765        final MoveInfo move;
14766
14767        final IPackageInstallObserver2 observer;
14768        // Always refers to PackageManager flags only
14769        final int installFlags;
14770        final String installerPackageName;
14771        final String volumeUuid;
14772        final UserHandle user;
14773        final String abiOverride;
14774        final String[] installGrantPermissions;
14775        /** If non-null, drop an async trace when the install completes */
14776        final String traceMethod;
14777        final int traceCookie;
14778        final Certificate[][] certificates;
14779        final int installReason;
14780
14781        // The list of instruction sets supported by this app. This is currently
14782        // only used during the rmdex() phase to clean up resources. We can get rid of this
14783        // if we move dex files under the common app path.
14784        /* nullable */ String[] instructionSets;
14785
14786        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14787                int installFlags, String installerPackageName, String volumeUuid,
14788                UserHandle user, String[] instructionSets,
14789                String abiOverride, String[] installGrantPermissions,
14790                String traceMethod, int traceCookie, Certificate[][] certificates,
14791                int installReason) {
14792            this.origin = origin;
14793            this.move = move;
14794            this.installFlags = installFlags;
14795            this.observer = observer;
14796            this.installerPackageName = installerPackageName;
14797            this.volumeUuid = volumeUuid;
14798            this.user = user;
14799            this.instructionSets = instructionSets;
14800            this.abiOverride = abiOverride;
14801            this.installGrantPermissions = installGrantPermissions;
14802            this.traceMethod = traceMethod;
14803            this.traceCookie = traceCookie;
14804            this.certificates = certificates;
14805            this.installReason = installReason;
14806        }
14807
14808        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14809        abstract int doPreInstall(int status);
14810
14811        /**
14812         * Rename package into final resting place. All paths on the given
14813         * scanned package should be updated to reflect the rename.
14814         */
14815        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14816        abstract int doPostInstall(int status, int uid);
14817
14818        /** @see PackageSettingBase#codePathString */
14819        abstract String getCodePath();
14820        /** @see PackageSettingBase#resourcePathString */
14821        abstract String getResourcePath();
14822
14823        // Need installer lock especially for dex file removal.
14824        abstract void cleanUpResourcesLI();
14825        abstract boolean doPostDeleteLI(boolean delete);
14826
14827        /**
14828         * Called before the source arguments are copied. This is used mostly
14829         * for MoveParams when it needs to read the source file to put it in the
14830         * destination.
14831         */
14832        int doPreCopy() {
14833            return PackageManager.INSTALL_SUCCEEDED;
14834        }
14835
14836        /**
14837         * Called after the source arguments are copied. This is used mostly for
14838         * MoveParams when it needs to read the source file to put it in the
14839         * destination.
14840         */
14841        int doPostCopy(int uid) {
14842            return PackageManager.INSTALL_SUCCEEDED;
14843        }
14844
14845        protected boolean isFwdLocked() {
14846            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14847        }
14848
14849        protected boolean isExternalAsec() {
14850            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14851        }
14852
14853        protected boolean isEphemeral() {
14854            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14855        }
14856
14857        UserHandle getUser() {
14858            return user;
14859        }
14860    }
14861
14862    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14863        if (!allCodePaths.isEmpty()) {
14864            if (instructionSets == null) {
14865                throw new IllegalStateException("instructionSet == null");
14866            }
14867            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14868            for (String codePath : allCodePaths) {
14869                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14870                    try {
14871                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14872                    } catch (InstallerException ignored) {
14873                    }
14874                }
14875            }
14876        }
14877    }
14878
14879    /**
14880     * Logic to handle installation of non-ASEC applications, including copying
14881     * and renaming logic.
14882     */
14883    class FileInstallArgs extends InstallArgs {
14884        private File codeFile;
14885        private File resourceFile;
14886
14887        // Example topology:
14888        // /data/app/com.example/base.apk
14889        // /data/app/com.example/split_foo.apk
14890        // /data/app/com.example/lib/arm/libfoo.so
14891        // /data/app/com.example/lib/arm64/libfoo.so
14892        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
14893
14894        /** New install */
14895        FileInstallArgs(InstallParams params) {
14896            super(params.origin, params.move, params.observer, params.installFlags,
14897                    params.installerPackageName, params.volumeUuid,
14898                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
14899                    params.grantedRuntimePermissions,
14900                    params.traceMethod, params.traceCookie, params.certificates,
14901                    params.installReason);
14902            if (isFwdLocked()) {
14903                throw new IllegalArgumentException("Forward locking only supported in ASEC");
14904            }
14905        }
14906
14907        /** Existing install */
14908        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
14909            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
14910                    null, null, null, 0, null /*certificates*/,
14911                    PackageManager.INSTALL_REASON_UNKNOWN);
14912            this.codeFile = (codePath != null) ? new File(codePath) : null;
14913            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
14914        }
14915
14916        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14917            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
14918            try {
14919                return doCopyApk(imcs, temp);
14920            } finally {
14921                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14922            }
14923        }
14924
14925        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14926            if (origin.staged) {
14927                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
14928                codeFile = origin.file;
14929                resourceFile = origin.file;
14930                return PackageManager.INSTALL_SUCCEEDED;
14931            }
14932
14933            try {
14934                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14935                final File tempDir =
14936                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
14937                codeFile = tempDir;
14938                resourceFile = tempDir;
14939            } catch (IOException e) {
14940                Slog.w(TAG, "Failed to create copy file: " + e);
14941                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14942            }
14943
14944            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
14945                @Override
14946                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
14947                    if (!FileUtils.isValidExtFilename(name)) {
14948                        throw new IllegalArgumentException("Invalid filename: " + name);
14949                    }
14950                    try {
14951                        final File file = new File(codeFile, name);
14952                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
14953                                O_RDWR | O_CREAT, 0644);
14954                        Os.chmod(file.getAbsolutePath(), 0644);
14955                        return new ParcelFileDescriptor(fd);
14956                    } catch (ErrnoException e) {
14957                        throw new RemoteException("Failed to open: " + e.getMessage());
14958                    }
14959                }
14960            };
14961
14962            int ret = PackageManager.INSTALL_SUCCEEDED;
14963            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
14964            if (ret != PackageManager.INSTALL_SUCCEEDED) {
14965                Slog.e(TAG, "Failed to copy package");
14966                return ret;
14967            }
14968
14969            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
14970            NativeLibraryHelper.Handle handle = null;
14971            try {
14972                handle = NativeLibraryHelper.Handle.create(codeFile);
14973                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
14974                        abiOverride);
14975            } catch (IOException e) {
14976                Slog.e(TAG, "Copying native libraries failed", e);
14977                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14978            } finally {
14979                IoUtils.closeQuietly(handle);
14980            }
14981
14982            return ret;
14983        }
14984
14985        int doPreInstall(int status) {
14986            if (status != PackageManager.INSTALL_SUCCEEDED) {
14987                cleanUp();
14988            }
14989            return status;
14990        }
14991
14992        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14993            if (status != PackageManager.INSTALL_SUCCEEDED) {
14994                cleanUp();
14995                return false;
14996            }
14997
14998            final File targetDir = codeFile.getParentFile();
14999            final File beforeCodeFile = codeFile;
15000            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15001
15002            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15003            try {
15004                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15005            } catch (ErrnoException e) {
15006                Slog.w(TAG, "Failed to rename", e);
15007                return false;
15008            }
15009
15010            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15011                Slog.w(TAG, "Failed to restorecon");
15012                return false;
15013            }
15014
15015            // Reflect the rename internally
15016            codeFile = afterCodeFile;
15017            resourceFile = afterCodeFile;
15018
15019            // Reflect the rename in scanned details
15020            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15021            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15022                    afterCodeFile, pkg.baseCodePath));
15023            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15024                    afterCodeFile, pkg.splitCodePaths));
15025
15026            // Reflect the rename in app info
15027            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15028            pkg.setApplicationInfoCodePath(pkg.codePath);
15029            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15030            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15031            pkg.setApplicationInfoResourcePath(pkg.codePath);
15032            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15033            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15034
15035            return true;
15036        }
15037
15038        int doPostInstall(int status, int uid) {
15039            if (status != PackageManager.INSTALL_SUCCEEDED) {
15040                cleanUp();
15041            }
15042            return status;
15043        }
15044
15045        @Override
15046        String getCodePath() {
15047            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15048        }
15049
15050        @Override
15051        String getResourcePath() {
15052            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15053        }
15054
15055        private boolean cleanUp() {
15056            if (codeFile == null || !codeFile.exists()) {
15057                return false;
15058            }
15059
15060            removeCodePathLI(codeFile);
15061
15062            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15063                resourceFile.delete();
15064            }
15065
15066            return true;
15067        }
15068
15069        void cleanUpResourcesLI() {
15070            // Try enumerating all code paths before deleting
15071            List<String> allCodePaths = Collections.EMPTY_LIST;
15072            if (codeFile != null && codeFile.exists()) {
15073                try {
15074                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15075                    allCodePaths = pkg.getAllCodePaths();
15076                } catch (PackageParserException e) {
15077                    // Ignored; we tried our best
15078                }
15079            }
15080
15081            cleanUp();
15082            removeDexFiles(allCodePaths, instructionSets);
15083        }
15084
15085        boolean doPostDeleteLI(boolean delete) {
15086            // XXX err, shouldn't we respect the delete flag?
15087            cleanUpResourcesLI();
15088            return true;
15089        }
15090    }
15091
15092    private boolean isAsecExternal(String cid) {
15093        final String asecPath = PackageHelper.getSdFilesystem(cid);
15094        return !asecPath.startsWith(mAsecInternalPath);
15095    }
15096
15097    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15098            PackageManagerException {
15099        if (copyRet < 0) {
15100            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15101                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15102                throw new PackageManagerException(copyRet, message);
15103            }
15104        }
15105    }
15106
15107    /**
15108     * Extract the StorageManagerService "container ID" from the full code path of an
15109     * .apk.
15110     */
15111    static String cidFromCodePath(String fullCodePath) {
15112        int eidx = fullCodePath.lastIndexOf("/");
15113        String subStr1 = fullCodePath.substring(0, eidx);
15114        int sidx = subStr1.lastIndexOf("/");
15115        return subStr1.substring(sidx+1, eidx);
15116    }
15117
15118    /**
15119     * Logic to handle installation of ASEC applications, including copying and
15120     * renaming logic.
15121     */
15122    class AsecInstallArgs extends InstallArgs {
15123        static final String RES_FILE_NAME = "pkg.apk";
15124        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15125
15126        String cid;
15127        String packagePath;
15128        String resourcePath;
15129
15130        /** New install */
15131        AsecInstallArgs(InstallParams params) {
15132            super(params.origin, params.move, params.observer, params.installFlags,
15133                    params.installerPackageName, params.volumeUuid,
15134                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15135                    params.grantedRuntimePermissions,
15136                    params.traceMethod, params.traceCookie, params.certificates,
15137                    params.installReason);
15138        }
15139
15140        /** Existing install */
15141        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15142                        boolean isExternal, boolean isForwardLocked) {
15143            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15144                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15145                    instructionSets, null, null, null, 0, null /*certificates*/,
15146                    PackageManager.INSTALL_REASON_UNKNOWN);
15147            // Hackily pretend we're still looking at a full code path
15148            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15149                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15150            }
15151
15152            // Extract cid from fullCodePath
15153            int eidx = fullCodePath.lastIndexOf("/");
15154            String subStr1 = fullCodePath.substring(0, eidx);
15155            int sidx = subStr1.lastIndexOf("/");
15156            cid = subStr1.substring(sidx+1, eidx);
15157            setMountPath(subStr1);
15158        }
15159
15160        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15161            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15162                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15163                    instructionSets, null, null, null, 0, null /*certificates*/,
15164                    PackageManager.INSTALL_REASON_UNKNOWN);
15165            this.cid = cid;
15166            setMountPath(PackageHelper.getSdDir(cid));
15167        }
15168
15169        void createCopyFile() {
15170            cid = mInstallerService.allocateExternalStageCidLegacy();
15171        }
15172
15173        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15174            if (origin.staged && origin.cid != null) {
15175                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15176                cid = origin.cid;
15177                setMountPath(PackageHelper.getSdDir(cid));
15178                return PackageManager.INSTALL_SUCCEEDED;
15179            }
15180
15181            if (temp) {
15182                createCopyFile();
15183            } else {
15184                /*
15185                 * Pre-emptively destroy the container since it's destroyed if
15186                 * copying fails due to it existing anyway.
15187                 */
15188                PackageHelper.destroySdDir(cid);
15189            }
15190
15191            final String newMountPath = imcs.copyPackageToContainer(
15192                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15193                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15194
15195            if (newMountPath != null) {
15196                setMountPath(newMountPath);
15197                return PackageManager.INSTALL_SUCCEEDED;
15198            } else {
15199                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15200            }
15201        }
15202
15203        @Override
15204        String getCodePath() {
15205            return packagePath;
15206        }
15207
15208        @Override
15209        String getResourcePath() {
15210            return resourcePath;
15211        }
15212
15213        int doPreInstall(int status) {
15214            if (status != PackageManager.INSTALL_SUCCEEDED) {
15215                // Destroy container
15216                PackageHelper.destroySdDir(cid);
15217            } else {
15218                boolean mounted = PackageHelper.isContainerMounted(cid);
15219                if (!mounted) {
15220                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15221                            Process.SYSTEM_UID);
15222                    if (newMountPath != null) {
15223                        setMountPath(newMountPath);
15224                    } else {
15225                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15226                    }
15227                }
15228            }
15229            return status;
15230        }
15231
15232        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15233            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15234            String newMountPath = null;
15235            if (PackageHelper.isContainerMounted(cid)) {
15236                // Unmount the container
15237                if (!PackageHelper.unMountSdDir(cid)) {
15238                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15239                    return false;
15240                }
15241            }
15242            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15243                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15244                        " which might be stale. Will try to clean up.");
15245                // Clean up the stale container and proceed to recreate.
15246                if (!PackageHelper.destroySdDir(newCacheId)) {
15247                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15248                    return false;
15249                }
15250                // Successfully cleaned up stale container. Try to rename again.
15251                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15252                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15253                            + " inspite of cleaning it up.");
15254                    return false;
15255                }
15256            }
15257            if (!PackageHelper.isContainerMounted(newCacheId)) {
15258                Slog.w(TAG, "Mounting container " + newCacheId);
15259                newMountPath = PackageHelper.mountSdDir(newCacheId,
15260                        getEncryptKey(), Process.SYSTEM_UID);
15261            } else {
15262                newMountPath = PackageHelper.getSdDir(newCacheId);
15263            }
15264            if (newMountPath == null) {
15265                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15266                return false;
15267            }
15268            Log.i(TAG, "Succesfully renamed " + cid +
15269                    " to " + newCacheId +
15270                    " at new path: " + newMountPath);
15271            cid = newCacheId;
15272
15273            final File beforeCodeFile = new File(packagePath);
15274            setMountPath(newMountPath);
15275            final File afterCodeFile = new File(packagePath);
15276
15277            // Reflect the rename in scanned details
15278            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15279            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15280                    afterCodeFile, pkg.baseCodePath));
15281            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15282                    afterCodeFile, pkg.splitCodePaths));
15283
15284            // Reflect the rename in app info
15285            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15286            pkg.setApplicationInfoCodePath(pkg.codePath);
15287            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15288            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15289            pkg.setApplicationInfoResourcePath(pkg.codePath);
15290            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15291            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15292
15293            return true;
15294        }
15295
15296        private void setMountPath(String mountPath) {
15297            final File mountFile = new File(mountPath);
15298
15299            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15300            if (monolithicFile.exists()) {
15301                packagePath = monolithicFile.getAbsolutePath();
15302                if (isFwdLocked()) {
15303                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15304                } else {
15305                    resourcePath = packagePath;
15306                }
15307            } else {
15308                packagePath = mountFile.getAbsolutePath();
15309                resourcePath = packagePath;
15310            }
15311        }
15312
15313        int doPostInstall(int status, int uid) {
15314            if (status != PackageManager.INSTALL_SUCCEEDED) {
15315                cleanUp();
15316            } else {
15317                final int groupOwner;
15318                final String protectedFile;
15319                if (isFwdLocked()) {
15320                    groupOwner = UserHandle.getSharedAppGid(uid);
15321                    protectedFile = RES_FILE_NAME;
15322                } else {
15323                    groupOwner = -1;
15324                    protectedFile = null;
15325                }
15326
15327                if (uid < Process.FIRST_APPLICATION_UID
15328                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15329                    Slog.e(TAG, "Failed to finalize " + cid);
15330                    PackageHelper.destroySdDir(cid);
15331                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15332                }
15333
15334                boolean mounted = PackageHelper.isContainerMounted(cid);
15335                if (!mounted) {
15336                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15337                }
15338            }
15339            return status;
15340        }
15341
15342        private void cleanUp() {
15343            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15344
15345            // Destroy secure container
15346            PackageHelper.destroySdDir(cid);
15347        }
15348
15349        private List<String> getAllCodePaths() {
15350            final File codeFile = new File(getCodePath());
15351            if (codeFile != null && codeFile.exists()) {
15352                try {
15353                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15354                    return pkg.getAllCodePaths();
15355                } catch (PackageParserException e) {
15356                    // Ignored; we tried our best
15357                }
15358            }
15359            return Collections.EMPTY_LIST;
15360        }
15361
15362        void cleanUpResourcesLI() {
15363            // Enumerate all code paths before deleting
15364            cleanUpResourcesLI(getAllCodePaths());
15365        }
15366
15367        private void cleanUpResourcesLI(List<String> allCodePaths) {
15368            cleanUp();
15369            removeDexFiles(allCodePaths, instructionSets);
15370        }
15371
15372        String getPackageName() {
15373            return getAsecPackageName(cid);
15374        }
15375
15376        boolean doPostDeleteLI(boolean delete) {
15377            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15378            final List<String> allCodePaths = getAllCodePaths();
15379            boolean mounted = PackageHelper.isContainerMounted(cid);
15380            if (mounted) {
15381                // Unmount first
15382                if (PackageHelper.unMountSdDir(cid)) {
15383                    mounted = false;
15384                }
15385            }
15386            if (!mounted && delete) {
15387                cleanUpResourcesLI(allCodePaths);
15388            }
15389            return !mounted;
15390        }
15391
15392        @Override
15393        int doPreCopy() {
15394            if (isFwdLocked()) {
15395                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15396                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15397                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15398                }
15399            }
15400
15401            return PackageManager.INSTALL_SUCCEEDED;
15402        }
15403
15404        @Override
15405        int doPostCopy(int uid) {
15406            if (isFwdLocked()) {
15407                if (uid < Process.FIRST_APPLICATION_UID
15408                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15409                                RES_FILE_NAME)) {
15410                    Slog.e(TAG, "Failed to finalize " + cid);
15411                    PackageHelper.destroySdDir(cid);
15412                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15413                }
15414            }
15415
15416            return PackageManager.INSTALL_SUCCEEDED;
15417        }
15418    }
15419
15420    /**
15421     * Logic to handle movement of existing installed applications.
15422     */
15423    class MoveInstallArgs extends InstallArgs {
15424        private File codeFile;
15425        private File resourceFile;
15426
15427        /** New install */
15428        MoveInstallArgs(InstallParams params) {
15429            super(params.origin, params.move, params.observer, params.installFlags,
15430                    params.installerPackageName, params.volumeUuid,
15431                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15432                    params.grantedRuntimePermissions,
15433                    params.traceMethod, params.traceCookie, params.certificates,
15434                    params.installReason);
15435        }
15436
15437        int copyApk(IMediaContainerService imcs, boolean temp) {
15438            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15439                    + move.fromUuid + " to " + move.toUuid);
15440            synchronized (mInstaller) {
15441                try {
15442                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15443                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15444                } catch (InstallerException e) {
15445                    Slog.w(TAG, "Failed to move app", e);
15446                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15447                }
15448            }
15449
15450            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15451            resourceFile = codeFile;
15452            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15453
15454            return PackageManager.INSTALL_SUCCEEDED;
15455        }
15456
15457        int doPreInstall(int status) {
15458            if (status != PackageManager.INSTALL_SUCCEEDED) {
15459                cleanUp(move.toUuid);
15460            }
15461            return status;
15462        }
15463
15464        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15465            if (status != PackageManager.INSTALL_SUCCEEDED) {
15466                cleanUp(move.toUuid);
15467                return false;
15468            }
15469
15470            // Reflect the move in app info
15471            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15472            pkg.setApplicationInfoCodePath(pkg.codePath);
15473            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15474            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15475            pkg.setApplicationInfoResourcePath(pkg.codePath);
15476            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15477            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15478
15479            return true;
15480        }
15481
15482        int doPostInstall(int status, int uid) {
15483            if (status == PackageManager.INSTALL_SUCCEEDED) {
15484                cleanUp(move.fromUuid);
15485            } else {
15486                cleanUp(move.toUuid);
15487            }
15488            return status;
15489        }
15490
15491        @Override
15492        String getCodePath() {
15493            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15494        }
15495
15496        @Override
15497        String getResourcePath() {
15498            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15499        }
15500
15501        private boolean cleanUp(String volumeUuid) {
15502            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15503                    move.dataAppName);
15504            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15505            final int[] userIds = sUserManager.getUserIds();
15506            synchronized (mInstallLock) {
15507                // Clean up both app data and code
15508                // All package moves are frozen until finished
15509                for (int userId : userIds) {
15510                    try {
15511                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15512                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15513                    } catch (InstallerException e) {
15514                        Slog.w(TAG, String.valueOf(e));
15515                    }
15516                }
15517                removeCodePathLI(codeFile);
15518            }
15519            return true;
15520        }
15521
15522        void cleanUpResourcesLI() {
15523            throw new UnsupportedOperationException();
15524        }
15525
15526        boolean doPostDeleteLI(boolean delete) {
15527            throw new UnsupportedOperationException();
15528        }
15529    }
15530
15531    static String getAsecPackageName(String packageCid) {
15532        int idx = packageCid.lastIndexOf("-");
15533        if (idx == -1) {
15534            return packageCid;
15535        }
15536        return packageCid.substring(0, idx);
15537    }
15538
15539    // Utility method used to create code paths based on package name and available index.
15540    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15541        String idxStr = "";
15542        int idx = 1;
15543        // Fall back to default value of idx=1 if prefix is not
15544        // part of oldCodePath
15545        if (oldCodePath != null) {
15546            String subStr = oldCodePath;
15547            // Drop the suffix right away
15548            if (suffix != null && subStr.endsWith(suffix)) {
15549                subStr = subStr.substring(0, subStr.length() - suffix.length());
15550            }
15551            // If oldCodePath already contains prefix find out the
15552            // ending index to either increment or decrement.
15553            int sidx = subStr.lastIndexOf(prefix);
15554            if (sidx != -1) {
15555                subStr = subStr.substring(sidx + prefix.length());
15556                if (subStr != null) {
15557                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15558                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15559                    }
15560                    try {
15561                        idx = Integer.parseInt(subStr);
15562                        if (idx <= 1) {
15563                            idx++;
15564                        } else {
15565                            idx--;
15566                        }
15567                    } catch(NumberFormatException e) {
15568                    }
15569                }
15570            }
15571        }
15572        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15573        return prefix + idxStr;
15574    }
15575
15576    private File getNextCodePath(File targetDir, String packageName) {
15577        File result;
15578        SecureRandom random = new SecureRandom();
15579        byte[] bytes = new byte[16];
15580        do {
15581            random.nextBytes(bytes);
15582            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15583            result = new File(targetDir, packageName + "-" + suffix);
15584        } while (result.exists());
15585        return result;
15586    }
15587
15588    // Utility method that returns the relative package path with respect
15589    // to the installation directory. Like say for /data/data/com.test-1.apk
15590    // string com.test-1 is returned.
15591    static String deriveCodePathName(String codePath) {
15592        if (codePath == null) {
15593            return null;
15594        }
15595        final File codeFile = new File(codePath);
15596        final String name = codeFile.getName();
15597        if (codeFile.isDirectory()) {
15598            return name;
15599        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15600            final int lastDot = name.lastIndexOf('.');
15601            return name.substring(0, lastDot);
15602        } else {
15603            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15604            return null;
15605        }
15606    }
15607
15608    static class PackageInstalledInfo {
15609        String name;
15610        int uid;
15611        // The set of users that originally had this package installed.
15612        int[] origUsers;
15613        // The set of users that now have this package installed.
15614        int[] newUsers;
15615        PackageParser.Package pkg;
15616        int returnCode;
15617        String returnMsg;
15618        PackageRemovedInfo removedInfo;
15619        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15620
15621        public void setError(int code, String msg) {
15622            setReturnCode(code);
15623            setReturnMessage(msg);
15624            Slog.w(TAG, msg);
15625        }
15626
15627        public void setError(String msg, PackageParserException e) {
15628            setReturnCode(e.error);
15629            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15630            Slog.w(TAG, msg, e);
15631        }
15632
15633        public void setError(String msg, PackageManagerException e) {
15634            returnCode = e.error;
15635            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15636            Slog.w(TAG, msg, e);
15637        }
15638
15639        public void setReturnCode(int returnCode) {
15640            this.returnCode = returnCode;
15641            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15642            for (int i = 0; i < childCount; i++) {
15643                addedChildPackages.valueAt(i).returnCode = returnCode;
15644            }
15645        }
15646
15647        private void setReturnMessage(String returnMsg) {
15648            this.returnMsg = returnMsg;
15649            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15650            for (int i = 0; i < childCount; i++) {
15651                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15652            }
15653        }
15654
15655        // In some error cases we want to convey more info back to the observer
15656        String origPackage;
15657        String origPermission;
15658    }
15659
15660    /*
15661     * Install a non-existing package.
15662     */
15663    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15664            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15665            PackageInstalledInfo res, int installReason) {
15666        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15667
15668        // Remember this for later, in case we need to rollback this install
15669        String pkgName = pkg.packageName;
15670
15671        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15672
15673        synchronized(mPackages) {
15674            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15675            if (renamedPackage != null) {
15676                // A package with the same name is already installed, though
15677                // it has been renamed to an older name.  The package we
15678                // are trying to install should be installed as an update to
15679                // the existing one, but that has not been requested, so bail.
15680                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15681                        + " without first uninstalling package running as "
15682                        + renamedPackage);
15683                return;
15684            }
15685            if (mPackages.containsKey(pkgName)) {
15686                // Don't allow installation over an existing package with the same name.
15687                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15688                        + " without first uninstalling.");
15689                return;
15690            }
15691        }
15692
15693        try {
15694            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15695                    System.currentTimeMillis(), user);
15696
15697            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15698
15699            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15700                prepareAppDataAfterInstallLIF(newPackage);
15701
15702            } else {
15703                // Remove package from internal structures, but keep around any
15704                // data that might have already existed
15705                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15706                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15707            }
15708        } catch (PackageManagerException e) {
15709            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15710        }
15711
15712        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15713    }
15714
15715    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
15716        // Can't rotate keys during boot or if sharedUser.
15717        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
15718                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
15719            return false;
15720        }
15721        // app is using upgradeKeySets; make sure all are valid
15722        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15723        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
15724        for (int i = 0; i < upgradeKeySets.length; i++) {
15725            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
15726                Slog.wtf(TAG, "Package "
15727                         + (oldPs.name != null ? oldPs.name : "<null>")
15728                         + " contains upgrade-key-set reference to unknown key-set: "
15729                         + upgradeKeySets[i]
15730                         + " reverting to signatures check.");
15731                return false;
15732            }
15733        }
15734        return true;
15735    }
15736
15737    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
15738        // Upgrade keysets are being used.  Determine if new package has a superset of the
15739        // required keys.
15740        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
15741        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15742        for (int i = 0; i < upgradeKeySets.length; i++) {
15743            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
15744            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
15745                return true;
15746            }
15747        }
15748        return false;
15749    }
15750
15751    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15752        try (DigestInputStream digestStream =
15753                new DigestInputStream(new FileInputStream(file), digest)) {
15754            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15755        }
15756    }
15757
15758    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
15759            UserHandle user, String installerPackageName, PackageInstalledInfo res,
15760            int installReason) {
15761        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
15762
15763        final PackageParser.Package oldPackage;
15764        final String pkgName = pkg.packageName;
15765        final int[] allUsers;
15766        final int[] installedUsers;
15767
15768        synchronized(mPackages) {
15769            oldPackage = mPackages.get(pkgName);
15770            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15771
15772            // don't allow upgrade to target a release SDK from a pre-release SDK
15773            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15774                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15775            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15776                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15777            if (oldTargetsPreRelease
15778                    && !newTargetsPreRelease
15779                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15780                Slog.w(TAG, "Can't install package targeting released sdk");
15781                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15782                return;
15783            }
15784
15785            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15786
15787            // verify signatures are valid
15788            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15789                if (!checkUpgradeKeySetLP(ps, pkg)) {
15790                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15791                            "New package not signed by keys specified by upgrade-keysets: "
15792                                    + pkgName);
15793                    return;
15794                }
15795            } else {
15796                // default to original signature matching
15797                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15798                        != PackageManager.SIGNATURE_MATCH) {
15799                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15800                            "New package has a different signature: " + pkgName);
15801                    return;
15802                }
15803            }
15804
15805            // don't allow a system upgrade unless the upgrade hash matches
15806            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
15807                byte[] digestBytes = null;
15808                try {
15809                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15810                    updateDigest(digest, new File(pkg.baseCodePath));
15811                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15812                        for (String path : pkg.splitCodePaths) {
15813                            updateDigest(digest, new File(path));
15814                        }
15815                    }
15816                    digestBytes = digest.digest();
15817                } catch (NoSuchAlgorithmException | IOException e) {
15818                    res.setError(INSTALL_FAILED_INVALID_APK,
15819                            "Could not compute hash: " + pkgName);
15820                    return;
15821                }
15822                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15823                    res.setError(INSTALL_FAILED_INVALID_APK,
15824                            "New package fails restrict-update check: " + pkgName);
15825                    return;
15826                }
15827                // retain upgrade restriction
15828                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15829            }
15830
15831            // Check for shared user id changes
15832            String invalidPackageName =
15833                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15834            if (invalidPackageName != null) {
15835                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15836                        "Package " + invalidPackageName + " tried to change user "
15837                                + oldPackage.mSharedUserId);
15838                return;
15839            }
15840
15841            // In case of rollback, remember per-user/profile install state
15842            allUsers = sUserManager.getUserIds();
15843            installedUsers = ps.queryInstalledUsers(allUsers, true);
15844
15845            // don't allow an upgrade from full to ephemeral
15846            if (isInstantApp) {
15847                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
15848                    for (int currentUser : allUsers) {
15849                        if (!ps.getInstantApp(currentUser)) {
15850                            // can't downgrade from full to instant
15851                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15852                                    + " for user: " + currentUser);
15853                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15854                            return;
15855                        }
15856                    }
15857                } else if (!ps.getInstantApp(user.getIdentifier())) {
15858                    // can't downgrade from full to instant
15859                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
15860                            + " for user: " + user.getIdentifier());
15861                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
15862                    return;
15863                }
15864            }
15865        }
15866
15867        // Update what is removed
15868        res.removedInfo = new PackageRemovedInfo();
15869        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15870        res.removedInfo.removedPackage = oldPackage.packageName;
15871        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15872        res.removedInfo.isUpdate = true;
15873        res.removedInfo.origUsers = installedUsers;
15874        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
15875        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15876        for (int i = 0; i < installedUsers.length; i++) {
15877            final int userId = installedUsers[i];
15878            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15879        }
15880
15881        final int childCount = (oldPackage.childPackages != null)
15882                ? oldPackage.childPackages.size() : 0;
15883        for (int i = 0; i < childCount; i++) {
15884            boolean childPackageUpdated = false;
15885            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15886            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15887            if (res.addedChildPackages != null) {
15888                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15889                if (childRes != null) {
15890                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15891                    childRes.removedInfo.removedPackage = childPkg.packageName;
15892                    childRes.removedInfo.isUpdate = true;
15893                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15894                    childPackageUpdated = true;
15895                }
15896            }
15897            if (!childPackageUpdated) {
15898                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
15899                childRemovedRes.removedPackage = childPkg.packageName;
15900                childRemovedRes.isUpdate = false;
15901                childRemovedRes.dataRemoved = true;
15902                synchronized (mPackages) {
15903                    if (childPs != null) {
15904                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15905                    }
15906                }
15907                if (res.removedInfo.removedChildPackages == null) {
15908                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15909                }
15910                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15911            }
15912        }
15913
15914        boolean sysPkg = (isSystemApp(oldPackage));
15915        if (sysPkg) {
15916            // Set the system/privileged flags as needed
15917            final boolean privileged =
15918                    (oldPackage.applicationInfo.privateFlags
15919                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15920            final int systemPolicyFlags = policyFlags
15921                    | PackageParser.PARSE_IS_SYSTEM
15922                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
15923
15924            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
15925                    user, allUsers, installerPackageName, res, installReason);
15926        } else {
15927            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
15928                    user, allUsers, installerPackageName, res, installReason);
15929        }
15930    }
15931
15932    public List<String> getPreviousCodePaths(String packageName) {
15933        final PackageSetting ps = mSettings.mPackages.get(packageName);
15934        final List<String> result = new ArrayList<String>();
15935        if (ps != null && ps.oldCodePaths != null) {
15936            result.addAll(ps.oldCodePaths);
15937        }
15938        return result;
15939    }
15940
15941    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
15942            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15943            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15944            int installReason) {
15945        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
15946                + deletedPackage);
15947
15948        String pkgName = deletedPackage.packageName;
15949        boolean deletedPkg = true;
15950        boolean addedPkg = false;
15951        boolean updatedSettings = false;
15952        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
15953        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
15954                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
15955
15956        final long origUpdateTime = (pkg.mExtras != null)
15957                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
15958
15959        // First delete the existing package while retaining the data directory
15960        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15961                res.removedInfo, true, pkg)) {
15962            // If the existing package wasn't successfully deleted
15963            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
15964            deletedPkg = false;
15965        } else {
15966            // Successfully deleted the old package; proceed with replace.
15967
15968            // If deleted package lived in a container, give users a chance to
15969            // relinquish resources before killing.
15970            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
15971                if (DEBUG_INSTALL) {
15972                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
15973                }
15974                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
15975                final ArrayList<String> pkgList = new ArrayList<String>(1);
15976                pkgList.add(deletedPackage.applicationInfo.packageName);
15977                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
15978            }
15979
15980            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15981                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15982            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15983
15984            try {
15985                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
15986                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
15987                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15988                        installReason);
15989
15990                // Update the in-memory copy of the previous code paths.
15991                PackageSetting ps = mSettings.mPackages.get(pkgName);
15992                if (!killApp) {
15993                    if (ps.oldCodePaths == null) {
15994                        ps.oldCodePaths = new ArraySet<>();
15995                    }
15996                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
15997                    if (deletedPackage.splitCodePaths != null) {
15998                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
15999                    }
16000                } else {
16001                    ps.oldCodePaths = null;
16002                }
16003                if (ps.childPackageNames != null) {
16004                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16005                        final String childPkgName = ps.childPackageNames.get(i);
16006                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16007                        childPs.oldCodePaths = ps.oldCodePaths;
16008                    }
16009                }
16010                // set instant app status, but, only if it's explicitly specified
16011                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16012                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16013                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16014                prepareAppDataAfterInstallLIF(newPackage);
16015                addedPkg = true;
16016                mDexManager.notifyPackageUpdated(newPackage.packageName,
16017                        newPackage.baseCodePath, newPackage.splitCodePaths);
16018            } catch (PackageManagerException e) {
16019                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16020            }
16021        }
16022
16023        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16024            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16025
16026            // Revert all internal state mutations and added folders for the failed install
16027            if (addedPkg) {
16028                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16029                        res.removedInfo, true, null);
16030            }
16031
16032            // Restore the old package
16033            if (deletedPkg) {
16034                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16035                File restoreFile = new File(deletedPackage.codePath);
16036                // Parse old package
16037                boolean oldExternal = isExternal(deletedPackage);
16038                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16039                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16040                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16041                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16042                try {
16043                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16044                            null);
16045                } catch (PackageManagerException e) {
16046                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16047                            + e.getMessage());
16048                    return;
16049                }
16050
16051                synchronized (mPackages) {
16052                    // Ensure the installer package name up to date
16053                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16054
16055                    // Update permissions for restored package
16056                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16057
16058                    mSettings.writeLPr();
16059                }
16060
16061                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16062            }
16063        } else {
16064            synchronized (mPackages) {
16065                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16066                if (ps != null) {
16067                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16068                    if (res.removedInfo.removedChildPackages != null) {
16069                        final int childCount = res.removedInfo.removedChildPackages.size();
16070                        // Iterate in reverse as we may modify the collection
16071                        for (int i = childCount - 1; i >= 0; i--) {
16072                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16073                            if (res.addedChildPackages.containsKey(childPackageName)) {
16074                                res.removedInfo.removedChildPackages.removeAt(i);
16075                            } else {
16076                                PackageRemovedInfo childInfo = res.removedInfo
16077                                        .removedChildPackages.valueAt(i);
16078                                childInfo.removedForAllUsers = mPackages.get(
16079                                        childInfo.removedPackage) == null;
16080                            }
16081                        }
16082                    }
16083                }
16084            }
16085        }
16086    }
16087
16088    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16089            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16090            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16091            int installReason) {
16092        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16093                + ", old=" + deletedPackage);
16094
16095        final boolean disabledSystem;
16096
16097        // Remove existing system package
16098        removePackageLI(deletedPackage, true);
16099
16100        synchronized (mPackages) {
16101            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16102        }
16103        if (!disabledSystem) {
16104            // We didn't need to disable the .apk as a current system package,
16105            // which means we are replacing another update that is already
16106            // installed.  We need to make sure to delete the older one's .apk.
16107            res.removedInfo.args = createInstallArgsForExisting(0,
16108                    deletedPackage.applicationInfo.getCodePath(),
16109                    deletedPackage.applicationInfo.getResourcePath(),
16110                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16111        } else {
16112            res.removedInfo.args = null;
16113        }
16114
16115        // Successfully disabled the old package. Now proceed with re-installation
16116        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16117                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16118        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16119
16120        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16121        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16122                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16123
16124        PackageParser.Package newPackage = null;
16125        try {
16126            // Add the package to the internal data structures
16127            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16128
16129            // Set the update and install times
16130            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16131            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16132                    System.currentTimeMillis());
16133
16134            // Update the package dynamic state if succeeded
16135            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16136                // Now that the install succeeded make sure we remove data
16137                // directories for any child package the update removed.
16138                final int deletedChildCount = (deletedPackage.childPackages != null)
16139                        ? deletedPackage.childPackages.size() : 0;
16140                final int newChildCount = (newPackage.childPackages != null)
16141                        ? newPackage.childPackages.size() : 0;
16142                for (int i = 0; i < deletedChildCount; i++) {
16143                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16144                    boolean childPackageDeleted = true;
16145                    for (int j = 0; j < newChildCount; j++) {
16146                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16147                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16148                            childPackageDeleted = false;
16149                            break;
16150                        }
16151                    }
16152                    if (childPackageDeleted) {
16153                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16154                                deletedChildPkg.packageName);
16155                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16156                            PackageRemovedInfo removedChildRes = res.removedInfo
16157                                    .removedChildPackages.get(deletedChildPkg.packageName);
16158                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16159                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16160                        }
16161                    }
16162                }
16163
16164                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16165                        installReason);
16166                prepareAppDataAfterInstallLIF(newPackage);
16167
16168                mDexManager.notifyPackageUpdated(newPackage.packageName,
16169                            newPackage.baseCodePath, newPackage.splitCodePaths);
16170            }
16171        } catch (PackageManagerException e) {
16172            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16173            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16174        }
16175
16176        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16177            // Re installation failed. Restore old information
16178            // Remove new pkg information
16179            if (newPackage != null) {
16180                removeInstalledPackageLI(newPackage, true);
16181            }
16182            // Add back the old system package
16183            try {
16184                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16185            } catch (PackageManagerException e) {
16186                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16187            }
16188
16189            synchronized (mPackages) {
16190                if (disabledSystem) {
16191                    enableSystemPackageLPw(deletedPackage);
16192                }
16193
16194                // Ensure the installer package name up to date
16195                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16196
16197                // Update permissions for restored package
16198                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16199
16200                mSettings.writeLPr();
16201            }
16202
16203            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16204                    + " after failed upgrade");
16205        }
16206    }
16207
16208    /**
16209     * Checks whether the parent or any of the child packages have a change shared
16210     * user. For a package to be a valid update the shred users of the parent and
16211     * the children should match. We may later support changing child shared users.
16212     * @param oldPkg The updated package.
16213     * @param newPkg The update package.
16214     * @return The shared user that change between the versions.
16215     */
16216    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16217            PackageParser.Package newPkg) {
16218        // Check parent shared user
16219        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16220            return newPkg.packageName;
16221        }
16222        // Check child shared users
16223        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16224        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16225        for (int i = 0; i < newChildCount; i++) {
16226            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16227            // If this child was present, did it have the same shared user?
16228            for (int j = 0; j < oldChildCount; j++) {
16229                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16230                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16231                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16232                    return newChildPkg.packageName;
16233                }
16234            }
16235        }
16236        return null;
16237    }
16238
16239    private void removeNativeBinariesLI(PackageSetting ps) {
16240        // Remove the lib path for the parent package
16241        if (ps != null) {
16242            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16243            // Remove the lib path for the child packages
16244            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16245            for (int i = 0; i < childCount; i++) {
16246                PackageSetting childPs = null;
16247                synchronized (mPackages) {
16248                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16249                }
16250                if (childPs != null) {
16251                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16252                            .legacyNativeLibraryPathString);
16253                }
16254            }
16255        }
16256    }
16257
16258    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16259        // Enable the parent package
16260        mSettings.enableSystemPackageLPw(pkg.packageName);
16261        // Enable the child packages
16262        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16263        for (int i = 0; i < childCount; i++) {
16264            PackageParser.Package childPkg = pkg.childPackages.get(i);
16265            mSettings.enableSystemPackageLPw(childPkg.packageName);
16266        }
16267    }
16268
16269    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16270            PackageParser.Package newPkg) {
16271        // Disable the parent package (parent always replaced)
16272        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16273        // Disable the child packages
16274        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16275        for (int i = 0; i < childCount; i++) {
16276            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16277            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16278            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16279        }
16280        return disabled;
16281    }
16282
16283    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16284            String installerPackageName) {
16285        // Enable the parent package
16286        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16287        // Enable the child packages
16288        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16289        for (int i = 0; i < childCount; i++) {
16290            PackageParser.Package childPkg = pkg.childPackages.get(i);
16291            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16292        }
16293    }
16294
16295    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16296        // Collect all used permissions in the UID
16297        ArraySet<String> usedPermissions = new ArraySet<>();
16298        final int packageCount = su.packages.size();
16299        for (int i = 0; i < packageCount; i++) {
16300            PackageSetting ps = su.packages.valueAt(i);
16301            if (ps.pkg == null) {
16302                continue;
16303            }
16304            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16305            for (int j = 0; j < requestedPermCount; j++) {
16306                String permission = ps.pkg.requestedPermissions.get(j);
16307                BasePermission bp = mSettings.mPermissions.get(permission);
16308                if (bp != null) {
16309                    usedPermissions.add(permission);
16310                }
16311            }
16312        }
16313
16314        PermissionsState permissionsState = su.getPermissionsState();
16315        // Prune install permissions
16316        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16317        final int installPermCount = installPermStates.size();
16318        for (int i = installPermCount - 1; i >= 0;  i--) {
16319            PermissionState permissionState = installPermStates.get(i);
16320            if (!usedPermissions.contains(permissionState.getName())) {
16321                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16322                if (bp != null) {
16323                    permissionsState.revokeInstallPermission(bp);
16324                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16325                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16326                }
16327            }
16328        }
16329
16330        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16331
16332        // Prune runtime permissions
16333        for (int userId : allUserIds) {
16334            List<PermissionState> runtimePermStates = permissionsState
16335                    .getRuntimePermissionStates(userId);
16336            final int runtimePermCount = runtimePermStates.size();
16337            for (int i = runtimePermCount - 1; i >= 0; i--) {
16338                PermissionState permissionState = runtimePermStates.get(i);
16339                if (!usedPermissions.contains(permissionState.getName())) {
16340                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16341                    if (bp != null) {
16342                        permissionsState.revokeRuntimePermission(bp, userId);
16343                        permissionsState.updatePermissionFlags(bp, userId,
16344                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16345                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16346                                runtimePermissionChangedUserIds, userId);
16347                    }
16348                }
16349            }
16350        }
16351
16352        return runtimePermissionChangedUserIds;
16353    }
16354
16355    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16356            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16357        // Update the parent package setting
16358        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16359                res, user, installReason);
16360        // Update the child packages setting
16361        final int childCount = (newPackage.childPackages != null)
16362                ? newPackage.childPackages.size() : 0;
16363        for (int i = 0; i < childCount; i++) {
16364            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16365            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16366            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16367                    childRes.origUsers, childRes, user, installReason);
16368        }
16369    }
16370
16371    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16372            String installerPackageName, int[] allUsers, int[] installedForUsers,
16373            PackageInstalledInfo res, UserHandle user, int installReason) {
16374        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16375
16376        String pkgName = newPackage.packageName;
16377        synchronized (mPackages) {
16378            //write settings. the installStatus will be incomplete at this stage.
16379            //note that the new package setting would have already been
16380            //added to mPackages. It hasn't been persisted yet.
16381            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16382            // TODO: Remove this write? It's also written at the end of this method
16383            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16384            mSettings.writeLPr();
16385            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16386        }
16387
16388        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16389        synchronized (mPackages) {
16390            updatePermissionsLPw(newPackage.packageName, newPackage,
16391                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16392                            ? UPDATE_PERMISSIONS_ALL : 0));
16393            // For system-bundled packages, we assume that installing an upgraded version
16394            // of the package implies that the user actually wants to run that new code,
16395            // so we enable the package.
16396            PackageSetting ps = mSettings.mPackages.get(pkgName);
16397            final int userId = user.getIdentifier();
16398            if (ps != null) {
16399                if (isSystemApp(newPackage)) {
16400                    if (DEBUG_INSTALL) {
16401                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16402                    }
16403                    // Enable system package for requested users
16404                    if (res.origUsers != null) {
16405                        for (int origUserId : res.origUsers) {
16406                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16407                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16408                                        origUserId, installerPackageName);
16409                            }
16410                        }
16411                    }
16412                    // Also convey the prior install/uninstall state
16413                    if (allUsers != null && installedForUsers != null) {
16414                        for (int currentUserId : allUsers) {
16415                            final boolean installed = ArrayUtils.contains(
16416                                    installedForUsers, currentUserId);
16417                            if (DEBUG_INSTALL) {
16418                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16419                            }
16420                            ps.setInstalled(installed, currentUserId);
16421                        }
16422                        // these install state changes will be persisted in the
16423                        // upcoming call to mSettings.writeLPr().
16424                    }
16425                }
16426                // It's implied that when a user requests installation, they want the app to be
16427                // installed and enabled.
16428                if (userId != UserHandle.USER_ALL) {
16429                    ps.setInstalled(true, userId);
16430                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16431                }
16432
16433                // When replacing an existing package, preserve the original install reason for all
16434                // users that had the package installed before.
16435                final Set<Integer> previousUserIds = new ArraySet<>();
16436                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16437                    final int installReasonCount = res.removedInfo.installReasons.size();
16438                    for (int i = 0; i < installReasonCount; i++) {
16439                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16440                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16441                        ps.setInstallReason(previousInstallReason, previousUserId);
16442                        previousUserIds.add(previousUserId);
16443                    }
16444                }
16445
16446                // Set install reason for users that are having the package newly installed.
16447                if (userId == UserHandle.USER_ALL) {
16448                    for (int currentUserId : sUserManager.getUserIds()) {
16449                        if (!previousUserIds.contains(currentUserId)) {
16450                            ps.setInstallReason(installReason, currentUserId);
16451                        }
16452                    }
16453                } else if (!previousUserIds.contains(userId)) {
16454                    ps.setInstallReason(installReason, userId);
16455                }
16456                mSettings.writeKernelMappingLPr(ps);
16457            }
16458            res.name = pkgName;
16459            res.uid = newPackage.applicationInfo.uid;
16460            res.pkg = newPackage;
16461            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16462            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16463            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16464            //to update install status
16465            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16466            mSettings.writeLPr();
16467            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16468        }
16469
16470        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16471    }
16472
16473    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16474        try {
16475            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16476            installPackageLI(args, res);
16477        } finally {
16478            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16479        }
16480    }
16481
16482    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16483        final int installFlags = args.installFlags;
16484        final String installerPackageName = args.installerPackageName;
16485        final String volumeUuid = args.volumeUuid;
16486        final File tmpPackageFile = new File(args.getCodePath());
16487        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16488        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16489                || (args.volumeUuid != null));
16490        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16491        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16492        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16493        boolean replace = false;
16494        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16495        if (args.move != null) {
16496            // moving a complete application; perform an initial scan on the new install location
16497            scanFlags |= SCAN_INITIAL;
16498        }
16499        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16500            scanFlags |= SCAN_DONT_KILL_APP;
16501        }
16502        if (instantApp) {
16503            scanFlags |= SCAN_AS_INSTANT_APP;
16504        }
16505        if (fullApp) {
16506            scanFlags |= SCAN_AS_FULL_APP;
16507        }
16508
16509        // Result object to be returned
16510        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16511
16512        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16513
16514        // Sanity check
16515        if (instantApp && (forwardLocked || onExternal)) {
16516            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16517                    + " external=" + onExternal);
16518            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16519            return;
16520        }
16521
16522        // Retrieve PackageSettings and parse package
16523        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16524                | PackageParser.PARSE_ENFORCE_CODE
16525                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16526                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16527                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16528                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16529        PackageParser pp = new PackageParser();
16530        pp.setSeparateProcesses(mSeparateProcesses);
16531        pp.setDisplayMetrics(mMetrics);
16532        pp.setCallback(mPackageParserCallback);
16533
16534        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16535        final PackageParser.Package pkg;
16536        try {
16537            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16538        } catch (PackageParserException e) {
16539            res.setError("Failed parse during installPackageLI", e);
16540            return;
16541        } finally {
16542            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16543        }
16544
16545        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
16546        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16547            Slog.w(TAG, "Instant app package " + pkg.packageName
16548                    + " does not target O, this will be a fatal error.");
16549            // STOPSHIP: Make this a fatal error
16550            pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O;
16551        }
16552        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
16553            Slog.w(TAG, "Instant app package " + pkg.packageName
16554                    + " does not target targetSandboxVersion 2, this will be a fatal error.");
16555            // STOPSHIP: Make this a fatal error
16556            pkg.applicationInfo.targetSandboxVersion = 2;
16557        }
16558
16559        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16560            // Static shared libraries have synthetic package names
16561            renameStaticSharedLibraryPackage(pkg);
16562
16563            // No static shared libs on external storage
16564            if (onExternal) {
16565                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16566                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16567                        "Packages declaring static-shared libs cannot be updated");
16568                return;
16569            }
16570        }
16571
16572        // If we are installing a clustered package add results for the children
16573        if (pkg.childPackages != null) {
16574            synchronized (mPackages) {
16575                final int childCount = pkg.childPackages.size();
16576                for (int i = 0; i < childCount; i++) {
16577                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16578                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16579                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16580                    childRes.pkg = childPkg;
16581                    childRes.name = childPkg.packageName;
16582                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16583                    if (childPs != null) {
16584                        childRes.origUsers = childPs.queryInstalledUsers(
16585                                sUserManager.getUserIds(), true);
16586                    }
16587                    if ((mPackages.containsKey(childPkg.packageName))) {
16588                        childRes.removedInfo = new PackageRemovedInfo();
16589                        childRes.removedInfo.removedPackage = childPkg.packageName;
16590                    }
16591                    if (res.addedChildPackages == null) {
16592                        res.addedChildPackages = new ArrayMap<>();
16593                    }
16594                    res.addedChildPackages.put(childPkg.packageName, childRes);
16595                }
16596            }
16597        }
16598
16599        // If package doesn't declare API override, mark that we have an install
16600        // time CPU ABI override.
16601        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16602            pkg.cpuAbiOverride = args.abiOverride;
16603        }
16604
16605        String pkgName = res.name = pkg.packageName;
16606        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16607            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16608                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16609                return;
16610            }
16611        }
16612
16613        try {
16614            // either use what we've been given or parse directly from the APK
16615            if (args.certificates != null) {
16616                try {
16617                    PackageParser.populateCertificates(pkg, args.certificates);
16618                } catch (PackageParserException e) {
16619                    // there was something wrong with the certificates we were given;
16620                    // try to pull them from the APK
16621                    PackageParser.collectCertificates(pkg, parseFlags);
16622                }
16623            } else {
16624                PackageParser.collectCertificates(pkg, parseFlags);
16625            }
16626        } catch (PackageParserException e) {
16627            res.setError("Failed collect during installPackageLI", e);
16628            return;
16629        }
16630
16631        // Get rid of all references to package scan path via parser.
16632        pp = null;
16633        String oldCodePath = null;
16634        boolean systemApp = false;
16635        synchronized (mPackages) {
16636            // Check if installing already existing package
16637            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16638                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16639                if (pkg.mOriginalPackages != null
16640                        && pkg.mOriginalPackages.contains(oldName)
16641                        && mPackages.containsKey(oldName)) {
16642                    // This package is derived from an original package,
16643                    // and this device has been updating from that original
16644                    // name.  We must continue using the original name, so
16645                    // rename the new package here.
16646                    pkg.setPackageName(oldName);
16647                    pkgName = pkg.packageName;
16648                    replace = true;
16649                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16650                            + oldName + " pkgName=" + pkgName);
16651                } else if (mPackages.containsKey(pkgName)) {
16652                    // This package, under its official name, already exists
16653                    // on the device; we should replace it.
16654                    replace = true;
16655                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16656                }
16657
16658                // Child packages are installed through the parent package
16659                if (pkg.parentPackage != null) {
16660                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16661                            "Package " + pkg.packageName + " is child of package "
16662                                    + pkg.parentPackage.parentPackage + ". Child packages "
16663                                    + "can be updated only through the parent package.");
16664                    return;
16665                }
16666
16667                if (replace) {
16668                    // Prevent apps opting out from runtime permissions
16669                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16670                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16671                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16672                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16673                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16674                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16675                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16676                                        + " doesn't support runtime permissions but the old"
16677                                        + " target SDK " + oldTargetSdk + " does.");
16678                        return;
16679                    }
16680                    // Prevent apps from downgrading their targetSandbox.
16681                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
16682                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
16683                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
16684                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
16685                                "Package " + pkg.packageName + " new target sandbox "
16686                                + newTargetSandbox + " is incompatible with the previous value of"
16687                                + oldTargetSandbox + ".");
16688                        return;
16689                    }
16690
16691                    // Prevent installing of child packages
16692                    if (oldPackage.parentPackage != null) {
16693                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16694                                "Package " + pkg.packageName + " is child of package "
16695                                        + oldPackage.parentPackage + ". Child packages "
16696                                        + "can be updated only through the parent package.");
16697                        return;
16698                    }
16699                }
16700            }
16701
16702            PackageSetting ps = mSettings.mPackages.get(pkgName);
16703            if (ps != null) {
16704                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16705
16706                // Static shared libs have same package with different versions where
16707                // we internally use a synthetic package name to allow multiple versions
16708                // of the same package, therefore we need to compare signatures against
16709                // the package setting for the latest library version.
16710                PackageSetting signatureCheckPs = ps;
16711                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16712                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16713                    if (libraryEntry != null) {
16714                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16715                    }
16716                }
16717
16718                // Quick sanity check that we're signed correctly if updating;
16719                // we'll check this again later when scanning, but we want to
16720                // bail early here before tripping over redefined permissions.
16721                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
16722                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
16723                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16724                                + pkg.packageName + " upgrade keys do not match the "
16725                                + "previously installed version");
16726                        return;
16727                    }
16728                } else {
16729                    try {
16730                        verifySignaturesLP(signatureCheckPs, pkg);
16731                    } catch (PackageManagerException e) {
16732                        res.setError(e.error, e.getMessage());
16733                        return;
16734                    }
16735                }
16736
16737                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16738                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16739                    systemApp = (ps.pkg.applicationInfo.flags &
16740                            ApplicationInfo.FLAG_SYSTEM) != 0;
16741                }
16742                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16743            }
16744
16745            int N = pkg.permissions.size();
16746            for (int i = N-1; i >= 0; i--) {
16747                PackageParser.Permission perm = pkg.permissions.get(i);
16748                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
16749
16750                // Don't allow anyone but the platform to define ephemeral permissions.
16751                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
16752                        && !PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16753                    Slog.w(TAG, "Package " + pkg.packageName
16754                            + " attempting to delcare ephemeral permission "
16755                            + perm.info.name + "; Removing ephemeral.");
16756                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
16757                }
16758                // Check whether the newly-scanned package wants to define an already-defined perm
16759                if (bp != null) {
16760                    // If the defining package is signed with our cert, it's okay.  This
16761                    // also includes the "updating the same package" case, of course.
16762                    // "updating same package" could also involve key-rotation.
16763                    final boolean sigsOk;
16764                    if (bp.sourcePackage.equals(pkg.packageName)
16765                            && (bp.packageSetting instanceof PackageSetting)
16766                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
16767                                    scanFlags))) {
16768                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
16769                    } else {
16770                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
16771                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16772                    }
16773                    if (!sigsOk) {
16774                        // If the owning package is the system itself, we log but allow
16775                        // install to proceed; we fail the install on all other permission
16776                        // redefinitions.
16777                        if (!bp.sourcePackage.equals("android")) {
16778                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16779                                    + pkg.packageName + " attempting to redeclare permission "
16780                                    + perm.info.name + " already owned by " + bp.sourcePackage);
16781                            res.origPermission = perm.info.name;
16782                            res.origPackage = bp.sourcePackage;
16783                            return;
16784                        } else {
16785                            Slog.w(TAG, "Package " + pkg.packageName
16786                                    + " attempting to redeclare system permission "
16787                                    + perm.info.name + "; ignoring new declaration");
16788                            pkg.permissions.remove(i);
16789                        }
16790                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16791                        // Prevent apps to change protection level to dangerous from any other
16792                        // type as this would allow a privilege escalation where an app adds a
16793                        // normal/signature permission in other app's group and later redefines
16794                        // it as dangerous leading to the group auto-grant.
16795                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16796                                == PermissionInfo.PROTECTION_DANGEROUS) {
16797                            if (bp != null && !bp.isRuntime()) {
16798                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16799                                        + "non-runtime permission " + perm.info.name
16800                                        + " to runtime; keeping old protection level");
16801                                perm.info.protectionLevel = bp.protectionLevel;
16802                            }
16803                        }
16804                    }
16805                }
16806            }
16807        }
16808
16809        if (systemApp) {
16810            if (onExternal) {
16811                // Abort update; system app can't be replaced with app on sdcard
16812                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16813                        "Cannot install updates to system apps on sdcard");
16814                return;
16815            } else if (instantApp) {
16816                // Abort update; system app can't be replaced with an instant app
16817                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16818                        "Cannot update a system app with an instant app");
16819                return;
16820            }
16821        }
16822
16823        if (args.move != null) {
16824            // We did an in-place move, so dex is ready to roll
16825            scanFlags |= SCAN_NO_DEX;
16826            scanFlags |= SCAN_MOVE;
16827
16828            synchronized (mPackages) {
16829                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16830                if (ps == null) {
16831                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16832                            "Missing settings for moved package " + pkgName);
16833                }
16834
16835                // We moved the entire application as-is, so bring over the
16836                // previously derived ABI information.
16837                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16838                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16839            }
16840
16841        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16842            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16843            scanFlags |= SCAN_NO_DEX;
16844
16845            try {
16846                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16847                    args.abiOverride : pkg.cpuAbiOverride);
16848                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
16849                        true /*extractLibs*/, mAppLib32InstallDir);
16850            } catch (PackageManagerException pme) {
16851                Slog.e(TAG, "Error deriving application ABI", pme);
16852                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16853                return;
16854            }
16855
16856            // Shared libraries for the package need to be updated.
16857            synchronized (mPackages) {
16858                try {
16859                    updateSharedLibrariesLPr(pkg, null);
16860                } catch (PackageManagerException e) {
16861                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
16862                }
16863            }
16864
16865            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16866            // Do not run PackageDexOptimizer through the local performDexOpt
16867            // method because `pkg` may not be in `mPackages` yet.
16868            //
16869            // Also, don't fail application installs if the dexopt step fails.
16870            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16871                    null /* instructionSets */, false /* checkProfiles */,
16872                    getCompilerFilterForReason(REASON_INSTALL),
16873                    getOrCreateCompilerPackageStats(pkg),
16874                    mDexManager.isUsedByOtherApps(pkg.packageName));
16875            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16876
16877            // Notify BackgroundDexOptService that the package has been changed.
16878            // If this is an update of a package which used to fail to compile,
16879            // BDOS will remove it from its blacklist.
16880            // TODO: Layering violation
16881            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
16882        }
16883
16884        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16885            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16886            return;
16887        }
16888
16889        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16890
16891        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16892                "installPackageLI")) {
16893            if (replace) {
16894                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16895                    // Static libs have a synthetic package name containing the version
16896                    // and cannot be updated as an update would get a new package name,
16897                    // unless this is the exact same version code which is useful for
16898                    // development.
16899                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16900                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
16901                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16902                                + "static-shared libs cannot be updated");
16903                        return;
16904                    }
16905                }
16906                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
16907                        installerPackageName, res, args.installReason);
16908            } else {
16909                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16910                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16911            }
16912        }
16913
16914        synchronized (mPackages) {
16915            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16916            if (ps != null) {
16917                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16918                ps.setUpdateAvailable(false /*updateAvailable*/);
16919            }
16920
16921            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16922            for (int i = 0; i < childCount; i++) {
16923                PackageParser.Package childPkg = pkg.childPackages.get(i);
16924                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16925                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16926                if (childPs != null) {
16927                    childRes.newUsers = childPs.queryInstalledUsers(
16928                            sUserManager.getUserIds(), true);
16929                }
16930            }
16931
16932            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16933                updateSequenceNumberLP(pkgName, res.newUsers);
16934                updateInstantAppInstallerLocked();
16935            }
16936        }
16937    }
16938
16939    private void startIntentFilterVerifications(int userId, boolean replacing,
16940            PackageParser.Package pkg) {
16941        if (mIntentFilterVerifierComponent == null) {
16942            Slog.w(TAG, "No IntentFilter verification will not be done as "
16943                    + "there is no IntentFilterVerifier available!");
16944            return;
16945        }
16946
16947        final int verifierUid = getPackageUid(
16948                mIntentFilterVerifierComponent.getPackageName(),
16949                MATCH_DEBUG_TRIAGED_MISSING,
16950                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16951
16952        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16953        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16954        mHandler.sendMessage(msg);
16955
16956        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16957        for (int i = 0; i < childCount; i++) {
16958            PackageParser.Package childPkg = pkg.childPackages.get(i);
16959            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16960            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
16961            mHandler.sendMessage(msg);
16962        }
16963    }
16964
16965    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
16966            PackageParser.Package pkg) {
16967        int size = pkg.activities.size();
16968        if (size == 0) {
16969            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16970                    "No activity, so no need to verify any IntentFilter!");
16971            return;
16972        }
16973
16974        final boolean hasDomainURLs = hasDomainURLs(pkg);
16975        if (!hasDomainURLs) {
16976            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16977                    "No domain URLs, so no need to verify any IntentFilter!");
16978            return;
16979        }
16980
16981        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
16982                + " if any IntentFilter from the " + size
16983                + " Activities needs verification ...");
16984
16985        int count = 0;
16986        final String packageName = pkg.packageName;
16987
16988        synchronized (mPackages) {
16989            // If this is a new install and we see that we've already run verification for this
16990            // package, we have nothing to do: it means the state was restored from backup.
16991            if (!replacing) {
16992                IntentFilterVerificationInfo ivi =
16993                        mSettings.getIntentFilterVerificationLPr(packageName);
16994                if (ivi != null) {
16995                    if (DEBUG_DOMAIN_VERIFICATION) {
16996                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
16997                                + ivi.getStatusString());
16998                    }
16999                    return;
17000                }
17001            }
17002
17003            // If any filters need to be verified, then all need to be.
17004            boolean needToVerify = false;
17005            for (PackageParser.Activity a : pkg.activities) {
17006                for (ActivityIntentInfo filter : a.intents) {
17007                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17008                        if (DEBUG_DOMAIN_VERIFICATION) {
17009                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
17010                        }
17011                        needToVerify = true;
17012                        break;
17013                    }
17014                }
17015            }
17016
17017            if (needToVerify) {
17018                final int verificationId = mIntentFilterVerificationToken++;
17019                for (PackageParser.Activity a : pkg.activities) {
17020                    for (ActivityIntentInfo filter : a.intents) {
17021                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17022                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17023                                    "Verification needed for IntentFilter:" + filter.toString());
17024                            mIntentFilterVerifier.addOneIntentFilterVerification(
17025                                    verifierUid, userId, verificationId, filter, packageName);
17026                            count++;
17027                        }
17028                    }
17029                }
17030            }
17031        }
17032
17033        if (count > 0) {
17034            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17035                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17036                    +  " for userId:" + userId);
17037            mIntentFilterVerifier.startVerifications(userId);
17038        } else {
17039            if (DEBUG_DOMAIN_VERIFICATION) {
17040                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17041            }
17042        }
17043    }
17044
17045    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17046        final ComponentName cn  = filter.activity.getComponentName();
17047        final String packageName = cn.getPackageName();
17048
17049        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17050                packageName);
17051        if (ivi == null) {
17052            return true;
17053        }
17054        int status = ivi.getStatus();
17055        switch (status) {
17056            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17057            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17058                return true;
17059
17060            default:
17061                // Nothing to do
17062                return false;
17063        }
17064    }
17065
17066    private static boolean isMultiArch(ApplicationInfo info) {
17067        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17068    }
17069
17070    private static boolean isExternal(PackageParser.Package pkg) {
17071        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17072    }
17073
17074    private static boolean isExternal(PackageSetting ps) {
17075        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17076    }
17077
17078    private static boolean isSystemApp(PackageParser.Package pkg) {
17079        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17080    }
17081
17082    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17083        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17084    }
17085
17086    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17087        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17088    }
17089
17090    private static boolean isSystemApp(PackageSetting ps) {
17091        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17092    }
17093
17094    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17095        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17096    }
17097
17098    private int packageFlagsToInstallFlags(PackageSetting ps) {
17099        int installFlags = 0;
17100        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17101            // This existing package was an external ASEC install when we have
17102            // the external flag without a UUID
17103            installFlags |= PackageManager.INSTALL_EXTERNAL;
17104        }
17105        if (ps.isForwardLocked()) {
17106            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17107        }
17108        return installFlags;
17109    }
17110
17111    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17112        if (isExternal(pkg)) {
17113            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17114                return StorageManager.UUID_PRIMARY_PHYSICAL;
17115            } else {
17116                return pkg.volumeUuid;
17117            }
17118        } else {
17119            return StorageManager.UUID_PRIVATE_INTERNAL;
17120        }
17121    }
17122
17123    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17124        if (isExternal(pkg)) {
17125            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17126                return mSettings.getExternalVersion();
17127            } else {
17128                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17129            }
17130        } else {
17131            return mSettings.getInternalVersion();
17132        }
17133    }
17134
17135    private void deleteTempPackageFiles() {
17136        final FilenameFilter filter = new FilenameFilter() {
17137            public boolean accept(File dir, String name) {
17138                return name.startsWith("vmdl") && name.endsWith(".tmp");
17139            }
17140        };
17141        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17142            file.delete();
17143        }
17144    }
17145
17146    @Override
17147    public void deletePackageAsUser(String packageName, int versionCode,
17148            IPackageDeleteObserver observer, int userId, int flags) {
17149        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17150                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17151    }
17152
17153    @Override
17154    public void deletePackageVersioned(VersionedPackage versionedPackage,
17155            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17156        mContext.enforceCallingOrSelfPermission(
17157                android.Manifest.permission.DELETE_PACKAGES, null);
17158        Preconditions.checkNotNull(versionedPackage);
17159        Preconditions.checkNotNull(observer);
17160        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17161                PackageManager.VERSION_CODE_HIGHEST,
17162                Integer.MAX_VALUE, "versionCode must be >= -1");
17163
17164        final String packageName = versionedPackage.getPackageName();
17165        // TODO: We will change version code to long, so in the new API it is long
17166        final int versionCode = (int) versionedPackage.getVersionCode();
17167        final String internalPackageName;
17168        synchronized (mPackages) {
17169            // Normalize package name to handle renamed packages and static libs
17170            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17171                    // TODO: We will change version code to long, so in the new API it is long
17172                    (int) versionedPackage.getVersionCode());
17173        }
17174
17175        final int uid = Binder.getCallingUid();
17176        if (!isOrphaned(internalPackageName)
17177                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17178            try {
17179                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17180                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17181                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17182                observer.onUserActionRequired(intent);
17183            } catch (RemoteException re) {
17184            }
17185            return;
17186        }
17187        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17188        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17189        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17190            mContext.enforceCallingOrSelfPermission(
17191                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17192                    "deletePackage for user " + userId);
17193        }
17194
17195        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17196            try {
17197                observer.onPackageDeleted(packageName,
17198                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17199            } catch (RemoteException re) {
17200            }
17201            return;
17202        }
17203
17204        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17205            try {
17206                observer.onPackageDeleted(packageName,
17207                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17208            } catch (RemoteException re) {
17209            }
17210            return;
17211        }
17212
17213        if (DEBUG_REMOVE) {
17214            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17215                    + " deleteAllUsers: " + deleteAllUsers + " version="
17216                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17217                    ? "VERSION_CODE_HIGHEST" : versionCode));
17218        }
17219        // Queue up an async operation since the package deletion may take a little while.
17220        mHandler.post(new Runnable() {
17221            public void run() {
17222                mHandler.removeCallbacks(this);
17223                int returnCode;
17224                if (!deleteAllUsers) {
17225                    returnCode = deletePackageX(internalPackageName, versionCode,
17226                            userId, deleteFlags);
17227                } else {
17228                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17229                            internalPackageName, users);
17230                    // If nobody is blocking uninstall, proceed with delete for all users
17231                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17232                        returnCode = deletePackageX(internalPackageName, versionCode,
17233                                userId, deleteFlags);
17234                    } else {
17235                        // Otherwise uninstall individually for users with blockUninstalls=false
17236                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17237                        for (int userId : users) {
17238                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17239                                returnCode = deletePackageX(internalPackageName, versionCode,
17240                                        userId, userFlags);
17241                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17242                                    Slog.w(TAG, "Package delete failed for user " + userId
17243                                            + ", returnCode " + returnCode);
17244                                }
17245                            }
17246                        }
17247                        // The app has only been marked uninstalled for certain users.
17248                        // We still need to report that delete was blocked
17249                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17250                    }
17251                }
17252                try {
17253                    observer.onPackageDeleted(packageName, returnCode, null);
17254                } catch (RemoteException e) {
17255                    Log.i(TAG, "Observer no longer exists.");
17256                } //end catch
17257            } //end run
17258        });
17259    }
17260
17261    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17262        if (pkg.staticSharedLibName != null) {
17263            return pkg.manifestPackageName;
17264        }
17265        return pkg.packageName;
17266    }
17267
17268    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17269        // Handle renamed packages
17270        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17271        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17272
17273        // Is this a static library?
17274        SparseArray<SharedLibraryEntry> versionedLib =
17275                mStaticLibsByDeclaringPackage.get(packageName);
17276        if (versionedLib == null || versionedLib.size() <= 0) {
17277            return packageName;
17278        }
17279
17280        // Figure out which lib versions the caller can see
17281        SparseIntArray versionsCallerCanSee = null;
17282        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17283        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17284                && callingAppId != Process.ROOT_UID) {
17285            versionsCallerCanSee = new SparseIntArray();
17286            String libName = versionedLib.valueAt(0).info.getName();
17287            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17288            if (uidPackages != null) {
17289                for (String uidPackage : uidPackages) {
17290                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17291                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17292                    if (libIdx >= 0) {
17293                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17294                        versionsCallerCanSee.append(libVersion, libVersion);
17295                    }
17296                }
17297            }
17298        }
17299
17300        // Caller can see nothing - done
17301        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17302            return packageName;
17303        }
17304
17305        // Find the version the caller can see and the app version code
17306        SharedLibraryEntry highestVersion = null;
17307        final int versionCount = versionedLib.size();
17308        for (int i = 0; i < versionCount; i++) {
17309            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17310            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17311                    libEntry.info.getVersion()) < 0) {
17312                continue;
17313            }
17314            // TODO: We will change version code to long, so in the new API it is long
17315            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17316            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17317                if (libVersionCode == versionCode) {
17318                    return libEntry.apk;
17319                }
17320            } else if (highestVersion == null) {
17321                highestVersion = libEntry;
17322            } else if (libVersionCode  > highestVersion.info
17323                    .getDeclaringPackage().getVersionCode()) {
17324                highestVersion = libEntry;
17325            }
17326        }
17327
17328        if (highestVersion != null) {
17329            return highestVersion.apk;
17330        }
17331
17332        return packageName;
17333    }
17334
17335    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17336        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17337              || callingUid == Process.SYSTEM_UID) {
17338            return true;
17339        }
17340        final int callingUserId = UserHandle.getUserId(callingUid);
17341        // If the caller installed the pkgName, then allow it to silently uninstall.
17342        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17343            return true;
17344        }
17345
17346        // Allow package verifier to silently uninstall.
17347        if (mRequiredVerifierPackage != null &&
17348                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17349            return true;
17350        }
17351
17352        // Allow package uninstaller to silently uninstall.
17353        if (mRequiredUninstallerPackage != null &&
17354                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17355            return true;
17356        }
17357
17358        // Allow storage manager to silently uninstall.
17359        if (mStorageManagerPackage != null &&
17360                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17361            return true;
17362        }
17363        return false;
17364    }
17365
17366    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17367        int[] result = EMPTY_INT_ARRAY;
17368        for (int userId : userIds) {
17369            if (getBlockUninstallForUser(packageName, userId)) {
17370                result = ArrayUtils.appendInt(result, userId);
17371            }
17372        }
17373        return result;
17374    }
17375
17376    @Override
17377    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17378        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17379    }
17380
17381    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17382        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17383                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17384        try {
17385            if (dpm != null) {
17386                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17387                        /* callingUserOnly =*/ false);
17388                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17389                        : deviceOwnerComponentName.getPackageName();
17390                // Does the package contains the device owner?
17391                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17392                // this check is probably not needed, since DO should be registered as a device
17393                // admin on some user too. (Original bug for this: b/17657954)
17394                if (packageName.equals(deviceOwnerPackageName)) {
17395                    return true;
17396                }
17397                // Does it contain a device admin for any user?
17398                int[] users;
17399                if (userId == UserHandle.USER_ALL) {
17400                    users = sUserManager.getUserIds();
17401                } else {
17402                    users = new int[]{userId};
17403                }
17404                for (int i = 0; i < users.length; ++i) {
17405                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17406                        return true;
17407                    }
17408                }
17409            }
17410        } catch (RemoteException e) {
17411        }
17412        return false;
17413    }
17414
17415    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17416        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17417    }
17418
17419    /**
17420     *  This method is an internal method that could be get invoked either
17421     *  to delete an installed package or to clean up a failed installation.
17422     *  After deleting an installed package, a broadcast is sent to notify any
17423     *  listeners that the package has been removed. For cleaning up a failed
17424     *  installation, the broadcast is not necessary since the package's
17425     *  installation wouldn't have sent the initial broadcast either
17426     *  The key steps in deleting a package are
17427     *  deleting the package information in internal structures like mPackages,
17428     *  deleting the packages base directories through installd
17429     *  updating mSettings to reflect current status
17430     *  persisting settings for later use
17431     *  sending a broadcast if necessary
17432     */
17433    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17434        final PackageRemovedInfo info = new PackageRemovedInfo();
17435        final boolean res;
17436
17437        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17438                ? UserHandle.USER_ALL : userId;
17439
17440        if (isPackageDeviceAdmin(packageName, removeUser)) {
17441            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17442            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17443        }
17444
17445        PackageSetting uninstalledPs = null;
17446        PackageParser.Package pkg = null;
17447
17448        // for the uninstall-updates case and restricted profiles, remember the per-
17449        // user handle installed state
17450        int[] allUsers;
17451        synchronized (mPackages) {
17452            uninstalledPs = mSettings.mPackages.get(packageName);
17453            if (uninstalledPs == null) {
17454                Slog.w(TAG, "Not removing non-existent package " + packageName);
17455                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17456            }
17457
17458            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17459                    && uninstalledPs.versionCode != versionCode) {
17460                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17461                        + uninstalledPs.versionCode + " != " + versionCode);
17462                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17463            }
17464
17465            // Static shared libs can be declared by any package, so let us not
17466            // allow removing a package if it provides a lib others depend on.
17467            pkg = mPackages.get(packageName);
17468            if (pkg != null && pkg.staticSharedLibName != null) {
17469                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17470                        pkg.staticSharedLibVersion);
17471                if (libEntry != null) {
17472                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17473                            libEntry.info, 0, userId);
17474                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17475                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17476                                + " hosting lib " + libEntry.info.getName() + " version "
17477                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17478                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17479                    }
17480                }
17481            }
17482
17483            allUsers = sUserManager.getUserIds();
17484            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17485        }
17486
17487        final int freezeUser;
17488        if (isUpdatedSystemApp(uninstalledPs)
17489                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17490            // We're downgrading a system app, which will apply to all users, so
17491            // freeze them all during the downgrade
17492            freezeUser = UserHandle.USER_ALL;
17493        } else {
17494            freezeUser = removeUser;
17495        }
17496
17497        synchronized (mInstallLock) {
17498            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17499            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17500                    deleteFlags, "deletePackageX")) {
17501                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17502                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
17503            }
17504            synchronized (mPackages) {
17505                if (res) {
17506                    if (pkg != null) {
17507                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17508                    }
17509                    updateSequenceNumberLP(packageName, info.removedUsers);
17510                    updateInstantAppInstallerLocked();
17511                }
17512            }
17513        }
17514
17515        if (res) {
17516            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17517            info.sendPackageRemovedBroadcasts(killApp);
17518            info.sendSystemPackageUpdatedBroadcasts();
17519            info.sendSystemPackageAppearedBroadcasts();
17520        }
17521        // Force a gc here.
17522        Runtime.getRuntime().gc();
17523        // Delete the resources here after sending the broadcast to let
17524        // other processes clean up before deleting resources.
17525        if (info.args != null) {
17526            synchronized (mInstallLock) {
17527                info.args.doPostDeleteLI(true);
17528            }
17529        }
17530
17531        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17532    }
17533
17534    class PackageRemovedInfo {
17535        String removedPackage;
17536        int uid = -1;
17537        int removedAppId = -1;
17538        int[] origUsers;
17539        int[] removedUsers = null;
17540        SparseArray<Integer> installReasons;
17541        boolean isRemovedPackageSystemUpdate = false;
17542        boolean isUpdate;
17543        boolean dataRemoved;
17544        boolean removedForAllUsers;
17545        boolean isStaticSharedLib;
17546        // Clean up resources deleted packages.
17547        InstallArgs args = null;
17548        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17549        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17550
17551        void sendPackageRemovedBroadcasts(boolean killApp) {
17552            sendPackageRemovedBroadcastInternal(killApp);
17553            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17554            for (int i = 0; i < childCount; i++) {
17555                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17556                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17557            }
17558        }
17559
17560        void sendSystemPackageUpdatedBroadcasts() {
17561            if (isRemovedPackageSystemUpdate) {
17562                sendSystemPackageUpdatedBroadcastsInternal();
17563                final int childCount = (removedChildPackages != null)
17564                        ? removedChildPackages.size() : 0;
17565                for (int i = 0; i < childCount; i++) {
17566                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17567                    if (childInfo.isRemovedPackageSystemUpdate) {
17568                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17569                    }
17570                }
17571            }
17572        }
17573
17574        void sendSystemPackageAppearedBroadcasts() {
17575            final int packageCount = (appearedChildPackages != null)
17576                    ? appearedChildPackages.size() : 0;
17577            for (int i = 0; i < packageCount; i++) {
17578                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17579                sendPackageAddedForNewUsers(installedInfo.name, true,
17580                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17581            }
17582        }
17583
17584        private void sendSystemPackageUpdatedBroadcastsInternal() {
17585            Bundle extras = new Bundle(2);
17586            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17587            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17588            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
17589                    extras, 0, null, null, null);
17590            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
17591                    extras, 0, null, null, null);
17592            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
17593                    null, 0, removedPackage, null, null);
17594        }
17595
17596        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17597            // Don't send static shared library removal broadcasts as these
17598            // libs are visible only the the apps that depend on them an one
17599            // cannot remove the library if it has a dependency.
17600            if (isStaticSharedLib) {
17601                return;
17602            }
17603            Bundle extras = new Bundle(2);
17604            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17605            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17606            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17607            if (isUpdate || isRemovedPackageSystemUpdate) {
17608                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17609            }
17610            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17611            if (removedPackage != null) {
17612                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
17613                        extras, 0, null, null, removedUsers);
17614                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17615                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17616                            removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17617                            null, null, removedUsers);
17618                }
17619            }
17620            if (removedAppId >= 0) {
17621                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
17622                        removedUsers);
17623            }
17624        }
17625    }
17626
17627    /*
17628     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17629     * flag is not set, the data directory is removed as well.
17630     * make sure this flag is set for partially installed apps. If not its meaningless to
17631     * delete a partially installed application.
17632     */
17633    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17634            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17635        String packageName = ps.name;
17636        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17637        // Retrieve object to delete permissions for shared user later on
17638        final PackageParser.Package deletedPkg;
17639        final PackageSetting deletedPs;
17640        // reader
17641        synchronized (mPackages) {
17642            deletedPkg = mPackages.get(packageName);
17643            deletedPs = mSettings.mPackages.get(packageName);
17644            if (outInfo != null) {
17645                outInfo.removedPackage = packageName;
17646                outInfo.isStaticSharedLib = deletedPkg != null
17647                        && deletedPkg.staticSharedLibName != null;
17648                outInfo.removedUsers = deletedPs != null
17649                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
17650                        : null;
17651            }
17652        }
17653
17654        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
17655
17656        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17657            final PackageParser.Package resolvedPkg;
17658            if (deletedPkg != null) {
17659                resolvedPkg = deletedPkg;
17660            } else {
17661                // We don't have a parsed package when it lives on an ejected
17662                // adopted storage device, so fake something together
17663                resolvedPkg = new PackageParser.Package(ps.name);
17664                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17665            }
17666            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17667                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17668            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17669            if (outInfo != null) {
17670                outInfo.dataRemoved = true;
17671            }
17672            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17673        }
17674
17675        int removedAppId = -1;
17676
17677        // writer
17678        synchronized (mPackages) {
17679            boolean installedStateChanged = false;
17680            if (deletedPs != null) {
17681                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17682                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17683                    clearDefaultBrowserIfNeeded(packageName);
17684                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17685                    removedAppId = mSettings.removePackageLPw(packageName);
17686                    if (outInfo != null) {
17687                        outInfo.removedAppId = removedAppId;
17688                    }
17689                    updatePermissionsLPw(deletedPs.name, null, 0);
17690                    if (deletedPs.sharedUser != null) {
17691                        // Remove permissions associated with package. Since runtime
17692                        // permissions are per user we have to kill the removed package
17693                        // or packages running under the shared user of the removed
17694                        // package if revoking the permissions requested only by the removed
17695                        // package is successful and this causes a change in gids.
17696                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17697                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17698                                    userId);
17699                            if (userIdToKill == UserHandle.USER_ALL
17700                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17701                                // If gids changed for this user, kill all affected packages.
17702                                mHandler.post(new Runnable() {
17703                                    @Override
17704                                    public void run() {
17705                                        // This has to happen with no lock held.
17706                                        killApplication(deletedPs.name, deletedPs.appId,
17707                                                KILL_APP_REASON_GIDS_CHANGED);
17708                                    }
17709                                });
17710                                break;
17711                            }
17712                        }
17713                    }
17714                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17715                }
17716                // make sure to preserve per-user disabled state if this removal was just
17717                // a downgrade of a system app to the factory package
17718                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17719                    if (DEBUG_REMOVE) {
17720                        Slog.d(TAG, "Propagating install state across downgrade");
17721                    }
17722                    for (int userId : allUserHandles) {
17723                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17724                        if (DEBUG_REMOVE) {
17725                            Slog.d(TAG, "    user " + userId + " => " + installed);
17726                        }
17727                        if (installed != ps.getInstalled(userId)) {
17728                            installedStateChanged = true;
17729                        }
17730                        ps.setInstalled(installed, userId);
17731                    }
17732                }
17733            }
17734            // can downgrade to reader
17735            if (writeSettings) {
17736                // Save settings now
17737                mSettings.writeLPr();
17738            }
17739            if (installedStateChanged) {
17740                mSettings.writeKernelMappingLPr(ps);
17741            }
17742        }
17743        if (removedAppId != -1) {
17744            // A user ID was deleted here. Go through all users and remove it
17745            // from KeyStore.
17746            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17747        }
17748    }
17749
17750    static boolean locationIsPrivileged(File path) {
17751        try {
17752            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
17753                    .getCanonicalPath();
17754            return path.getCanonicalPath().startsWith(privilegedAppDir);
17755        } catch (IOException e) {
17756            Slog.e(TAG, "Unable to access code path " + path);
17757        }
17758        return false;
17759    }
17760
17761    /*
17762     * Tries to delete system package.
17763     */
17764    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17765            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17766            boolean writeSettings) {
17767        if (deletedPs.parentPackageName != null) {
17768            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17769            return false;
17770        }
17771
17772        final boolean applyUserRestrictions
17773                = (allUserHandles != null) && (outInfo.origUsers != null);
17774        final PackageSetting disabledPs;
17775        // Confirm if the system package has been updated
17776        // An updated system app can be deleted. This will also have to restore
17777        // the system pkg from system partition
17778        // reader
17779        synchronized (mPackages) {
17780            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17781        }
17782
17783        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17784                + " disabledPs=" + disabledPs);
17785
17786        if (disabledPs == null) {
17787            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17788            return false;
17789        } else if (DEBUG_REMOVE) {
17790            Slog.d(TAG, "Deleting system pkg from data partition");
17791        }
17792
17793        if (DEBUG_REMOVE) {
17794            if (applyUserRestrictions) {
17795                Slog.d(TAG, "Remembering install states:");
17796                for (int userId : allUserHandles) {
17797                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17798                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17799                }
17800            }
17801        }
17802
17803        // Delete the updated package
17804        outInfo.isRemovedPackageSystemUpdate = true;
17805        if (outInfo.removedChildPackages != null) {
17806            final int childCount = (deletedPs.childPackageNames != null)
17807                    ? deletedPs.childPackageNames.size() : 0;
17808            for (int i = 0; i < childCount; i++) {
17809                String childPackageName = deletedPs.childPackageNames.get(i);
17810                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17811                        .contains(childPackageName)) {
17812                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17813                            childPackageName);
17814                    if (childInfo != null) {
17815                        childInfo.isRemovedPackageSystemUpdate = true;
17816                    }
17817                }
17818            }
17819        }
17820
17821        if (disabledPs.versionCode < deletedPs.versionCode) {
17822            // Delete data for downgrades
17823            flags &= ~PackageManager.DELETE_KEEP_DATA;
17824        } else {
17825            // Preserve data by setting flag
17826            flags |= PackageManager.DELETE_KEEP_DATA;
17827        }
17828
17829        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17830                outInfo, writeSettings, disabledPs.pkg);
17831        if (!ret) {
17832            return false;
17833        }
17834
17835        // writer
17836        synchronized (mPackages) {
17837            // Reinstate the old system package
17838            enableSystemPackageLPw(disabledPs.pkg);
17839            // Remove any native libraries from the upgraded package.
17840            removeNativeBinariesLI(deletedPs);
17841        }
17842
17843        // Install the system package
17844        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17845        int parseFlags = mDefParseFlags
17846                | PackageParser.PARSE_MUST_BE_APK
17847                | PackageParser.PARSE_IS_SYSTEM
17848                | PackageParser.PARSE_IS_SYSTEM_DIR;
17849        if (locationIsPrivileged(disabledPs.codePath)) {
17850            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
17851        }
17852
17853        final PackageParser.Package newPkg;
17854        try {
17855            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
17856                0 /* currentTime */, null);
17857        } catch (PackageManagerException e) {
17858            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17859                    + e.getMessage());
17860            return false;
17861        }
17862
17863        try {
17864            // update shared libraries for the newly re-installed system package
17865            updateSharedLibrariesLPr(newPkg, null);
17866        } catch (PackageManagerException e) {
17867            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17868        }
17869
17870        prepareAppDataAfterInstallLIF(newPkg);
17871
17872        // writer
17873        synchronized (mPackages) {
17874            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
17875
17876            // Propagate the permissions state as we do not want to drop on the floor
17877            // runtime permissions. The update permissions method below will take
17878            // care of removing obsolete permissions and grant install permissions.
17879            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
17880            updatePermissionsLPw(newPkg.packageName, newPkg,
17881                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
17882
17883            if (applyUserRestrictions) {
17884                boolean installedStateChanged = false;
17885                if (DEBUG_REMOVE) {
17886                    Slog.d(TAG, "Propagating install state across reinstall");
17887                }
17888                for (int userId : allUserHandles) {
17889                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17890                    if (DEBUG_REMOVE) {
17891                        Slog.d(TAG, "    user " + userId + " => " + installed);
17892                    }
17893                    if (installed != ps.getInstalled(userId)) {
17894                        installedStateChanged = true;
17895                    }
17896                    ps.setInstalled(installed, userId);
17897
17898                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17899                }
17900                // Regardless of writeSettings we need to ensure that this restriction
17901                // state propagation is persisted
17902                mSettings.writeAllUsersPackageRestrictionsLPr();
17903                if (installedStateChanged) {
17904                    mSettings.writeKernelMappingLPr(ps);
17905                }
17906            }
17907            // can downgrade to reader here
17908            if (writeSettings) {
17909                mSettings.writeLPr();
17910            }
17911        }
17912        return true;
17913    }
17914
17915    private boolean deleteInstalledPackageLIF(PackageSetting ps,
17916            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
17917            PackageRemovedInfo outInfo, boolean writeSettings,
17918            PackageParser.Package replacingPackage) {
17919        synchronized (mPackages) {
17920            if (outInfo != null) {
17921                outInfo.uid = ps.appId;
17922            }
17923
17924            if (outInfo != null && outInfo.removedChildPackages != null) {
17925                final int childCount = (ps.childPackageNames != null)
17926                        ? ps.childPackageNames.size() : 0;
17927                for (int i = 0; i < childCount; i++) {
17928                    String childPackageName = ps.childPackageNames.get(i);
17929                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
17930                    if (childPs == null) {
17931                        return false;
17932                    }
17933                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17934                            childPackageName);
17935                    if (childInfo != null) {
17936                        childInfo.uid = childPs.appId;
17937                    }
17938                }
17939            }
17940        }
17941
17942        // Delete package data from internal structures and also remove data if flag is set
17943        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
17944
17945        // Delete the child packages data
17946        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17947        for (int i = 0; i < childCount; i++) {
17948            PackageSetting childPs;
17949            synchronized (mPackages) {
17950                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17951            }
17952            if (childPs != null) {
17953                PackageRemovedInfo childOutInfo = (outInfo != null
17954                        && outInfo.removedChildPackages != null)
17955                        ? outInfo.removedChildPackages.get(childPs.name) : null;
17956                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
17957                        && (replacingPackage != null
17958                        && !replacingPackage.hasChildPackage(childPs.name))
17959                        ? flags & ~DELETE_KEEP_DATA : flags;
17960                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
17961                        deleteFlags, writeSettings);
17962            }
17963        }
17964
17965        // Delete application code and resources only for parent packages
17966        if (ps.parentPackageName == null) {
17967            if (deleteCodeAndResources && (outInfo != null)) {
17968                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
17969                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
17970                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
17971            }
17972        }
17973
17974        return true;
17975    }
17976
17977    @Override
17978    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
17979            int userId) {
17980        mContext.enforceCallingOrSelfPermission(
17981                android.Manifest.permission.DELETE_PACKAGES, null);
17982        synchronized (mPackages) {
17983            PackageSetting ps = mSettings.mPackages.get(packageName);
17984            if (ps == null) {
17985                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
17986                return false;
17987            }
17988            // Cannot block uninstall of static shared libs as they are
17989            // considered a part of the using app (emulating static linking).
17990            // Also static libs are installed always on internal storage.
17991            PackageParser.Package pkg = mPackages.get(packageName);
17992            if (pkg != null && pkg.staticSharedLibName != null) {
17993                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
17994                        + " providing static shared library: " + pkg.staticSharedLibName);
17995                return false;
17996            }
17997            if (!ps.getInstalled(userId)) {
17998                // Can't block uninstall for an app that is not installed or enabled.
17999                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
18000                return false;
18001            }
18002            ps.setBlockUninstall(blockUninstall, userId);
18003            mSettings.writePackageRestrictionsLPr(userId);
18004        }
18005        return true;
18006    }
18007
18008    @Override
18009    public boolean getBlockUninstallForUser(String packageName, int userId) {
18010        synchronized (mPackages) {
18011            PackageSetting ps = mSettings.mPackages.get(packageName);
18012            if (ps == null) {
18013                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
18014                return false;
18015            }
18016            return ps.getBlockUninstall(userId);
18017        }
18018    }
18019
18020    @Override
18021    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18022        int callingUid = Binder.getCallingUid();
18023        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
18024            throw new SecurityException(
18025                    "setRequiredForSystemUser can only be run by the system or root");
18026        }
18027        synchronized (mPackages) {
18028            PackageSetting ps = mSettings.mPackages.get(packageName);
18029            if (ps == null) {
18030                Log.w(TAG, "Package doesn't exist: " + packageName);
18031                return false;
18032            }
18033            if (systemUserApp) {
18034                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18035            } else {
18036                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18037            }
18038            mSettings.writeLPr();
18039        }
18040        return true;
18041    }
18042
18043    /*
18044     * This method handles package deletion in general
18045     */
18046    private boolean deletePackageLIF(String packageName, UserHandle user,
18047            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18048            PackageRemovedInfo outInfo, boolean writeSettings,
18049            PackageParser.Package replacingPackage) {
18050        if (packageName == null) {
18051            Slog.w(TAG, "Attempt to delete null packageName.");
18052            return false;
18053        }
18054
18055        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18056
18057        PackageSetting ps;
18058        synchronized (mPackages) {
18059            ps = mSettings.mPackages.get(packageName);
18060            if (ps == null) {
18061                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18062                return false;
18063            }
18064
18065            if (ps.parentPackageName != null && (!isSystemApp(ps)
18066                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18067                if (DEBUG_REMOVE) {
18068                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18069                            + ((user == null) ? UserHandle.USER_ALL : user));
18070                }
18071                final int removedUserId = (user != null) ? user.getIdentifier()
18072                        : UserHandle.USER_ALL;
18073                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18074                    return false;
18075                }
18076                markPackageUninstalledForUserLPw(ps, user);
18077                scheduleWritePackageRestrictionsLocked(user);
18078                return true;
18079            }
18080        }
18081
18082        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18083                && user.getIdentifier() != UserHandle.USER_ALL)) {
18084            // The caller is asking that the package only be deleted for a single
18085            // user.  To do this, we just mark its uninstalled state and delete
18086            // its data. If this is a system app, we only allow this to happen if
18087            // they have set the special DELETE_SYSTEM_APP which requests different
18088            // semantics than normal for uninstalling system apps.
18089            markPackageUninstalledForUserLPw(ps, user);
18090
18091            if (!isSystemApp(ps)) {
18092                // Do not uninstall the APK if an app should be cached
18093                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18094                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18095                    // Other user still have this package installed, so all
18096                    // we need to do is clear this user's data and save that
18097                    // it is uninstalled.
18098                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18099                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18100                        return false;
18101                    }
18102                    scheduleWritePackageRestrictionsLocked(user);
18103                    return true;
18104                } else {
18105                    // We need to set it back to 'installed' so the uninstall
18106                    // broadcasts will be sent correctly.
18107                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18108                    ps.setInstalled(true, user.getIdentifier());
18109                    mSettings.writeKernelMappingLPr(ps);
18110                }
18111            } else {
18112                // This is a system app, so we assume that the
18113                // other users still have this package installed, so all
18114                // we need to do is clear this user's data and save that
18115                // it is uninstalled.
18116                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18117                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18118                    return false;
18119                }
18120                scheduleWritePackageRestrictionsLocked(user);
18121                return true;
18122            }
18123        }
18124
18125        // If we are deleting a composite package for all users, keep track
18126        // of result for each child.
18127        if (ps.childPackageNames != null && outInfo != null) {
18128            synchronized (mPackages) {
18129                final int childCount = ps.childPackageNames.size();
18130                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18131                for (int i = 0; i < childCount; i++) {
18132                    String childPackageName = ps.childPackageNames.get(i);
18133                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
18134                    childInfo.removedPackage = childPackageName;
18135                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18136                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18137                    if (childPs != null) {
18138                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18139                    }
18140                }
18141            }
18142        }
18143
18144        boolean ret = false;
18145        if (isSystemApp(ps)) {
18146            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18147            // When an updated system application is deleted we delete the existing resources
18148            // as well and fall back to existing code in system partition
18149            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18150        } else {
18151            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18152            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18153                    outInfo, writeSettings, replacingPackage);
18154        }
18155
18156        // Take a note whether we deleted the package for all users
18157        if (outInfo != null) {
18158            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18159            if (outInfo.removedChildPackages != null) {
18160                synchronized (mPackages) {
18161                    final int childCount = outInfo.removedChildPackages.size();
18162                    for (int i = 0; i < childCount; i++) {
18163                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18164                        if (childInfo != null) {
18165                            childInfo.removedForAllUsers = mPackages.get(
18166                                    childInfo.removedPackage) == null;
18167                        }
18168                    }
18169                }
18170            }
18171            // If we uninstalled an update to a system app there may be some
18172            // child packages that appeared as they are declared in the system
18173            // app but were not declared in the update.
18174            if (isSystemApp(ps)) {
18175                synchronized (mPackages) {
18176                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18177                    final int childCount = (updatedPs.childPackageNames != null)
18178                            ? updatedPs.childPackageNames.size() : 0;
18179                    for (int i = 0; i < childCount; i++) {
18180                        String childPackageName = updatedPs.childPackageNames.get(i);
18181                        if (outInfo.removedChildPackages == null
18182                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18183                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18184                            if (childPs == null) {
18185                                continue;
18186                            }
18187                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18188                            installRes.name = childPackageName;
18189                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18190                            installRes.pkg = mPackages.get(childPackageName);
18191                            installRes.uid = childPs.pkg.applicationInfo.uid;
18192                            if (outInfo.appearedChildPackages == null) {
18193                                outInfo.appearedChildPackages = new ArrayMap<>();
18194                            }
18195                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18196                        }
18197                    }
18198                }
18199            }
18200        }
18201
18202        return ret;
18203    }
18204
18205    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18206        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18207                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18208        for (int nextUserId : userIds) {
18209            if (DEBUG_REMOVE) {
18210                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18211            }
18212            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18213                    false /*installed*/,
18214                    true /*stopped*/,
18215                    true /*notLaunched*/,
18216                    false /*hidden*/,
18217                    false /*suspended*/,
18218                    false /*instantApp*/,
18219                    null /*lastDisableAppCaller*/,
18220                    null /*enabledComponents*/,
18221                    null /*disabledComponents*/,
18222                    false /*blockUninstall*/,
18223                    ps.readUserState(nextUserId).domainVerificationStatus,
18224                    0, PackageManager.INSTALL_REASON_UNKNOWN);
18225        }
18226        mSettings.writeKernelMappingLPr(ps);
18227    }
18228
18229    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18230            PackageRemovedInfo outInfo) {
18231        final PackageParser.Package pkg;
18232        synchronized (mPackages) {
18233            pkg = mPackages.get(ps.name);
18234        }
18235
18236        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18237                : new int[] {userId};
18238        for (int nextUserId : userIds) {
18239            if (DEBUG_REMOVE) {
18240                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18241                        + nextUserId);
18242            }
18243
18244            destroyAppDataLIF(pkg, userId,
18245                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18246            destroyAppProfilesLIF(pkg, userId);
18247            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18248            schedulePackageCleaning(ps.name, nextUserId, false);
18249            synchronized (mPackages) {
18250                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18251                    scheduleWritePackageRestrictionsLocked(nextUserId);
18252                }
18253                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18254            }
18255        }
18256
18257        if (outInfo != null) {
18258            outInfo.removedPackage = ps.name;
18259            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18260            outInfo.removedAppId = ps.appId;
18261            outInfo.removedUsers = userIds;
18262        }
18263
18264        return true;
18265    }
18266
18267    private final class ClearStorageConnection implements ServiceConnection {
18268        IMediaContainerService mContainerService;
18269
18270        @Override
18271        public void onServiceConnected(ComponentName name, IBinder service) {
18272            synchronized (this) {
18273                mContainerService = IMediaContainerService.Stub
18274                        .asInterface(Binder.allowBlocking(service));
18275                notifyAll();
18276            }
18277        }
18278
18279        @Override
18280        public void onServiceDisconnected(ComponentName name) {
18281        }
18282    }
18283
18284    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18285        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18286
18287        final boolean mounted;
18288        if (Environment.isExternalStorageEmulated()) {
18289            mounted = true;
18290        } else {
18291            final String status = Environment.getExternalStorageState();
18292
18293            mounted = status.equals(Environment.MEDIA_MOUNTED)
18294                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18295        }
18296
18297        if (!mounted) {
18298            return;
18299        }
18300
18301        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18302        int[] users;
18303        if (userId == UserHandle.USER_ALL) {
18304            users = sUserManager.getUserIds();
18305        } else {
18306            users = new int[] { userId };
18307        }
18308        final ClearStorageConnection conn = new ClearStorageConnection();
18309        if (mContext.bindServiceAsUser(
18310                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18311            try {
18312                for (int curUser : users) {
18313                    long timeout = SystemClock.uptimeMillis() + 5000;
18314                    synchronized (conn) {
18315                        long now;
18316                        while (conn.mContainerService == null &&
18317                                (now = SystemClock.uptimeMillis()) < timeout) {
18318                            try {
18319                                conn.wait(timeout - now);
18320                            } catch (InterruptedException e) {
18321                            }
18322                        }
18323                    }
18324                    if (conn.mContainerService == null) {
18325                        return;
18326                    }
18327
18328                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18329                    clearDirectory(conn.mContainerService,
18330                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18331                    if (allData) {
18332                        clearDirectory(conn.mContainerService,
18333                                userEnv.buildExternalStorageAppDataDirs(packageName));
18334                        clearDirectory(conn.mContainerService,
18335                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18336                    }
18337                }
18338            } finally {
18339                mContext.unbindService(conn);
18340            }
18341        }
18342    }
18343
18344    @Override
18345    public void clearApplicationProfileData(String packageName) {
18346        enforceSystemOrRoot("Only the system can clear all profile data");
18347
18348        final PackageParser.Package pkg;
18349        synchronized (mPackages) {
18350            pkg = mPackages.get(packageName);
18351        }
18352
18353        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18354            synchronized (mInstallLock) {
18355                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18356            }
18357        }
18358    }
18359
18360    @Override
18361    public void clearApplicationUserData(final String packageName,
18362            final IPackageDataObserver observer, final int userId) {
18363        mContext.enforceCallingOrSelfPermission(
18364                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18365
18366        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18367                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18368
18369        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18370            throw new SecurityException("Cannot clear data for a protected package: "
18371                    + packageName);
18372        }
18373        // Queue up an async operation since the package deletion may take a little while.
18374        mHandler.post(new Runnable() {
18375            public void run() {
18376                mHandler.removeCallbacks(this);
18377                final boolean succeeded;
18378                try (PackageFreezer freezer = freezePackage(packageName,
18379                        "clearApplicationUserData")) {
18380                    synchronized (mInstallLock) {
18381                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18382                    }
18383                    clearExternalStorageDataSync(packageName, userId, true);
18384                    synchronized (mPackages) {
18385                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18386                                packageName, userId);
18387                    }
18388                }
18389                if (succeeded) {
18390                    // invoke DeviceStorageMonitor's update method to clear any notifications
18391                    DeviceStorageMonitorInternal dsm = LocalServices
18392                            .getService(DeviceStorageMonitorInternal.class);
18393                    if (dsm != null) {
18394                        dsm.checkMemory();
18395                    }
18396                }
18397                if(observer != null) {
18398                    try {
18399                        observer.onRemoveCompleted(packageName, succeeded);
18400                    } catch (RemoteException e) {
18401                        Log.i(TAG, "Observer no longer exists.");
18402                    }
18403                } //end if observer
18404            } //end run
18405        });
18406    }
18407
18408    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18409        if (packageName == null) {
18410            Slog.w(TAG, "Attempt to delete null packageName.");
18411            return false;
18412        }
18413
18414        // Try finding details about the requested package
18415        PackageParser.Package pkg;
18416        synchronized (mPackages) {
18417            pkg = mPackages.get(packageName);
18418            if (pkg == null) {
18419                final PackageSetting ps = mSettings.mPackages.get(packageName);
18420                if (ps != null) {
18421                    pkg = ps.pkg;
18422                }
18423            }
18424
18425            if (pkg == null) {
18426                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18427                return false;
18428            }
18429
18430            PackageSetting ps = (PackageSetting) pkg.mExtras;
18431            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18432        }
18433
18434        clearAppDataLIF(pkg, userId,
18435                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18436
18437        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18438        removeKeystoreDataIfNeeded(userId, appId);
18439
18440        UserManagerInternal umInternal = getUserManagerInternal();
18441        final int flags;
18442        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18443            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18444        } else if (umInternal.isUserRunning(userId)) {
18445            flags = StorageManager.FLAG_STORAGE_DE;
18446        } else {
18447            flags = 0;
18448        }
18449        prepareAppDataContentsLIF(pkg, userId, flags);
18450
18451        return true;
18452    }
18453
18454    /**
18455     * Reverts user permission state changes (permissions and flags) in
18456     * all packages for a given user.
18457     *
18458     * @param userId The device user for which to do a reset.
18459     */
18460    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18461        final int packageCount = mPackages.size();
18462        for (int i = 0; i < packageCount; i++) {
18463            PackageParser.Package pkg = mPackages.valueAt(i);
18464            PackageSetting ps = (PackageSetting) pkg.mExtras;
18465            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18466        }
18467    }
18468
18469    private void resetNetworkPolicies(int userId) {
18470        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18471    }
18472
18473    /**
18474     * Reverts user permission state changes (permissions and flags).
18475     *
18476     * @param ps The package for which to reset.
18477     * @param userId The device user for which to do a reset.
18478     */
18479    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18480            final PackageSetting ps, final int userId) {
18481        if (ps.pkg == null) {
18482            return;
18483        }
18484
18485        // These are flags that can change base on user actions.
18486        final int userSettableMask = FLAG_PERMISSION_USER_SET
18487                | FLAG_PERMISSION_USER_FIXED
18488                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18489                | FLAG_PERMISSION_REVIEW_REQUIRED;
18490
18491        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18492                | FLAG_PERMISSION_POLICY_FIXED;
18493
18494        boolean writeInstallPermissions = false;
18495        boolean writeRuntimePermissions = false;
18496
18497        final int permissionCount = ps.pkg.requestedPermissions.size();
18498        for (int i = 0; i < permissionCount; i++) {
18499            String permission = ps.pkg.requestedPermissions.get(i);
18500
18501            BasePermission bp = mSettings.mPermissions.get(permission);
18502            if (bp == null) {
18503                continue;
18504            }
18505
18506            // If shared user we just reset the state to which only this app contributed.
18507            if (ps.sharedUser != null) {
18508                boolean used = false;
18509                final int packageCount = ps.sharedUser.packages.size();
18510                for (int j = 0; j < packageCount; j++) {
18511                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18512                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18513                            && pkg.pkg.requestedPermissions.contains(permission)) {
18514                        used = true;
18515                        break;
18516                    }
18517                }
18518                if (used) {
18519                    continue;
18520                }
18521            }
18522
18523            PermissionsState permissionsState = ps.getPermissionsState();
18524
18525            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
18526
18527            // Always clear the user settable flags.
18528            final boolean hasInstallState = permissionsState.getInstallPermissionState(
18529                    bp.name) != null;
18530            // If permission review is enabled and this is a legacy app, mark the
18531            // permission as requiring a review as this is the initial state.
18532            int flags = 0;
18533            if (mPermissionReviewRequired
18534                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18535                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18536            }
18537            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18538                if (hasInstallState) {
18539                    writeInstallPermissions = true;
18540                } else {
18541                    writeRuntimePermissions = true;
18542                }
18543            }
18544
18545            // Below is only runtime permission handling.
18546            if (!bp.isRuntime()) {
18547                continue;
18548            }
18549
18550            // Never clobber system or policy.
18551            if ((oldFlags & policyOrSystemFlags) != 0) {
18552                continue;
18553            }
18554
18555            // If this permission was granted by default, make sure it is.
18556            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18557                if (permissionsState.grantRuntimePermission(bp, userId)
18558                        != PERMISSION_OPERATION_FAILURE) {
18559                    writeRuntimePermissions = true;
18560                }
18561            // If permission review is enabled the permissions for a legacy apps
18562            // are represented as constantly granted runtime ones, so don't revoke.
18563            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18564                // Otherwise, reset the permission.
18565                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18566                switch (revokeResult) {
18567                    case PERMISSION_OPERATION_SUCCESS:
18568                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18569                        writeRuntimePermissions = true;
18570                        final int appId = ps.appId;
18571                        mHandler.post(new Runnable() {
18572                            @Override
18573                            public void run() {
18574                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18575                            }
18576                        });
18577                    } break;
18578                }
18579            }
18580        }
18581
18582        // Synchronously write as we are taking permissions away.
18583        if (writeRuntimePermissions) {
18584            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18585        }
18586
18587        // Synchronously write as we are taking permissions away.
18588        if (writeInstallPermissions) {
18589            mSettings.writeLPr();
18590        }
18591    }
18592
18593    /**
18594     * Remove entries from the keystore daemon. Will only remove it if the
18595     * {@code appId} is valid.
18596     */
18597    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18598        if (appId < 0) {
18599            return;
18600        }
18601
18602        final KeyStore keyStore = KeyStore.getInstance();
18603        if (keyStore != null) {
18604            if (userId == UserHandle.USER_ALL) {
18605                for (final int individual : sUserManager.getUserIds()) {
18606                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18607                }
18608            } else {
18609                keyStore.clearUid(UserHandle.getUid(userId, appId));
18610            }
18611        } else {
18612            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18613        }
18614    }
18615
18616    @Override
18617    public void deleteApplicationCacheFiles(final String packageName,
18618            final IPackageDataObserver observer) {
18619        final int userId = UserHandle.getCallingUserId();
18620        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18621    }
18622
18623    @Override
18624    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18625            final IPackageDataObserver observer) {
18626        mContext.enforceCallingOrSelfPermission(
18627                android.Manifest.permission.DELETE_CACHE_FILES, null);
18628        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18629                /* requireFullPermission= */ true, /* checkShell= */ false,
18630                "delete application cache files");
18631
18632        final PackageParser.Package pkg;
18633        synchronized (mPackages) {
18634            pkg = mPackages.get(packageName);
18635        }
18636
18637        // Queue up an async operation since the package deletion may take a little while.
18638        mHandler.post(new Runnable() {
18639            public void run() {
18640                synchronized (mInstallLock) {
18641                    final int flags = StorageManager.FLAG_STORAGE_DE
18642                            | StorageManager.FLAG_STORAGE_CE;
18643                    // We're only clearing cache files, so we don't care if the
18644                    // app is unfrozen and still able to run
18645                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18646                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18647                }
18648                clearExternalStorageDataSync(packageName, userId, false);
18649                if (observer != null) {
18650                    try {
18651                        observer.onRemoveCompleted(packageName, true);
18652                    } catch (RemoteException e) {
18653                        Log.i(TAG, "Observer no longer exists.");
18654                    }
18655                }
18656            }
18657        });
18658    }
18659
18660    @Override
18661    public void getPackageSizeInfo(final String packageName, int userHandle,
18662            final IPackageStatsObserver observer) {
18663        throw new UnsupportedOperationException(
18664                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
18665    }
18666
18667    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18668        final PackageSetting ps;
18669        synchronized (mPackages) {
18670            ps = mSettings.mPackages.get(packageName);
18671            if (ps == null) {
18672                Slog.w(TAG, "Failed to find settings for " + packageName);
18673                return false;
18674            }
18675        }
18676
18677        final String[] packageNames = { packageName };
18678        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18679        final String[] codePaths = { ps.codePathString };
18680
18681        try {
18682            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18683                    ps.appId, ceDataInodes, codePaths, stats);
18684
18685            // For now, ignore code size of packages on system partition
18686            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18687                stats.codeSize = 0;
18688            }
18689
18690            // External clients expect these to be tracked separately
18691            stats.dataSize -= stats.cacheSize;
18692
18693        } catch (InstallerException e) {
18694            Slog.w(TAG, String.valueOf(e));
18695            return false;
18696        }
18697
18698        return true;
18699    }
18700
18701    private int getUidTargetSdkVersionLockedLPr(int uid) {
18702        Object obj = mSettings.getUserIdLPr(uid);
18703        if (obj instanceof SharedUserSetting) {
18704            final SharedUserSetting sus = (SharedUserSetting) obj;
18705            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18706            final Iterator<PackageSetting> it = sus.packages.iterator();
18707            while (it.hasNext()) {
18708                final PackageSetting ps = it.next();
18709                if (ps.pkg != null) {
18710                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18711                    if (v < vers) vers = v;
18712                }
18713            }
18714            return vers;
18715        } else if (obj instanceof PackageSetting) {
18716            final PackageSetting ps = (PackageSetting) obj;
18717            if (ps.pkg != null) {
18718                return ps.pkg.applicationInfo.targetSdkVersion;
18719            }
18720        }
18721        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18722    }
18723
18724    @Override
18725    public void addPreferredActivity(IntentFilter filter, int match,
18726            ComponentName[] set, ComponentName activity, int userId) {
18727        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18728                "Adding preferred");
18729    }
18730
18731    private void addPreferredActivityInternal(IntentFilter filter, int match,
18732            ComponentName[] set, ComponentName activity, boolean always, int userId,
18733            String opname) {
18734        // writer
18735        int callingUid = Binder.getCallingUid();
18736        enforceCrossUserPermission(callingUid, userId,
18737                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18738        if (filter.countActions() == 0) {
18739            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18740            return;
18741        }
18742        synchronized (mPackages) {
18743            if (mContext.checkCallingOrSelfPermission(
18744                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18745                    != PackageManager.PERMISSION_GRANTED) {
18746                if (getUidTargetSdkVersionLockedLPr(callingUid)
18747                        < Build.VERSION_CODES.FROYO) {
18748                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18749                            + callingUid);
18750                    return;
18751                }
18752                mContext.enforceCallingOrSelfPermission(
18753                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18754            }
18755
18756            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18757            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18758                    + userId + ":");
18759            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18760            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18761            scheduleWritePackageRestrictionsLocked(userId);
18762            postPreferredActivityChangedBroadcast(userId);
18763        }
18764    }
18765
18766    private void postPreferredActivityChangedBroadcast(int userId) {
18767        mHandler.post(() -> {
18768            final IActivityManager am = ActivityManager.getService();
18769            if (am == null) {
18770                return;
18771            }
18772
18773            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18774            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18775            try {
18776                am.broadcastIntent(null, intent, null, null,
18777                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18778                        null, false, false, userId);
18779            } catch (RemoteException e) {
18780            }
18781        });
18782    }
18783
18784    @Override
18785    public void replacePreferredActivity(IntentFilter filter, int match,
18786            ComponentName[] set, ComponentName activity, int userId) {
18787        if (filter.countActions() != 1) {
18788            throw new IllegalArgumentException(
18789                    "replacePreferredActivity expects filter to have only 1 action.");
18790        }
18791        if (filter.countDataAuthorities() != 0
18792                || filter.countDataPaths() != 0
18793                || filter.countDataSchemes() > 1
18794                || filter.countDataTypes() != 0) {
18795            throw new IllegalArgumentException(
18796                    "replacePreferredActivity expects filter to have no data authorities, " +
18797                    "paths, or types; and at most one scheme.");
18798        }
18799
18800        final int callingUid = Binder.getCallingUid();
18801        enforceCrossUserPermission(callingUid, userId,
18802                true /* requireFullPermission */, false /* checkShell */,
18803                "replace preferred activity");
18804        synchronized (mPackages) {
18805            if (mContext.checkCallingOrSelfPermission(
18806                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18807                    != PackageManager.PERMISSION_GRANTED) {
18808                if (getUidTargetSdkVersionLockedLPr(callingUid)
18809                        < Build.VERSION_CODES.FROYO) {
18810                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18811                            + Binder.getCallingUid());
18812                    return;
18813                }
18814                mContext.enforceCallingOrSelfPermission(
18815                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18816            }
18817
18818            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18819            if (pir != null) {
18820                // Get all of the existing entries that exactly match this filter.
18821                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18822                if (existing != null && existing.size() == 1) {
18823                    PreferredActivity cur = existing.get(0);
18824                    if (DEBUG_PREFERRED) {
18825                        Slog.i(TAG, "Checking replace of preferred:");
18826                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18827                        if (!cur.mPref.mAlways) {
18828                            Slog.i(TAG, "  -- CUR; not mAlways!");
18829                        } else {
18830                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18831                            Slog.i(TAG, "  -- CUR: mSet="
18832                                    + Arrays.toString(cur.mPref.mSetComponents));
18833                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18834                            Slog.i(TAG, "  -- NEW: mMatch="
18835                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18836                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18837                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18838                        }
18839                    }
18840                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18841                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18842                            && cur.mPref.sameSet(set)) {
18843                        // Setting the preferred activity to what it happens to be already
18844                        if (DEBUG_PREFERRED) {
18845                            Slog.i(TAG, "Replacing with same preferred activity "
18846                                    + cur.mPref.mShortComponent + " for user "
18847                                    + userId + ":");
18848                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18849                        }
18850                        return;
18851                    }
18852                }
18853
18854                if (existing != null) {
18855                    if (DEBUG_PREFERRED) {
18856                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
18857                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18858                    }
18859                    for (int i = 0; i < existing.size(); i++) {
18860                        PreferredActivity pa = existing.get(i);
18861                        if (DEBUG_PREFERRED) {
18862                            Slog.i(TAG, "Removing existing preferred activity "
18863                                    + pa.mPref.mComponent + ":");
18864                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
18865                        }
18866                        pir.removeFilter(pa);
18867                    }
18868                }
18869            }
18870            addPreferredActivityInternal(filter, match, set, activity, true, userId,
18871                    "Replacing preferred");
18872        }
18873    }
18874
18875    @Override
18876    public void clearPackagePreferredActivities(String packageName) {
18877        final int uid = Binder.getCallingUid();
18878        // writer
18879        synchronized (mPackages) {
18880            PackageParser.Package pkg = mPackages.get(packageName);
18881            if (pkg == null || pkg.applicationInfo.uid != uid) {
18882                if (mContext.checkCallingOrSelfPermission(
18883                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18884                        != PackageManager.PERMISSION_GRANTED) {
18885                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
18886                            < Build.VERSION_CODES.FROYO) {
18887                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
18888                                + Binder.getCallingUid());
18889                        return;
18890                    }
18891                    mContext.enforceCallingOrSelfPermission(
18892                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18893                }
18894            }
18895
18896            int user = UserHandle.getCallingUserId();
18897            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
18898                scheduleWritePackageRestrictionsLocked(user);
18899            }
18900        }
18901    }
18902
18903    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18904    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
18905        ArrayList<PreferredActivity> removed = null;
18906        boolean changed = false;
18907        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18908            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
18909            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18910            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
18911                continue;
18912            }
18913            Iterator<PreferredActivity> it = pir.filterIterator();
18914            while (it.hasNext()) {
18915                PreferredActivity pa = it.next();
18916                // Mark entry for removal only if it matches the package name
18917                // and the entry is of type "always".
18918                if (packageName == null ||
18919                        (pa.mPref.mComponent.getPackageName().equals(packageName)
18920                                && pa.mPref.mAlways)) {
18921                    if (removed == null) {
18922                        removed = new ArrayList<PreferredActivity>();
18923                    }
18924                    removed.add(pa);
18925                }
18926            }
18927            if (removed != null) {
18928                for (int j=0; j<removed.size(); j++) {
18929                    PreferredActivity pa = removed.get(j);
18930                    pir.removeFilter(pa);
18931                }
18932                changed = true;
18933            }
18934        }
18935        if (changed) {
18936            postPreferredActivityChangedBroadcast(userId);
18937        }
18938        return changed;
18939    }
18940
18941    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18942    private void clearIntentFilterVerificationsLPw(int userId) {
18943        final int packageCount = mPackages.size();
18944        for (int i = 0; i < packageCount; i++) {
18945            PackageParser.Package pkg = mPackages.valueAt(i);
18946            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
18947        }
18948    }
18949
18950    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18951    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
18952        if (userId == UserHandle.USER_ALL) {
18953            if (mSettings.removeIntentFilterVerificationLPw(packageName,
18954                    sUserManager.getUserIds())) {
18955                for (int oneUserId : sUserManager.getUserIds()) {
18956                    scheduleWritePackageRestrictionsLocked(oneUserId);
18957                }
18958            }
18959        } else {
18960            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
18961                scheduleWritePackageRestrictionsLocked(userId);
18962            }
18963        }
18964    }
18965
18966    void clearDefaultBrowserIfNeeded(String packageName) {
18967        for (int oneUserId : sUserManager.getUserIds()) {
18968            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
18969            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
18970            if (packageName.equals(defaultBrowserPackageName)) {
18971                setDefaultBrowserPackageName(null, oneUserId);
18972            }
18973        }
18974    }
18975
18976    @Override
18977    public void resetApplicationPreferences(int userId) {
18978        mContext.enforceCallingOrSelfPermission(
18979                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18980        final long identity = Binder.clearCallingIdentity();
18981        // writer
18982        try {
18983            synchronized (mPackages) {
18984                clearPackagePreferredActivitiesLPw(null, userId);
18985                mSettings.applyDefaultPreferredAppsLPw(this, userId);
18986                // TODO: We have to reset the default SMS and Phone. This requires
18987                // significant refactoring to keep all default apps in the package
18988                // manager (cleaner but more work) or have the services provide
18989                // callbacks to the package manager to request a default app reset.
18990                applyFactoryDefaultBrowserLPw(userId);
18991                clearIntentFilterVerificationsLPw(userId);
18992                primeDomainVerificationsLPw(userId);
18993                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
18994                scheduleWritePackageRestrictionsLocked(userId);
18995            }
18996            resetNetworkPolicies(userId);
18997        } finally {
18998            Binder.restoreCallingIdentity(identity);
18999        }
19000    }
19001
19002    @Override
19003    public int getPreferredActivities(List<IntentFilter> outFilters,
19004            List<ComponentName> outActivities, String packageName) {
19005
19006        int num = 0;
19007        final int userId = UserHandle.getCallingUserId();
19008        // reader
19009        synchronized (mPackages) {
19010            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19011            if (pir != null) {
19012                final Iterator<PreferredActivity> it = pir.filterIterator();
19013                while (it.hasNext()) {
19014                    final PreferredActivity pa = it.next();
19015                    if (packageName == null
19016                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19017                                    && pa.mPref.mAlways)) {
19018                        if (outFilters != null) {
19019                            outFilters.add(new IntentFilter(pa));
19020                        }
19021                        if (outActivities != null) {
19022                            outActivities.add(pa.mPref.mComponent);
19023                        }
19024                    }
19025                }
19026            }
19027        }
19028
19029        return num;
19030    }
19031
19032    @Override
19033    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19034            int userId) {
19035        int callingUid = Binder.getCallingUid();
19036        if (callingUid != Process.SYSTEM_UID) {
19037            throw new SecurityException(
19038                    "addPersistentPreferredActivity can only be run by the system");
19039        }
19040        if (filter.countActions() == 0) {
19041            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19042            return;
19043        }
19044        synchronized (mPackages) {
19045            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19046                    ":");
19047            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19048            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19049                    new PersistentPreferredActivity(filter, activity));
19050            scheduleWritePackageRestrictionsLocked(userId);
19051            postPreferredActivityChangedBroadcast(userId);
19052        }
19053    }
19054
19055    @Override
19056    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19057        int callingUid = Binder.getCallingUid();
19058        if (callingUid != Process.SYSTEM_UID) {
19059            throw new SecurityException(
19060                    "clearPackagePersistentPreferredActivities can only be run by the system");
19061        }
19062        ArrayList<PersistentPreferredActivity> removed = null;
19063        boolean changed = false;
19064        synchronized (mPackages) {
19065            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19066                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19067                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19068                        .valueAt(i);
19069                if (userId != thisUserId) {
19070                    continue;
19071                }
19072                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19073                while (it.hasNext()) {
19074                    PersistentPreferredActivity ppa = it.next();
19075                    // Mark entry for removal only if it matches the package name.
19076                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19077                        if (removed == null) {
19078                            removed = new ArrayList<PersistentPreferredActivity>();
19079                        }
19080                        removed.add(ppa);
19081                    }
19082                }
19083                if (removed != null) {
19084                    for (int j=0; j<removed.size(); j++) {
19085                        PersistentPreferredActivity ppa = removed.get(j);
19086                        ppir.removeFilter(ppa);
19087                    }
19088                    changed = true;
19089                }
19090            }
19091
19092            if (changed) {
19093                scheduleWritePackageRestrictionsLocked(userId);
19094                postPreferredActivityChangedBroadcast(userId);
19095            }
19096        }
19097    }
19098
19099    /**
19100     * Common machinery for picking apart a restored XML blob and passing
19101     * it to a caller-supplied functor to be applied to the running system.
19102     */
19103    private void restoreFromXml(XmlPullParser parser, int userId,
19104            String expectedStartTag, BlobXmlRestorer functor)
19105            throws IOException, XmlPullParserException {
19106        int type;
19107        while ((type = parser.next()) != XmlPullParser.START_TAG
19108                && type != XmlPullParser.END_DOCUMENT) {
19109        }
19110        if (type != XmlPullParser.START_TAG) {
19111            // oops didn't find a start tag?!
19112            if (DEBUG_BACKUP) {
19113                Slog.e(TAG, "Didn't find start tag during restore");
19114            }
19115            return;
19116        }
19117Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19118        // this is supposed to be TAG_PREFERRED_BACKUP
19119        if (!expectedStartTag.equals(parser.getName())) {
19120            if (DEBUG_BACKUP) {
19121                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19122            }
19123            return;
19124        }
19125
19126        // skip interfering stuff, then we're aligned with the backing implementation
19127        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19128Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19129        functor.apply(parser, userId);
19130    }
19131
19132    private interface BlobXmlRestorer {
19133        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19134    }
19135
19136    /**
19137     * Non-Binder method, support for the backup/restore mechanism: write the
19138     * full set of preferred activities in its canonical XML format.  Returns the
19139     * XML output as a byte array, or null if there is none.
19140     */
19141    @Override
19142    public byte[] getPreferredActivityBackup(int userId) {
19143        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19144            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19145        }
19146
19147        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19148        try {
19149            final XmlSerializer serializer = new FastXmlSerializer();
19150            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19151            serializer.startDocument(null, true);
19152            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19153
19154            synchronized (mPackages) {
19155                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19156            }
19157
19158            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19159            serializer.endDocument();
19160            serializer.flush();
19161        } catch (Exception e) {
19162            if (DEBUG_BACKUP) {
19163                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19164            }
19165            return null;
19166        }
19167
19168        return dataStream.toByteArray();
19169    }
19170
19171    @Override
19172    public void restorePreferredActivities(byte[] backup, int userId) {
19173        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19174            throw new SecurityException("Only the system may call restorePreferredActivities()");
19175        }
19176
19177        try {
19178            final XmlPullParser parser = Xml.newPullParser();
19179            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19180            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19181                    new BlobXmlRestorer() {
19182                        @Override
19183                        public void apply(XmlPullParser parser, int userId)
19184                                throws XmlPullParserException, IOException {
19185                            synchronized (mPackages) {
19186                                mSettings.readPreferredActivitiesLPw(parser, userId);
19187                            }
19188                        }
19189                    } );
19190        } catch (Exception e) {
19191            if (DEBUG_BACKUP) {
19192                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19193            }
19194        }
19195    }
19196
19197    /**
19198     * Non-Binder method, support for the backup/restore mechanism: write the
19199     * default browser (etc) settings in its canonical XML format.  Returns the default
19200     * browser XML representation as a byte array, or null if there is none.
19201     */
19202    @Override
19203    public byte[] getDefaultAppsBackup(int userId) {
19204        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19205            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19206        }
19207
19208        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19209        try {
19210            final XmlSerializer serializer = new FastXmlSerializer();
19211            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19212            serializer.startDocument(null, true);
19213            serializer.startTag(null, TAG_DEFAULT_APPS);
19214
19215            synchronized (mPackages) {
19216                mSettings.writeDefaultAppsLPr(serializer, userId);
19217            }
19218
19219            serializer.endTag(null, TAG_DEFAULT_APPS);
19220            serializer.endDocument();
19221            serializer.flush();
19222        } catch (Exception e) {
19223            if (DEBUG_BACKUP) {
19224                Slog.e(TAG, "Unable to write default apps for backup", e);
19225            }
19226            return null;
19227        }
19228
19229        return dataStream.toByteArray();
19230    }
19231
19232    @Override
19233    public void restoreDefaultApps(byte[] backup, int userId) {
19234        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19235            throw new SecurityException("Only the system may call restoreDefaultApps()");
19236        }
19237
19238        try {
19239            final XmlPullParser parser = Xml.newPullParser();
19240            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19241            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19242                    new BlobXmlRestorer() {
19243                        @Override
19244                        public void apply(XmlPullParser parser, int userId)
19245                                throws XmlPullParserException, IOException {
19246                            synchronized (mPackages) {
19247                                mSettings.readDefaultAppsLPw(parser, userId);
19248                            }
19249                        }
19250                    } );
19251        } catch (Exception e) {
19252            if (DEBUG_BACKUP) {
19253                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19254            }
19255        }
19256    }
19257
19258    @Override
19259    public byte[] getIntentFilterVerificationBackup(int userId) {
19260        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19261            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19262        }
19263
19264        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19265        try {
19266            final XmlSerializer serializer = new FastXmlSerializer();
19267            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19268            serializer.startDocument(null, true);
19269            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19270
19271            synchronized (mPackages) {
19272                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19273            }
19274
19275            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19276            serializer.endDocument();
19277            serializer.flush();
19278        } catch (Exception e) {
19279            if (DEBUG_BACKUP) {
19280                Slog.e(TAG, "Unable to write default apps for backup", e);
19281            }
19282            return null;
19283        }
19284
19285        return dataStream.toByteArray();
19286    }
19287
19288    @Override
19289    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19290        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19291            throw new SecurityException("Only the system may call restorePreferredActivities()");
19292        }
19293
19294        try {
19295            final XmlPullParser parser = Xml.newPullParser();
19296            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19297            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19298                    new BlobXmlRestorer() {
19299                        @Override
19300                        public void apply(XmlPullParser parser, int userId)
19301                                throws XmlPullParserException, IOException {
19302                            synchronized (mPackages) {
19303                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19304                                mSettings.writeLPr();
19305                            }
19306                        }
19307                    } );
19308        } catch (Exception e) {
19309            if (DEBUG_BACKUP) {
19310                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19311            }
19312        }
19313    }
19314
19315    @Override
19316    public byte[] getPermissionGrantBackup(int userId) {
19317        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19318            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19319        }
19320
19321        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19322        try {
19323            final XmlSerializer serializer = new FastXmlSerializer();
19324            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19325            serializer.startDocument(null, true);
19326            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19327
19328            synchronized (mPackages) {
19329                serializeRuntimePermissionGrantsLPr(serializer, userId);
19330            }
19331
19332            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19333            serializer.endDocument();
19334            serializer.flush();
19335        } catch (Exception e) {
19336            if (DEBUG_BACKUP) {
19337                Slog.e(TAG, "Unable to write default apps for backup", e);
19338            }
19339            return null;
19340        }
19341
19342        return dataStream.toByteArray();
19343    }
19344
19345    @Override
19346    public void restorePermissionGrants(byte[] backup, int userId) {
19347        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19348            throw new SecurityException("Only the system may call restorePermissionGrants()");
19349        }
19350
19351        try {
19352            final XmlPullParser parser = Xml.newPullParser();
19353            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19354            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19355                    new BlobXmlRestorer() {
19356                        @Override
19357                        public void apply(XmlPullParser parser, int userId)
19358                                throws XmlPullParserException, IOException {
19359                            synchronized (mPackages) {
19360                                processRestoredPermissionGrantsLPr(parser, userId);
19361                            }
19362                        }
19363                    } );
19364        } catch (Exception e) {
19365            if (DEBUG_BACKUP) {
19366                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19367            }
19368        }
19369    }
19370
19371    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19372            throws IOException {
19373        serializer.startTag(null, TAG_ALL_GRANTS);
19374
19375        final int N = mSettings.mPackages.size();
19376        for (int i = 0; i < N; i++) {
19377            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19378            boolean pkgGrantsKnown = false;
19379
19380            PermissionsState packagePerms = ps.getPermissionsState();
19381
19382            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19383                final int grantFlags = state.getFlags();
19384                // only look at grants that are not system/policy fixed
19385                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19386                    final boolean isGranted = state.isGranted();
19387                    // And only back up the user-twiddled state bits
19388                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19389                        final String packageName = mSettings.mPackages.keyAt(i);
19390                        if (!pkgGrantsKnown) {
19391                            serializer.startTag(null, TAG_GRANT);
19392                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19393                            pkgGrantsKnown = true;
19394                        }
19395
19396                        final boolean userSet =
19397                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19398                        final boolean userFixed =
19399                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19400                        final boolean revoke =
19401                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19402
19403                        serializer.startTag(null, TAG_PERMISSION);
19404                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19405                        if (isGranted) {
19406                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19407                        }
19408                        if (userSet) {
19409                            serializer.attribute(null, ATTR_USER_SET, "true");
19410                        }
19411                        if (userFixed) {
19412                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19413                        }
19414                        if (revoke) {
19415                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19416                        }
19417                        serializer.endTag(null, TAG_PERMISSION);
19418                    }
19419                }
19420            }
19421
19422            if (pkgGrantsKnown) {
19423                serializer.endTag(null, TAG_GRANT);
19424            }
19425        }
19426
19427        serializer.endTag(null, TAG_ALL_GRANTS);
19428    }
19429
19430    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19431            throws XmlPullParserException, IOException {
19432        String pkgName = null;
19433        int outerDepth = parser.getDepth();
19434        int type;
19435        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19436                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19437            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19438                continue;
19439            }
19440
19441            final String tagName = parser.getName();
19442            if (tagName.equals(TAG_GRANT)) {
19443                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19444                if (DEBUG_BACKUP) {
19445                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19446                }
19447            } else if (tagName.equals(TAG_PERMISSION)) {
19448
19449                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19450                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19451
19452                int newFlagSet = 0;
19453                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19454                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19455                }
19456                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19457                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19458                }
19459                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19460                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19461                }
19462                if (DEBUG_BACKUP) {
19463                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
19464                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
19465                }
19466                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19467                if (ps != null) {
19468                    // Already installed so we apply the grant immediately
19469                    if (DEBUG_BACKUP) {
19470                        Slog.v(TAG, "        + already installed; applying");
19471                    }
19472                    PermissionsState perms = ps.getPermissionsState();
19473                    BasePermission bp = mSettings.mPermissions.get(permName);
19474                    if (bp != null) {
19475                        if (isGranted) {
19476                            perms.grantRuntimePermission(bp, userId);
19477                        }
19478                        if (newFlagSet != 0) {
19479                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19480                        }
19481                    }
19482                } else {
19483                    // Need to wait for post-restore install to apply the grant
19484                    if (DEBUG_BACKUP) {
19485                        Slog.v(TAG, "        - not yet installed; saving for later");
19486                    }
19487                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19488                            isGranted, newFlagSet, userId);
19489                }
19490            } else {
19491                PackageManagerService.reportSettingsProblem(Log.WARN,
19492                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19493                XmlUtils.skipCurrentTag(parser);
19494            }
19495        }
19496
19497        scheduleWriteSettingsLocked();
19498        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19499    }
19500
19501    @Override
19502    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19503            int sourceUserId, int targetUserId, int flags) {
19504        mContext.enforceCallingOrSelfPermission(
19505                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19506        int callingUid = Binder.getCallingUid();
19507        enforceOwnerRights(ownerPackage, callingUid);
19508        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19509        if (intentFilter.countActions() == 0) {
19510            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19511            return;
19512        }
19513        synchronized (mPackages) {
19514            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19515                    ownerPackage, targetUserId, flags);
19516            CrossProfileIntentResolver resolver =
19517                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19518            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19519            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19520            if (existing != null) {
19521                int size = existing.size();
19522                for (int i = 0; i < size; i++) {
19523                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19524                        return;
19525                    }
19526                }
19527            }
19528            resolver.addFilter(newFilter);
19529            scheduleWritePackageRestrictionsLocked(sourceUserId);
19530        }
19531    }
19532
19533    @Override
19534    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19535        mContext.enforceCallingOrSelfPermission(
19536                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19537        int callingUid = Binder.getCallingUid();
19538        enforceOwnerRights(ownerPackage, callingUid);
19539        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19540        synchronized (mPackages) {
19541            CrossProfileIntentResolver resolver =
19542                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19543            ArraySet<CrossProfileIntentFilter> set =
19544                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19545            for (CrossProfileIntentFilter filter : set) {
19546                if (filter.getOwnerPackage().equals(ownerPackage)) {
19547                    resolver.removeFilter(filter);
19548                }
19549            }
19550            scheduleWritePackageRestrictionsLocked(sourceUserId);
19551        }
19552    }
19553
19554    // Enforcing that callingUid is owning pkg on userId
19555    private void enforceOwnerRights(String pkg, int callingUid) {
19556        // The system owns everything.
19557        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19558            return;
19559        }
19560        int callingUserId = UserHandle.getUserId(callingUid);
19561        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19562        if (pi == null) {
19563            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19564                    + callingUserId);
19565        }
19566        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19567            throw new SecurityException("Calling uid " + callingUid
19568                    + " does not own package " + pkg);
19569        }
19570    }
19571
19572    @Override
19573    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19574        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19575    }
19576
19577    /**
19578     * Report the 'Home' activity which is currently set as "always use this one". If non is set
19579     * then reports the most likely home activity or null if there are more than one.
19580     */
19581    public ComponentName getDefaultHomeActivity(int userId) {
19582        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
19583        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
19584        if (cn != null) {
19585            return cn;
19586        }
19587
19588        // Find the launcher with the highest priority and return that component if there are no
19589        // other home activity with the same priority.
19590        int lastPriority = Integer.MIN_VALUE;
19591        ComponentName lastComponent = null;
19592        final int size = allHomeCandidates.size();
19593        for (int i = 0; i < size; i++) {
19594            final ResolveInfo ri = allHomeCandidates.get(i);
19595            if (ri.priority > lastPriority) {
19596                lastComponent = ri.activityInfo.getComponentName();
19597                lastPriority = ri.priority;
19598            } else if (ri.priority == lastPriority) {
19599                // Two components found with same priority.
19600                lastComponent = null;
19601            }
19602        }
19603        return lastComponent;
19604    }
19605
19606    private Intent getHomeIntent() {
19607        Intent intent = new Intent(Intent.ACTION_MAIN);
19608        intent.addCategory(Intent.CATEGORY_HOME);
19609        intent.addCategory(Intent.CATEGORY_DEFAULT);
19610        return intent;
19611    }
19612
19613    private IntentFilter getHomeFilter() {
19614        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19615        filter.addCategory(Intent.CATEGORY_HOME);
19616        filter.addCategory(Intent.CATEGORY_DEFAULT);
19617        return filter;
19618    }
19619
19620    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19621            int userId) {
19622        Intent intent  = getHomeIntent();
19623        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19624                PackageManager.GET_META_DATA, userId);
19625        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19626                true, false, false, userId);
19627
19628        allHomeCandidates.clear();
19629        if (list != null) {
19630            for (ResolveInfo ri : list) {
19631                allHomeCandidates.add(ri);
19632            }
19633        }
19634        return (preferred == null || preferred.activityInfo == null)
19635                ? null
19636                : new ComponentName(preferred.activityInfo.packageName,
19637                        preferred.activityInfo.name);
19638    }
19639
19640    @Override
19641    public void setHomeActivity(ComponentName comp, int userId) {
19642        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19643        getHomeActivitiesAsUser(homeActivities, userId);
19644
19645        boolean found = false;
19646
19647        final int size = homeActivities.size();
19648        final ComponentName[] set = new ComponentName[size];
19649        for (int i = 0; i < size; i++) {
19650            final ResolveInfo candidate = homeActivities.get(i);
19651            final ActivityInfo info = candidate.activityInfo;
19652            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19653            set[i] = activityName;
19654            if (!found && activityName.equals(comp)) {
19655                found = true;
19656            }
19657        }
19658        if (!found) {
19659            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19660                    + userId);
19661        }
19662        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19663                set, comp, userId);
19664    }
19665
19666    private @Nullable String getSetupWizardPackageName() {
19667        final Intent intent = new Intent(Intent.ACTION_MAIN);
19668        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19669
19670        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19671                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19672                        | MATCH_DISABLED_COMPONENTS,
19673                UserHandle.myUserId());
19674        if (matches.size() == 1) {
19675            return matches.get(0).getComponentInfo().packageName;
19676        } else {
19677            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19678                    + ": matches=" + matches);
19679            return null;
19680        }
19681    }
19682
19683    private @Nullable String getStorageManagerPackageName() {
19684        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19685
19686        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19687                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19688                        | MATCH_DISABLED_COMPONENTS,
19689                UserHandle.myUserId());
19690        if (matches.size() == 1) {
19691            return matches.get(0).getComponentInfo().packageName;
19692        } else {
19693            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19694                    + matches.size() + ": matches=" + matches);
19695            return null;
19696        }
19697    }
19698
19699    @Override
19700    public void setApplicationEnabledSetting(String appPackageName,
19701            int newState, int flags, int userId, String callingPackage) {
19702        if (!sUserManager.exists(userId)) return;
19703        if (callingPackage == null) {
19704            callingPackage = Integer.toString(Binder.getCallingUid());
19705        }
19706        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19707    }
19708
19709    @Override
19710    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
19711        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
19712        synchronized (mPackages) {
19713            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
19714            if (pkgSetting != null) {
19715                pkgSetting.setUpdateAvailable(updateAvailable);
19716            }
19717        }
19718    }
19719
19720    @Override
19721    public void setComponentEnabledSetting(ComponentName componentName,
19722            int newState, int flags, int userId) {
19723        if (!sUserManager.exists(userId)) return;
19724        setEnabledSetting(componentName.getPackageName(),
19725                componentName.getClassName(), newState, flags, userId, null);
19726    }
19727
19728    private void setEnabledSetting(final String packageName, String className, int newState,
19729            final int flags, int userId, String callingPackage) {
19730        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19731              || newState == COMPONENT_ENABLED_STATE_ENABLED
19732              || newState == COMPONENT_ENABLED_STATE_DISABLED
19733              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19734              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19735            throw new IllegalArgumentException("Invalid new component state: "
19736                    + newState);
19737        }
19738        PackageSetting pkgSetting;
19739        final int uid = Binder.getCallingUid();
19740        final int permission;
19741        if (uid == Process.SYSTEM_UID) {
19742            permission = PackageManager.PERMISSION_GRANTED;
19743        } else {
19744            permission = mContext.checkCallingOrSelfPermission(
19745                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19746        }
19747        enforceCrossUserPermission(uid, userId,
19748                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19749        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19750        boolean sendNow = false;
19751        boolean isApp = (className == null);
19752        String componentName = isApp ? packageName : className;
19753        int packageUid = -1;
19754        ArrayList<String> components;
19755
19756        // writer
19757        synchronized (mPackages) {
19758            pkgSetting = mSettings.mPackages.get(packageName);
19759            if (pkgSetting == null) {
19760                if (className == null) {
19761                    throw new IllegalArgumentException("Unknown package: " + packageName);
19762                }
19763                throw new IllegalArgumentException(
19764                        "Unknown component: " + packageName + "/" + className);
19765            }
19766        }
19767
19768        // Limit who can change which apps
19769        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
19770            // Don't allow apps that don't have permission to modify other apps
19771            if (!allowedByPermission) {
19772                throw new SecurityException(
19773                        "Permission Denial: attempt to change component state from pid="
19774                        + Binder.getCallingPid()
19775                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
19776            }
19777            // Don't allow changing protected packages.
19778            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19779                throw new SecurityException("Cannot disable a protected package: " + packageName);
19780            }
19781        }
19782
19783        synchronized (mPackages) {
19784            if (uid == Process.SHELL_UID
19785                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19786                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19787                // unless it is a test package.
19788                int oldState = pkgSetting.getEnabled(userId);
19789                if (className == null
19790                    &&
19791                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19792                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19793                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19794                    &&
19795                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19796                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
19797                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19798                    // ok
19799                } else {
19800                    throw new SecurityException(
19801                            "Shell cannot change component state for " + packageName + "/"
19802                            + className + " to " + newState);
19803                }
19804            }
19805            if (className == null) {
19806                // We're dealing with an application/package level state change
19807                if (pkgSetting.getEnabled(userId) == newState) {
19808                    // Nothing to do
19809                    return;
19810                }
19811                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19812                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
19813                    // Don't care about who enables an app.
19814                    callingPackage = null;
19815                }
19816                pkgSetting.setEnabled(newState, userId, callingPackage);
19817                // pkgSetting.pkg.mSetEnabled = newState;
19818            } else {
19819                // We're dealing with a component level state change
19820                // First, verify that this is a valid class name.
19821                PackageParser.Package pkg = pkgSetting.pkg;
19822                if (pkg == null || !pkg.hasComponentClassName(className)) {
19823                    if (pkg != null &&
19824                            pkg.applicationInfo.targetSdkVersion >=
19825                                    Build.VERSION_CODES.JELLY_BEAN) {
19826                        throw new IllegalArgumentException("Component class " + className
19827                                + " does not exist in " + packageName);
19828                    } else {
19829                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
19830                                + className + " does not exist in " + packageName);
19831                    }
19832                }
19833                switch (newState) {
19834                case COMPONENT_ENABLED_STATE_ENABLED:
19835                    if (!pkgSetting.enableComponentLPw(className, userId)) {
19836                        return;
19837                    }
19838                    break;
19839                case COMPONENT_ENABLED_STATE_DISABLED:
19840                    if (!pkgSetting.disableComponentLPw(className, userId)) {
19841                        return;
19842                    }
19843                    break;
19844                case COMPONENT_ENABLED_STATE_DEFAULT:
19845                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
19846                        return;
19847                    }
19848                    break;
19849                default:
19850                    Slog.e(TAG, "Invalid new component state: " + newState);
19851                    return;
19852                }
19853            }
19854            scheduleWritePackageRestrictionsLocked(userId);
19855            updateSequenceNumberLP(packageName, new int[] { userId });
19856            final long callingId = Binder.clearCallingIdentity();
19857            try {
19858                updateInstantAppInstallerLocked();
19859            } finally {
19860                Binder.restoreCallingIdentity(callingId);
19861            }
19862            components = mPendingBroadcasts.get(userId, packageName);
19863            final boolean newPackage = components == null;
19864            if (newPackage) {
19865                components = new ArrayList<String>();
19866            }
19867            if (!components.contains(componentName)) {
19868                components.add(componentName);
19869            }
19870            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
19871                sendNow = true;
19872                // Purge entry from pending broadcast list if another one exists already
19873                // since we are sending one right away.
19874                mPendingBroadcasts.remove(userId, packageName);
19875            } else {
19876                if (newPackage) {
19877                    mPendingBroadcasts.put(userId, packageName, components);
19878                }
19879                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
19880                    // Schedule a message
19881                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
19882                }
19883            }
19884        }
19885
19886        long callingId = Binder.clearCallingIdentity();
19887        try {
19888            if (sendNow) {
19889                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
19890                sendPackageChangedBroadcast(packageName,
19891                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
19892            }
19893        } finally {
19894            Binder.restoreCallingIdentity(callingId);
19895        }
19896    }
19897
19898    @Override
19899    public void flushPackageRestrictionsAsUser(int userId) {
19900        if (!sUserManager.exists(userId)) {
19901            return;
19902        }
19903        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
19904                false /* checkShell */, "flushPackageRestrictions");
19905        synchronized (mPackages) {
19906            mSettings.writePackageRestrictionsLPr(userId);
19907            mDirtyUsers.remove(userId);
19908            if (mDirtyUsers.isEmpty()) {
19909                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
19910            }
19911        }
19912    }
19913
19914    private void sendPackageChangedBroadcast(String packageName,
19915            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
19916        if (DEBUG_INSTALL)
19917            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
19918                    + componentNames);
19919        Bundle extras = new Bundle(4);
19920        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
19921        String nameList[] = new String[componentNames.size()];
19922        componentNames.toArray(nameList);
19923        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
19924        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
19925        extras.putInt(Intent.EXTRA_UID, packageUid);
19926        // If this is not reporting a change of the overall package, then only send it
19927        // to registered receivers.  We don't want to launch a swath of apps for every
19928        // little component state change.
19929        final int flags = !componentNames.contains(packageName)
19930                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
19931        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
19932                new int[] {UserHandle.getUserId(packageUid)});
19933    }
19934
19935    @Override
19936    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
19937        if (!sUserManager.exists(userId)) return;
19938        final int uid = Binder.getCallingUid();
19939        final int permission = mContext.checkCallingOrSelfPermission(
19940                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19941        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19942        enforceCrossUserPermission(uid, userId,
19943                true /* requireFullPermission */, true /* checkShell */, "stop package");
19944        // writer
19945        synchronized (mPackages) {
19946            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
19947                    allowedByPermission, uid, userId)) {
19948                scheduleWritePackageRestrictionsLocked(userId);
19949            }
19950        }
19951    }
19952
19953    @Override
19954    public String getInstallerPackageName(String packageName) {
19955        // reader
19956        synchronized (mPackages) {
19957            return mSettings.getInstallerPackageNameLPr(packageName);
19958        }
19959    }
19960
19961    public boolean isOrphaned(String packageName) {
19962        // reader
19963        synchronized (mPackages) {
19964            return mSettings.isOrphaned(packageName);
19965        }
19966    }
19967
19968    @Override
19969    public int getApplicationEnabledSetting(String packageName, int userId) {
19970        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19971        int uid = Binder.getCallingUid();
19972        enforceCrossUserPermission(uid, userId,
19973                false /* requireFullPermission */, false /* checkShell */, "get enabled");
19974        // reader
19975        synchronized (mPackages) {
19976            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
19977        }
19978    }
19979
19980    @Override
19981    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
19982        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19983        int uid = Binder.getCallingUid();
19984        enforceCrossUserPermission(uid, userId,
19985                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
19986        // reader
19987        synchronized (mPackages) {
19988            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
19989        }
19990    }
19991
19992    @Override
19993    public void enterSafeMode() {
19994        enforceSystemOrRoot("Only the system can request entering safe mode");
19995
19996        if (!mSystemReady) {
19997            mSafeMode = true;
19998        }
19999    }
20000
20001    @Override
20002    public void systemReady() {
20003        mSystemReady = true;
20004
20005        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20006        // disabled after already being started.
20007        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20008                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20009
20010        // Read the compatibilty setting when the system is ready.
20011        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20012                mContext.getContentResolver(),
20013                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20014        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20015        if (DEBUG_SETTINGS) {
20016            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20017        }
20018
20019        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20020
20021        synchronized (mPackages) {
20022            // Verify that all of the preferred activity components actually
20023            // exist.  It is possible for applications to be updated and at
20024            // that point remove a previously declared activity component that
20025            // had been set as a preferred activity.  We try to clean this up
20026            // the next time we encounter that preferred activity, but it is
20027            // possible for the user flow to never be able to return to that
20028            // situation so here we do a sanity check to make sure we haven't
20029            // left any junk around.
20030            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20031            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20032                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20033                removed.clear();
20034                for (PreferredActivity pa : pir.filterSet()) {
20035                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20036                        removed.add(pa);
20037                    }
20038                }
20039                if (removed.size() > 0) {
20040                    for (int r=0; r<removed.size(); r++) {
20041                        PreferredActivity pa = removed.get(r);
20042                        Slog.w(TAG, "Removing dangling preferred activity: "
20043                                + pa.mPref.mComponent);
20044                        pir.removeFilter(pa);
20045                    }
20046                    mSettings.writePackageRestrictionsLPr(
20047                            mSettings.mPreferredActivities.keyAt(i));
20048                }
20049            }
20050
20051            for (int userId : UserManagerService.getInstance().getUserIds()) {
20052                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20053                    grantPermissionsUserIds = ArrayUtils.appendInt(
20054                            grantPermissionsUserIds, userId);
20055                }
20056            }
20057        }
20058        sUserManager.systemReady();
20059
20060        // If we upgraded grant all default permissions before kicking off.
20061        for (int userId : grantPermissionsUserIds) {
20062            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20063        }
20064
20065        // If we did not grant default permissions, we preload from this the
20066        // default permission exceptions lazily to ensure we don't hit the
20067        // disk on a new user creation.
20068        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20069            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20070        }
20071
20072        // Kick off any messages waiting for system ready
20073        if (mPostSystemReadyMessages != null) {
20074            for (Message msg : mPostSystemReadyMessages) {
20075                msg.sendToTarget();
20076            }
20077            mPostSystemReadyMessages = null;
20078        }
20079
20080        // Watch for external volumes that come and go over time
20081        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20082        storage.registerListener(mStorageListener);
20083
20084        mInstallerService.systemReady();
20085        mPackageDexOptimizer.systemReady();
20086
20087        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20088                StorageManagerInternal.class);
20089        StorageManagerInternal.addExternalStoragePolicy(
20090                new StorageManagerInternal.ExternalStorageMountPolicy() {
20091            @Override
20092            public int getMountMode(int uid, String packageName) {
20093                if (Process.isIsolated(uid)) {
20094                    return Zygote.MOUNT_EXTERNAL_NONE;
20095                }
20096                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
20097                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20098                }
20099                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20100                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20101                }
20102                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20103                    return Zygote.MOUNT_EXTERNAL_READ;
20104                }
20105                return Zygote.MOUNT_EXTERNAL_WRITE;
20106            }
20107
20108            @Override
20109            public boolean hasExternalStorage(int uid, String packageName) {
20110                return true;
20111            }
20112        });
20113
20114        // Now that we're mostly running, clean up stale users and apps
20115        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20116        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
20117
20118        if (mPrivappPermissionsViolations != null) {
20119            Slog.wtf(TAG,"Signature|privileged permissions not in "
20120                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
20121            mPrivappPermissionsViolations = null;
20122        }
20123    }
20124
20125    public void waitForAppDataPrepared() {
20126        if (mPrepareAppDataFuture == null) {
20127            return;
20128        }
20129        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
20130        mPrepareAppDataFuture = null;
20131    }
20132
20133    @Override
20134    public boolean isSafeMode() {
20135        return mSafeMode;
20136    }
20137
20138    @Override
20139    public boolean hasSystemUidErrors() {
20140        return mHasSystemUidErrors;
20141    }
20142
20143    static String arrayToString(int[] array) {
20144        StringBuffer buf = new StringBuffer(128);
20145        buf.append('[');
20146        if (array != null) {
20147            for (int i=0; i<array.length; i++) {
20148                if (i > 0) buf.append(", ");
20149                buf.append(array[i]);
20150            }
20151        }
20152        buf.append(']');
20153        return buf.toString();
20154    }
20155
20156    static class DumpState {
20157        public static final int DUMP_LIBS = 1 << 0;
20158        public static final int DUMP_FEATURES = 1 << 1;
20159        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20160        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20161        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20162        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20163        public static final int DUMP_PERMISSIONS = 1 << 6;
20164        public static final int DUMP_PACKAGES = 1 << 7;
20165        public static final int DUMP_SHARED_USERS = 1 << 8;
20166        public static final int DUMP_MESSAGES = 1 << 9;
20167        public static final int DUMP_PROVIDERS = 1 << 10;
20168        public static final int DUMP_VERIFIERS = 1 << 11;
20169        public static final int DUMP_PREFERRED = 1 << 12;
20170        public static final int DUMP_PREFERRED_XML = 1 << 13;
20171        public static final int DUMP_KEYSETS = 1 << 14;
20172        public static final int DUMP_VERSION = 1 << 15;
20173        public static final int DUMP_INSTALLS = 1 << 16;
20174        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20175        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20176        public static final int DUMP_FROZEN = 1 << 19;
20177        public static final int DUMP_DEXOPT = 1 << 20;
20178        public static final int DUMP_COMPILER_STATS = 1 << 21;
20179        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
20180
20181        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20182
20183        private int mTypes;
20184
20185        private int mOptions;
20186
20187        private boolean mTitlePrinted;
20188
20189        private SharedUserSetting mSharedUser;
20190
20191        public boolean isDumping(int type) {
20192            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20193                return true;
20194            }
20195
20196            return (mTypes & type) != 0;
20197        }
20198
20199        public void setDump(int type) {
20200            mTypes |= type;
20201        }
20202
20203        public boolean isOptionEnabled(int option) {
20204            return (mOptions & option) != 0;
20205        }
20206
20207        public void setOptionEnabled(int option) {
20208            mOptions |= option;
20209        }
20210
20211        public boolean onTitlePrinted() {
20212            final boolean printed = mTitlePrinted;
20213            mTitlePrinted = true;
20214            return printed;
20215        }
20216
20217        public boolean getTitlePrinted() {
20218            return mTitlePrinted;
20219        }
20220
20221        public void setTitlePrinted(boolean enabled) {
20222            mTitlePrinted = enabled;
20223        }
20224
20225        public SharedUserSetting getSharedUser() {
20226            return mSharedUser;
20227        }
20228
20229        public void setSharedUser(SharedUserSetting user) {
20230            mSharedUser = user;
20231        }
20232    }
20233
20234    @Override
20235    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20236            FileDescriptor err, String[] args, ShellCallback callback,
20237            ResultReceiver resultReceiver) {
20238        (new PackageManagerShellCommand(this)).exec(
20239                this, in, out, err, args, callback, resultReceiver);
20240    }
20241
20242    @Override
20243    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20244        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
20245
20246        DumpState dumpState = new DumpState();
20247        boolean fullPreferred = false;
20248        boolean checkin = false;
20249
20250        String packageName = null;
20251        ArraySet<String> permissionNames = null;
20252
20253        int opti = 0;
20254        while (opti < args.length) {
20255            String opt = args[opti];
20256            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20257                break;
20258            }
20259            opti++;
20260
20261            if ("-a".equals(opt)) {
20262                // Right now we only know how to print all.
20263            } else if ("-h".equals(opt)) {
20264                pw.println("Package manager dump options:");
20265                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20266                pw.println("    --checkin: dump for a checkin");
20267                pw.println("    -f: print details of intent filters");
20268                pw.println("    -h: print this help");
20269                pw.println("  cmd may be one of:");
20270                pw.println("    l[ibraries]: list known shared libraries");
20271                pw.println("    f[eatures]: list device features");
20272                pw.println("    k[eysets]: print known keysets");
20273                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20274                pw.println("    perm[issions]: dump permissions");
20275                pw.println("    permission [name ...]: dump declaration and use of given permission");
20276                pw.println("    pref[erred]: print preferred package settings");
20277                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20278                pw.println("    prov[iders]: dump content providers");
20279                pw.println("    p[ackages]: dump installed packages");
20280                pw.println("    s[hared-users]: dump shared user IDs");
20281                pw.println("    m[essages]: print collected runtime messages");
20282                pw.println("    v[erifiers]: print package verifier info");
20283                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20284                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20285                pw.println("    version: print database version info");
20286                pw.println("    write: write current settings now");
20287                pw.println("    installs: details about install sessions");
20288                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20289                pw.println("    dexopt: dump dexopt state");
20290                pw.println("    compiler-stats: dump compiler statistics");
20291                pw.println("    enabled-overlays: dump list of enabled overlay packages");
20292                pw.println("    <package.name>: info about given package");
20293                return;
20294            } else if ("--checkin".equals(opt)) {
20295                checkin = true;
20296            } else if ("-f".equals(opt)) {
20297                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20298            } else if ("--proto".equals(opt)) {
20299                dumpProto(fd);
20300                return;
20301            } else {
20302                pw.println("Unknown argument: " + opt + "; use -h for help");
20303            }
20304        }
20305
20306        // Is the caller requesting to dump a particular piece of data?
20307        if (opti < args.length) {
20308            String cmd = args[opti];
20309            opti++;
20310            // Is this a package name?
20311            if ("android".equals(cmd) || cmd.contains(".")) {
20312                packageName = cmd;
20313                // When dumping a single package, we always dump all of its
20314                // filter information since the amount of data will be reasonable.
20315                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20316            } else if ("check-permission".equals(cmd)) {
20317                if (opti >= args.length) {
20318                    pw.println("Error: check-permission missing permission argument");
20319                    return;
20320                }
20321                String perm = args[opti];
20322                opti++;
20323                if (opti >= args.length) {
20324                    pw.println("Error: check-permission missing package argument");
20325                    return;
20326                }
20327
20328                String pkg = args[opti];
20329                opti++;
20330                int user = UserHandle.getUserId(Binder.getCallingUid());
20331                if (opti < args.length) {
20332                    try {
20333                        user = Integer.parseInt(args[opti]);
20334                    } catch (NumberFormatException e) {
20335                        pw.println("Error: check-permission user argument is not a number: "
20336                                + args[opti]);
20337                        return;
20338                    }
20339                }
20340
20341                // Normalize package name to handle renamed packages and static libs
20342                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20343
20344                pw.println(checkPermission(perm, pkg, user));
20345                return;
20346            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20347                dumpState.setDump(DumpState.DUMP_LIBS);
20348            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20349                dumpState.setDump(DumpState.DUMP_FEATURES);
20350            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20351                if (opti >= args.length) {
20352                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20353                            | DumpState.DUMP_SERVICE_RESOLVERS
20354                            | DumpState.DUMP_RECEIVER_RESOLVERS
20355                            | DumpState.DUMP_CONTENT_RESOLVERS);
20356                } else {
20357                    while (opti < args.length) {
20358                        String name = args[opti];
20359                        if ("a".equals(name) || "activity".equals(name)) {
20360                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20361                        } else if ("s".equals(name) || "service".equals(name)) {
20362                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20363                        } else if ("r".equals(name) || "receiver".equals(name)) {
20364                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20365                        } else if ("c".equals(name) || "content".equals(name)) {
20366                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20367                        } else {
20368                            pw.println("Error: unknown resolver table type: " + name);
20369                            return;
20370                        }
20371                        opti++;
20372                    }
20373                }
20374            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20375                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20376            } else if ("permission".equals(cmd)) {
20377                if (opti >= args.length) {
20378                    pw.println("Error: permission requires permission name");
20379                    return;
20380                }
20381                permissionNames = new ArraySet<>();
20382                while (opti < args.length) {
20383                    permissionNames.add(args[opti]);
20384                    opti++;
20385                }
20386                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20387                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20388            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20389                dumpState.setDump(DumpState.DUMP_PREFERRED);
20390            } else if ("preferred-xml".equals(cmd)) {
20391                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20392                if (opti < args.length && "--full".equals(args[opti])) {
20393                    fullPreferred = true;
20394                    opti++;
20395                }
20396            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20397                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20398            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20399                dumpState.setDump(DumpState.DUMP_PACKAGES);
20400            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20401                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20402            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20403                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20404            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20405                dumpState.setDump(DumpState.DUMP_MESSAGES);
20406            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20407                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20408            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20409                    || "intent-filter-verifiers".equals(cmd)) {
20410                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20411            } else if ("version".equals(cmd)) {
20412                dumpState.setDump(DumpState.DUMP_VERSION);
20413            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20414                dumpState.setDump(DumpState.DUMP_KEYSETS);
20415            } else if ("installs".equals(cmd)) {
20416                dumpState.setDump(DumpState.DUMP_INSTALLS);
20417            } else if ("frozen".equals(cmd)) {
20418                dumpState.setDump(DumpState.DUMP_FROZEN);
20419            } else if ("dexopt".equals(cmd)) {
20420                dumpState.setDump(DumpState.DUMP_DEXOPT);
20421            } else if ("compiler-stats".equals(cmd)) {
20422                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20423            } else if ("enabled-overlays".equals(cmd)) {
20424                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
20425            } else if ("write".equals(cmd)) {
20426                synchronized (mPackages) {
20427                    mSettings.writeLPr();
20428                    pw.println("Settings written.");
20429                    return;
20430                }
20431            }
20432        }
20433
20434        if (checkin) {
20435            pw.println("vers,1");
20436        }
20437
20438        // reader
20439        synchronized (mPackages) {
20440            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20441                if (!checkin) {
20442                    if (dumpState.onTitlePrinted())
20443                        pw.println();
20444                    pw.println("Database versions:");
20445                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20446                }
20447            }
20448
20449            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20450                if (!checkin) {
20451                    if (dumpState.onTitlePrinted())
20452                        pw.println();
20453                    pw.println("Verifiers:");
20454                    pw.print("  Required: ");
20455                    pw.print(mRequiredVerifierPackage);
20456                    pw.print(" (uid=");
20457                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20458                            UserHandle.USER_SYSTEM));
20459                    pw.println(")");
20460                } else if (mRequiredVerifierPackage != null) {
20461                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20462                    pw.print(",");
20463                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20464                            UserHandle.USER_SYSTEM));
20465                }
20466            }
20467
20468            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20469                    packageName == null) {
20470                if (mIntentFilterVerifierComponent != null) {
20471                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20472                    if (!checkin) {
20473                        if (dumpState.onTitlePrinted())
20474                            pw.println();
20475                        pw.println("Intent Filter Verifier:");
20476                        pw.print("  Using: ");
20477                        pw.print(verifierPackageName);
20478                        pw.print(" (uid=");
20479                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20480                                UserHandle.USER_SYSTEM));
20481                        pw.println(")");
20482                    } else if (verifierPackageName != null) {
20483                        pw.print("ifv,"); pw.print(verifierPackageName);
20484                        pw.print(",");
20485                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20486                                UserHandle.USER_SYSTEM));
20487                    }
20488                } else {
20489                    pw.println();
20490                    pw.println("No Intent Filter Verifier available!");
20491                }
20492            }
20493
20494            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20495                boolean printedHeader = false;
20496                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20497                while (it.hasNext()) {
20498                    String libName = it.next();
20499                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20500                    if (versionedLib == null) {
20501                        continue;
20502                    }
20503                    final int versionCount = versionedLib.size();
20504                    for (int i = 0; i < versionCount; i++) {
20505                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20506                        if (!checkin) {
20507                            if (!printedHeader) {
20508                                if (dumpState.onTitlePrinted())
20509                                    pw.println();
20510                                pw.println("Libraries:");
20511                                printedHeader = true;
20512                            }
20513                            pw.print("  ");
20514                        } else {
20515                            pw.print("lib,");
20516                        }
20517                        pw.print(libEntry.info.getName());
20518                        if (libEntry.info.isStatic()) {
20519                            pw.print(" version=" + libEntry.info.getVersion());
20520                        }
20521                        if (!checkin) {
20522                            pw.print(" -> ");
20523                        }
20524                        if (libEntry.path != null) {
20525                            pw.print(" (jar) ");
20526                            pw.print(libEntry.path);
20527                        } else {
20528                            pw.print(" (apk) ");
20529                            pw.print(libEntry.apk);
20530                        }
20531                        pw.println();
20532                    }
20533                }
20534            }
20535
20536            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20537                if (dumpState.onTitlePrinted())
20538                    pw.println();
20539                if (!checkin) {
20540                    pw.println("Features:");
20541                }
20542
20543                synchronized (mAvailableFeatures) {
20544                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20545                        if (checkin) {
20546                            pw.print("feat,");
20547                            pw.print(feat.name);
20548                            pw.print(",");
20549                            pw.println(feat.version);
20550                        } else {
20551                            pw.print("  ");
20552                            pw.print(feat.name);
20553                            if (feat.version > 0) {
20554                                pw.print(" version=");
20555                                pw.print(feat.version);
20556                            }
20557                            pw.println();
20558                        }
20559                    }
20560                }
20561            }
20562
20563            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20564                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20565                        : "Activity Resolver Table:", "  ", packageName,
20566                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20567                    dumpState.setTitlePrinted(true);
20568                }
20569            }
20570            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20571                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20572                        : "Receiver Resolver Table:", "  ", packageName,
20573                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20574                    dumpState.setTitlePrinted(true);
20575                }
20576            }
20577            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20578                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20579                        : "Service Resolver Table:", "  ", packageName,
20580                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20581                    dumpState.setTitlePrinted(true);
20582                }
20583            }
20584            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20585                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20586                        : "Provider Resolver Table:", "  ", packageName,
20587                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20588                    dumpState.setTitlePrinted(true);
20589                }
20590            }
20591
20592            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20593                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20594                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20595                    int user = mSettings.mPreferredActivities.keyAt(i);
20596                    if (pir.dump(pw,
20597                            dumpState.getTitlePrinted()
20598                                ? "\nPreferred Activities User " + user + ":"
20599                                : "Preferred Activities User " + user + ":", "  ",
20600                            packageName, true, false)) {
20601                        dumpState.setTitlePrinted(true);
20602                    }
20603                }
20604            }
20605
20606            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20607                pw.flush();
20608                FileOutputStream fout = new FileOutputStream(fd);
20609                BufferedOutputStream str = new BufferedOutputStream(fout);
20610                XmlSerializer serializer = new FastXmlSerializer();
20611                try {
20612                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20613                    serializer.startDocument(null, true);
20614                    serializer.setFeature(
20615                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20616                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20617                    serializer.endDocument();
20618                    serializer.flush();
20619                } catch (IllegalArgumentException e) {
20620                    pw.println("Failed writing: " + e);
20621                } catch (IllegalStateException e) {
20622                    pw.println("Failed writing: " + e);
20623                } catch (IOException e) {
20624                    pw.println("Failed writing: " + e);
20625                }
20626            }
20627
20628            if (!checkin
20629                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20630                    && packageName == null) {
20631                pw.println();
20632                int count = mSettings.mPackages.size();
20633                if (count == 0) {
20634                    pw.println("No applications!");
20635                    pw.println();
20636                } else {
20637                    final String prefix = "  ";
20638                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20639                    if (allPackageSettings.size() == 0) {
20640                        pw.println("No domain preferred apps!");
20641                        pw.println();
20642                    } else {
20643                        pw.println("App verification status:");
20644                        pw.println();
20645                        count = 0;
20646                        for (PackageSetting ps : allPackageSettings) {
20647                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20648                            if (ivi == null || ivi.getPackageName() == null) continue;
20649                            pw.println(prefix + "Package: " + ivi.getPackageName());
20650                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20651                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20652                            pw.println();
20653                            count++;
20654                        }
20655                        if (count == 0) {
20656                            pw.println(prefix + "No app verification established.");
20657                            pw.println();
20658                        }
20659                        for (int userId : sUserManager.getUserIds()) {
20660                            pw.println("App linkages for user " + userId + ":");
20661                            pw.println();
20662                            count = 0;
20663                            for (PackageSetting ps : allPackageSettings) {
20664                                final long status = ps.getDomainVerificationStatusForUser(userId);
20665                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20666                                        && !DEBUG_DOMAIN_VERIFICATION) {
20667                                    continue;
20668                                }
20669                                pw.println(prefix + "Package: " + ps.name);
20670                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20671                                String statusStr = IntentFilterVerificationInfo.
20672                                        getStatusStringFromValue(status);
20673                                pw.println(prefix + "Status:  " + statusStr);
20674                                pw.println();
20675                                count++;
20676                            }
20677                            if (count == 0) {
20678                                pw.println(prefix + "No configured app linkages.");
20679                                pw.println();
20680                            }
20681                        }
20682                    }
20683                }
20684            }
20685
20686            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20687                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20688                if (packageName == null && permissionNames == null) {
20689                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
20690                        if (iperm == 0) {
20691                            if (dumpState.onTitlePrinted())
20692                                pw.println();
20693                            pw.println("AppOp Permissions:");
20694                        }
20695                        pw.print("  AppOp Permission ");
20696                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
20697                        pw.println(":");
20698                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
20699                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
20700                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
20701                        }
20702                    }
20703                }
20704            }
20705
20706            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20707                boolean printedSomething = false;
20708                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20709                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20710                        continue;
20711                    }
20712                    if (!printedSomething) {
20713                        if (dumpState.onTitlePrinted())
20714                            pw.println();
20715                        pw.println("Registered ContentProviders:");
20716                        printedSomething = true;
20717                    }
20718                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20719                    pw.print("    "); pw.println(p.toString());
20720                }
20721                printedSomething = false;
20722                for (Map.Entry<String, PackageParser.Provider> entry :
20723                        mProvidersByAuthority.entrySet()) {
20724                    PackageParser.Provider p = entry.getValue();
20725                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20726                        continue;
20727                    }
20728                    if (!printedSomething) {
20729                        if (dumpState.onTitlePrinted())
20730                            pw.println();
20731                        pw.println("ContentProvider Authorities:");
20732                        printedSomething = true;
20733                    }
20734                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20735                    pw.print("    "); pw.println(p.toString());
20736                    if (p.info != null && p.info.applicationInfo != null) {
20737                        final String appInfo = p.info.applicationInfo.toString();
20738                        pw.print("      applicationInfo="); pw.println(appInfo);
20739                    }
20740                }
20741            }
20742
20743            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20744                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20745            }
20746
20747            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20748                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20749            }
20750
20751            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20752                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20753            }
20754
20755            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20756                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20757            }
20758
20759            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
20760                // XXX should handle packageName != null by dumping only install data that
20761                // the given package is involved with.
20762                if (dumpState.onTitlePrinted()) pw.println();
20763                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
20764            }
20765
20766            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20767                // XXX should handle packageName != null by dumping only install data that
20768                // the given package is involved with.
20769                if (dumpState.onTitlePrinted()) pw.println();
20770
20771                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20772                ipw.println();
20773                ipw.println("Frozen packages:");
20774                ipw.increaseIndent();
20775                if (mFrozenPackages.size() == 0) {
20776                    ipw.println("(none)");
20777                } else {
20778                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20779                        ipw.println(mFrozenPackages.valueAt(i));
20780                    }
20781                }
20782                ipw.decreaseIndent();
20783            }
20784
20785            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20786                if (dumpState.onTitlePrinted()) pw.println();
20787                dumpDexoptStateLPr(pw, packageName);
20788            }
20789
20790            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20791                if (dumpState.onTitlePrinted()) pw.println();
20792                dumpCompilerStatsLPr(pw, packageName);
20793            }
20794
20795            if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) {
20796                if (dumpState.onTitlePrinted()) pw.println();
20797                dumpEnabledOverlaysLPr(pw);
20798            }
20799
20800            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20801                if (dumpState.onTitlePrinted()) pw.println();
20802                mSettings.dumpReadMessagesLPr(pw, dumpState);
20803
20804                pw.println();
20805                pw.println("Package warning messages:");
20806                BufferedReader in = null;
20807                String line = null;
20808                try {
20809                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20810                    while ((line = in.readLine()) != null) {
20811                        if (line.contains("ignored: updated version")) continue;
20812                        pw.println(line);
20813                    }
20814                } catch (IOException ignored) {
20815                } finally {
20816                    IoUtils.closeQuietly(in);
20817                }
20818            }
20819
20820            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
20821                BufferedReader in = null;
20822                String line = null;
20823                try {
20824                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20825                    while ((line = in.readLine()) != null) {
20826                        if (line.contains("ignored: updated version")) continue;
20827                        pw.print("msg,");
20828                        pw.println(line);
20829                    }
20830                } catch (IOException ignored) {
20831                } finally {
20832                    IoUtils.closeQuietly(in);
20833                }
20834            }
20835        }
20836    }
20837
20838    private void dumpProto(FileDescriptor fd) {
20839        final ProtoOutputStream proto = new ProtoOutputStream(fd);
20840
20841        synchronized (mPackages) {
20842            final long requiredVerifierPackageToken =
20843                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
20844            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
20845            proto.write(
20846                    PackageServiceDumpProto.PackageShortProto.UID,
20847                    getPackageUid(
20848                            mRequiredVerifierPackage,
20849                            MATCH_DEBUG_TRIAGED_MISSING,
20850                            UserHandle.USER_SYSTEM));
20851            proto.end(requiredVerifierPackageToken);
20852
20853            if (mIntentFilterVerifierComponent != null) {
20854                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20855                final long verifierPackageToken =
20856                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
20857                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
20858                proto.write(
20859                        PackageServiceDumpProto.PackageShortProto.UID,
20860                        getPackageUid(
20861                                verifierPackageName,
20862                                MATCH_DEBUG_TRIAGED_MISSING,
20863                                UserHandle.USER_SYSTEM));
20864                proto.end(verifierPackageToken);
20865            }
20866
20867            dumpSharedLibrariesProto(proto);
20868            dumpFeaturesProto(proto);
20869            mSettings.dumpPackagesProto(proto);
20870            mSettings.dumpSharedUsersProto(proto);
20871            dumpMessagesProto(proto);
20872        }
20873        proto.flush();
20874    }
20875
20876    private void dumpMessagesProto(ProtoOutputStream proto) {
20877        BufferedReader in = null;
20878        String line = null;
20879        try {
20880            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20881            while ((line = in.readLine()) != null) {
20882                if (line.contains("ignored: updated version")) continue;
20883                proto.write(PackageServiceDumpProto.MESSAGES, line);
20884            }
20885        } catch (IOException ignored) {
20886        } finally {
20887            IoUtils.closeQuietly(in);
20888        }
20889    }
20890
20891    private void dumpFeaturesProto(ProtoOutputStream proto) {
20892        synchronized (mAvailableFeatures) {
20893            final int count = mAvailableFeatures.size();
20894            for (int i = 0; i < count; i++) {
20895                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
20896                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
20897                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
20898                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
20899                proto.end(featureToken);
20900            }
20901        }
20902    }
20903
20904    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
20905        final int count = mSharedLibraries.size();
20906        for (int i = 0; i < count; i++) {
20907            final String libName = mSharedLibraries.keyAt(i);
20908            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20909            if (versionedLib == null) {
20910                continue;
20911            }
20912            final int versionCount = versionedLib.size();
20913            for (int j = 0; j < versionCount; j++) {
20914                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
20915                final long sharedLibraryToken =
20916                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
20917                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
20918                final boolean isJar = (libEntry.path != null);
20919                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
20920                if (isJar) {
20921                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
20922                } else {
20923                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
20924                }
20925                proto.end(sharedLibraryToken);
20926            }
20927        }
20928    }
20929
20930    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
20931        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20932        ipw.println();
20933        ipw.println("Dexopt state:");
20934        ipw.increaseIndent();
20935        Collection<PackageParser.Package> packages = null;
20936        if (packageName != null) {
20937            PackageParser.Package targetPackage = mPackages.get(packageName);
20938            if (targetPackage != null) {
20939                packages = Collections.singletonList(targetPackage);
20940            } else {
20941                ipw.println("Unable to find package: " + packageName);
20942                return;
20943            }
20944        } else {
20945            packages = mPackages.values();
20946        }
20947
20948        for (PackageParser.Package pkg : packages) {
20949            ipw.println("[" + pkg.packageName + "]");
20950            ipw.increaseIndent();
20951            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
20952            ipw.decreaseIndent();
20953        }
20954    }
20955
20956    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
20957        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20958        ipw.println();
20959        ipw.println("Compiler stats:");
20960        ipw.increaseIndent();
20961        Collection<PackageParser.Package> packages = null;
20962        if (packageName != null) {
20963            PackageParser.Package targetPackage = mPackages.get(packageName);
20964            if (targetPackage != null) {
20965                packages = Collections.singletonList(targetPackage);
20966            } else {
20967                ipw.println("Unable to find package: " + packageName);
20968                return;
20969            }
20970        } else {
20971            packages = mPackages.values();
20972        }
20973
20974        for (PackageParser.Package pkg : packages) {
20975            ipw.println("[" + pkg.packageName + "]");
20976            ipw.increaseIndent();
20977
20978            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
20979            if (stats == null) {
20980                ipw.println("(No recorded stats)");
20981            } else {
20982                stats.dump(ipw);
20983            }
20984            ipw.decreaseIndent();
20985        }
20986    }
20987
20988    private void dumpEnabledOverlaysLPr(PrintWriter pw) {
20989        pw.println("Enabled overlay paths:");
20990        final int N = mEnabledOverlayPaths.size();
20991        for (int i = 0; i < N; i++) {
20992            final int userId = mEnabledOverlayPaths.keyAt(i);
20993            pw.println(String.format("    User %d:", userId));
20994            final ArrayMap<String, ArrayList<String>> userSpecificOverlays =
20995                mEnabledOverlayPaths.valueAt(i);
20996            final int M = userSpecificOverlays.size();
20997            for (int j = 0; j < M; j++) {
20998                final String targetPackageName = userSpecificOverlays.keyAt(j);
20999                final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j);
21000                pw.println(String.format("        %s: %s", targetPackageName, overlayPackagePaths));
21001            }
21002        }
21003    }
21004
21005    private String dumpDomainString(String packageName) {
21006        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21007                .getList();
21008        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21009
21010        ArraySet<String> result = new ArraySet<>();
21011        if (iviList.size() > 0) {
21012            for (IntentFilterVerificationInfo ivi : iviList) {
21013                for (String host : ivi.getDomains()) {
21014                    result.add(host);
21015                }
21016            }
21017        }
21018        if (filters != null && filters.size() > 0) {
21019            for (IntentFilter filter : filters) {
21020                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21021                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21022                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21023                    result.addAll(filter.getHostsList());
21024                }
21025            }
21026        }
21027
21028        StringBuilder sb = new StringBuilder(result.size() * 16);
21029        for (String domain : result) {
21030            if (sb.length() > 0) sb.append(" ");
21031            sb.append(domain);
21032        }
21033        return sb.toString();
21034    }
21035
21036    // ------- apps on sdcard specific code -------
21037    static final boolean DEBUG_SD_INSTALL = false;
21038
21039    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21040
21041    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21042
21043    private boolean mMediaMounted = false;
21044
21045    static String getEncryptKey() {
21046        try {
21047            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21048                    SD_ENCRYPTION_KEYSTORE_NAME);
21049            if (sdEncKey == null) {
21050                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21051                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21052                if (sdEncKey == null) {
21053                    Slog.e(TAG, "Failed to create encryption keys");
21054                    return null;
21055                }
21056            }
21057            return sdEncKey;
21058        } catch (NoSuchAlgorithmException nsae) {
21059            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21060            return null;
21061        } catch (IOException ioe) {
21062            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21063            return null;
21064        }
21065    }
21066
21067    /*
21068     * Update media status on PackageManager.
21069     */
21070    @Override
21071    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
21072        int callingUid = Binder.getCallingUid();
21073        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
21074            throw new SecurityException("Media status can only be updated by the system");
21075        }
21076        // reader; this apparently protects mMediaMounted, but should probably
21077        // be a different lock in that case.
21078        synchronized (mPackages) {
21079            Log.i(TAG, "Updating external media status from "
21080                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
21081                    + (mediaStatus ? "mounted" : "unmounted"));
21082            if (DEBUG_SD_INSTALL)
21083                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
21084                        + ", mMediaMounted=" + mMediaMounted);
21085            if (mediaStatus == mMediaMounted) {
21086                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
21087                        : 0, -1);
21088                mHandler.sendMessage(msg);
21089                return;
21090            }
21091            mMediaMounted = mediaStatus;
21092        }
21093        // Queue up an async operation since the package installation may take a
21094        // little while.
21095        mHandler.post(new Runnable() {
21096            public void run() {
21097                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
21098            }
21099        });
21100    }
21101
21102    /**
21103     * Called by StorageManagerService when the initial ASECs to scan are available.
21104     * Should block until all the ASEC containers are finished being scanned.
21105     */
21106    public void scanAvailableAsecs() {
21107        updateExternalMediaStatusInner(true, false, false);
21108    }
21109
21110    /*
21111     * Collect information of applications on external media, map them against
21112     * existing containers and update information based on current mount status.
21113     * Please note that we always have to report status if reportStatus has been
21114     * set to true especially when unloading packages.
21115     */
21116    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
21117            boolean externalStorage) {
21118        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
21119        int[] uidArr = EmptyArray.INT;
21120
21121        final String[] list = PackageHelper.getSecureContainerList();
21122        if (ArrayUtils.isEmpty(list)) {
21123            Log.i(TAG, "No secure containers found");
21124        } else {
21125            // Process list of secure containers and categorize them
21126            // as active or stale based on their package internal state.
21127
21128            // reader
21129            synchronized (mPackages) {
21130                for (String cid : list) {
21131                    // Leave stages untouched for now; installer service owns them
21132                    if (PackageInstallerService.isStageName(cid)) continue;
21133
21134                    if (DEBUG_SD_INSTALL)
21135                        Log.i(TAG, "Processing container " + cid);
21136                    String pkgName = getAsecPackageName(cid);
21137                    if (pkgName == null) {
21138                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
21139                        continue;
21140                    }
21141                    if (DEBUG_SD_INSTALL)
21142                        Log.i(TAG, "Looking for pkg : " + pkgName);
21143
21144                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
21145                    if (ps == null) {
21146                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
21147                        continue;
21148                    }
21149
21150                    /*
21151                     * Skip packages that are not external if we're unmounting
21152                     * external storage.
21153                     */
21154                    if (externalStorage && !isMounted && !isExternal(ps)) {
21155                        continue;
21156                    }
21157
21158                    final AsecInstallArgs args = new AsecInstallArgs(cid,
21159                            getAppDexInstructionSets(ps), ps.isForwardLocked());
21160                    // The package status is changed only if the code path
21161                    // matches between settings and the container id.
21162                    if (ps.codePathString != null
21163                            && ps.codePathString.startsWith(args.getCodePath())) {
21164                        if (DEBUG_SD_INSTALL) {
21165                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
21166                                    + " at code path: " + ps.codePathString);
21167                        }
21168
21169                        // We do have a valid package installed on sdcard
21170                        processCids.put(args, ps.codePathString);
21171                        final int uid = ps.appId;
21172                        if (uid != -1) {
21173                            uidArr = ArrayUtils.appendInt(uidArr, uid);
21174                        }
21175                    } else {
21176                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
21177                                + ps.codePathString);
21178                    }
21179                }
21180            }
21181
21182            Arrays.sort(uidArr);
21183        }
21184
21185        // Process packages with valid entries.
21186        if (isMounted) {
21187            if (DEBUG_SD_INSTALL)
21188                Log.i(TAG, "Loading packages");
21189            loadMediaPackages(processCids, uidArr, externalStorage);
21190            startCleaningPackages();
21191            mInstallerService.onSecureContainersAvailable();
21192        } else {
21193            if (DEBUG_SD_INSTALL)
21194                Log.i(TAG, "Unloading packages");
21195            unloadMediaPackages(processCids, uidArr, reportStatus);
21196        }
21197    }
21198
21199    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21200            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21201        final int size = infos.size();
21202        final String[] packageNames = new String[size];
21203        final int[] packageUids = new int[size];
21204        for (int i = 0; i < size; i++) {
21205            final ApplicationInfo info = infos.get(i);
21206            packageNames[i] = info.packageName;
21207            packageUids[i] = info.uid;
21208        }
21209        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21210                finishedReceiver);
21211    }
21212
21213    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21214            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21215        sendResourcesChangedBroadcast(mediaStatus, replacing,
21216                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21217    }
21218
21219    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21220            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21221        int size = pkgList.length;
21222        if (size > 0) {
21223            // Send broadcasts here
21224            Bundle extras = new Bundle();
21225            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21226            if (uidArr != null) {
21227                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21228            }
21229            if (replacing) {
21230                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21231            }
21232            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21233                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21234            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
21235        }
21236    }
21237
21238   /*
21239     * Look at potentially valid container ids from processCids If package
21240     * information doesn't match the one on record or package scanning fails,
21241     * the cid is added to list of removeCids. We currently don't delete stale
21242     * containers.
21243     */
21244    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
21245            boolean externalStorage) {
21246        ArrayList<String> pkgList = new ArrayList<String>();
21247        Set<AsecInstallArgs> keys = processCids.keySet();
21248
21249        for (AsecInstallArgs args : keys) {
21250            String codePath = processCids.get(args);
21251            if (DEBUG_SD_INSTALL)
21252                Log.i(TAG, "Loading container : " + args.cid);
21253            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
21254            try {
21255                // Make sure there are no container errors first.
21256                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
21257                    Slog.e(TAG, "Failed to mount cid : " + args.cid
21258                            + " when installing from sdcard");
21259                    continue;
21260                }
21261                // Check code path here.
21262                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
21263                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
21264                            + " does not match one in settings " + codePath);
21265                    continue;
21266                }
21267                // Parse package
21268                int parseFlags = mDefParseFlags;
21269                if (args.isExternalAsec()) {
21270                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
21271                }
21272                if (args.isFwdLocked()) {
21273                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21274                }
21275
21276                synchronized (mInstallLock) {
21277                    PackageParser.Package pkg = null;
21278                    try {
21279                        // Sadly we don't know the package name yet to freeze it
21280                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21281                                SCAN_IGNORE_FROZEN, 0, null);
21282                    } catch (PackageManagerException e) {
21283                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21284                    }
21285                    // Scan the package
21286                    if (pkg != null) {
21287                        /*
21288                         * TODO why is the lock being held? doPostInstall is
21289                         * called in other places without the lock. This needs
21290                         * to be straightened out.
21291                         */
21292                        // writer
21293                        synchronized (mPackages) {
21294                            retCode = PackageManager.INSTALL_SUCCEEDED;
21295                            pkgList.add(pkg.packageName);
21296                            // Post process args
21297                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21298                                    pkg.applicationInfo.uid);
21299                        }
21300                    } else {
21301                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21302                    }
21303                }
21304
21305            } finally {
21306                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21307                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21308                }
21309            }
21310        }
21311        // writer
21312        synchronized (mPackages) {
21313            // If the platform SDK has changed since the last time we booted,
21314            // we need to re-grant app permission to catch any new ones that
21315            // appear. This is really a hack, and means that apps can in some
21316            // cases get permissions that the user didn't initially explicitly
21317            // allow... it would be nice to have some better way to handle
21318            // this situation.
21319            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21320                    : mSettings.getInternalVersion();
21321            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21322                    : StorageManager.UUID_PRIVATE_INTERNAL;
21323
21324            int updateFlags = UPDATE_PERMISSIONS_ALL;
21325            if (ver.sdkVersion != mSdkVersion) {
21326                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21327                        + mSdkVersion + "; regranting permissions for external");
21328                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21329            }
21330            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21331
21332            // Yay, everything is now upgraded
21333            ver.forceCurrent();
21334
21335            // can downgrade to reader
21336            // Persist settings
21337            mSettings.writeLPr();
21338        }
21339        // Send a broadcast to let everyone know we are done processing
21340        if (pkgList.size() > 0) {
21341            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21342        }
21343    }
21344
21345   /*
21346     * Utility method to unload a list of specified containers
21347     */
21348    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21349        // Just unmount all valid containers.
21350        for (AsecInstallArgs arg : cidArgs) {
21351            synchronized (mInstallLock) {
21352                arg.doPostDeleteLI(false);
21353           }
21354       }
21355   }
21356
21357    /*
21358     * Unload packages mounted on external media. This involves deleting package
21359     * data from internal structures, sending broadcasts about disabled packages,
21360     * gc'ing to free up references, unmounting all secure containers
21361     * corresponding to packages on external media, and posting a
21362     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21363     * that we always have to post this message if status has been requested no
21364     * matter what.
21365     */
21366    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21367            final boolean reportStatus) {
21368        if (DEBUG_SD_INSTALL)
21369            Log.i(TAG, "unloading media packages");
21370        ArrayList<String> pkgList = new ArrayList<String>();
21371        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21372        final Set<AsecInstallArgs> keys = processCids.keySet();
21373        for (AsecInstallArgs args : keys) {
21374            String pkgName = args.getPackageName();
21375            if (DEBUG_SD_INSTALL)
21376                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21377            // Delete package internally
21378            PackageRemovedInfo outInfo = new PackageRemovedInfo();
21379            synchronized (mInstallLock) {
21380                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21381                final boolean res;
21382                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21383                        "unloadMediaPackages")) {
21384                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21385                            null);
21386                }
21387                if (res) {
21388                    pkgList.add(pkgName);
21389                } else {
21390                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21391                    failedList.add(args);
21392                }
21393            }
21394        }
21395
21396        // reader
21397        synchronized (mPackages) {
21398            // We didn't update the settings after removing each package;
21399            // write them now for all packages.
21400            mSettings.writeLPr();
21401        }
21402
21403        // We have to absolutely send UPDATED_MEDIA_STATUS only
21404        // after confirming that all the receivers processed the ordered
21405        // broadcast when packages get disabled, force a gc to clean things up.
21406        // and unload all the containers.
21407        if (pkgList.size() > 0) {
21408            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21409                    new IIntentReceiver.Stub() {
21410                public void performReceive(Intent intent, int resultCode, String data,
21411                        Bundle extras, boolean ordered, boolean sticky,
21412                        int sendingUser) throws RemoteException {
21413                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21414                            reportStatus ? 1 : 0, 1, keys);
21415                    mHandler.sendMessage(msg);
21416                }
21417            });
21418        } else {
21419            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
21420                    keys);
21421            mHandler.sendMessage(msg);
21422        }
21423    }
21424
21425    private void loadPrivatePackages(final VolumeInfo vol) {
21426        mHandler.post(new Runnable() {
21427            @Override
21428            public void run() {
21429                loadPrivatePackagesInner(vol);
21430            }
21431        });
21432    }
21433
21434    private void loadPrivatePackagesInner(VolumeInfo vol) {
21435        final String volumeUuid = vol.fsUuid;
21436        if (TextUtils.isEmpty(volumeUuid)) {
21437            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21438            return;
21439        }
21440
21441        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21442        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21443        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21444
21445        final VersionInfo ver;
21446        final List<PackageSetting> packages;
21447        synchronized (mPackages) {
21448            ver = mSettings.findOrCreateVersion(volumeUuid);
21449            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21450        }
21451
21452        for (PackageSetting ps : packages) {
21453            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21454            synchronized (mInstallLock) {
21455                final PackageParser.Package pkg;
21456                try {
21457                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21458                    loaded.add(pkg.applicationInfo);
21459
21460                } catch (PackageManagerException e) {
21461                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21462                }
21463
21464                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21465                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21466                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21467                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21468                }
21469            }
21470        }
21471
21472        // Reconcile app data for all started/unlocked users
21473        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21474        final UserManager um = mContext.getSystemService(UserManager.class);
21475        UserManagerInternal umInternal = getUserManagerInternal();
21476        for (UserInfo user : um.getUsers()) {
21477            final int flags;
21478            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21479                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21480            } else if (umInternal.isUserRunning(user.id)) {
21481                flags = StorageManager.FLAG_STORAGE_DE;
21482            } else {
21483                continue;
21484            }
21485
21486            try {
21487                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21488                synchronized (mInstallLock) {
21489                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21490                }
21491            } catch (IllegalStateException e) {
21492                // Device was probably ejected, and we'll process that event momentarily
21493                Slog.w(TAG, "Failed to prepare storage: " + e);
21494            }
21495        }
21496
21497        synchronized (mPackages) {
21498            int updateFlags = UPDATE_PERMISSIONS_ALL;
21499            if (ver.sdkVersion != mSdkVersion) {
21500                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21501                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21502                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21503            }
21504            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21505
21506            // Yay, everything is now upgraded
21507            ver.forceCurrent();
21508
21509            mSettings.writeLPr();
21510        }
21511
21512        for (PackageFreezer freezer : freezers) {
21513            freezer.close();
21514        }
21515
21516        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21517        sendResourcesChangedBroadcast(true, false, loaded, null);
21518    }
21519
21520    private void unloadPrivatePackages(final VolumeInfo vol) {
21521        mHandler.post(new Runnable() {
21522            @Override
21523            public void run() {
21524                unloadPrivatePackagesInner(vol);
21525            }
21526        });
21527    }
21528
21529    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21530        final String volumeUuid = vol.fsUuid;
21531        if (TextUtils.isEmpty(volumeUuid)) {
21532            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21533            return;
21534        }
21535
21536        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21537        synchronized (mInstallLock) {
21538        synchronized (mPackages) {
21539            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21540            for (PackageSetting ps : packages) {
21541                if (ps.pkg == null) continue;
21542
21543                final ApplicationInfo info = ps.pkg.applicationInfo;
21544                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21545                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
21546
21547                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21548                        "unloadPrivatePackagesInner")) {
21549                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21550                            false, null)) {
21551                        unloaded.add(info);
21552                    } else {
21553                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21554                    }
21555                }
21556
21557                // Try very hard to release any references to this package
21558                // so we don't risk the system server being killed due to
21559                // open FDs
21560                AttributeCache.instance().removePackage(ps.name);
21561            }
21562
21563            mSettings.writeLPr();
21564        }
21565        }
21566
21567        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21568        sendResourcesChangedBroadcast(false, false, unloaded, null);
21569
21570        // Try very hard to release any references to this path so we don't risk
21571        // the system server being killed due to open FDs
21572        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21573
21574        for (int i = 0; i < 3; i++) {
21575            System.gc();
21576            System.runFinalization();
21577        }
21578    }
21579
21580    private void assertPackageKnown(String volumeUuid, String packageName)
21581            throws PackageManagerException {
21582        synchronized (mPackages) {
21583            // Normalize package name to handle renamed packages
21584            packageName = normalizePackageNameLPr(packageName);
21585
21586            final PackageSetting ps = mSettings.mPackages.get(packageName);
21587            if (ps == null) {
21588                throw new PackageManagerException("Package " + packageName + " is unknown");
21589            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21590                throw new PackageManagerException(
21591                        "Package " + packageName + " found on unknown volume " + volumeUuid
21592                                + "; expected volume " + ps.volumeUuid);
21593            }
21594        }
21595    }
21596
21597    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21598            throws PackageManagerException {
21599        synchronized (mPackages) {
21600            // Normalize package name to handle renamed packages
21601            packageName = normalizePackageNameLPr(packageName);
21602
21603            final PackageSetting ps = mSettings.mPackages.get(packageName);
21604            if (ps == null) {
21605                throw new PackageManagerException("Package " + packageName + " is unknown");
21606            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21607                throw new PackageManagerException(
21608                        "Package " + packageName + " found on unknown volume " + volumeUuid
21609                                + "; expected volume " + ps.volumeUuid);
21610            } else if (!ps.getInstalled(userId)) {
21611                throw new PackageManagerException(
21612                        "Package " + packageName + " not installed for user " + userId);
21613            }
21614        }
21615    }
21616
21617    private List<String> collectAbsoluteCodePaths() {
21618        synchronized (mPackages) {
21619            List<String> codePaths = new ArrayList<>();
21620            final int packageCount = mSettings.mPackages.size();
21621            for (int i = 0; i < packageCount; i++) {
21622                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21623                codePaths.add(ps.codePath.getAbsolutePath());
21624            }
21625            return codePaths;
21626        }
21627    }
21628
21629    /**
21630     * Examine all apps present on given mounted volume, and destroy apps that
21631     * aren't expected, either due to uninstallation or reinstallation on
21632     * another volume.
21633     */
21634    private void reconcileApps(String volumeUuid) {
21635        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21636        List<File> filesToDelete = null;
21637
21638        final File[] files = FileUtils.listFilesOrEmpty(
21639                Environment.getDataAppDirectory(volumeUuid));
21640        for (File file : files) {
21641            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21642                    && !PackageInstallerService.isStageName(file.getName());
21643            if (!isPackage) {
21644                // Ignore entries which are not packages
21645                continue;
21646            }
21647
21648            String absolutePath = file.getAbsolutePath();
21649
21650            boolean pathValid = false;
21651            final int absoluteCodePathCount = absoluteCodePaths.size();
21652            for (int i = 0; i < absoluteCodePathCount; i++) {
21653                String absoluteCodePath = absoluteCodePaths.get(i);
21654                if (absolutePath.startsWith(absoluteCodePath)) {
21655                    pathValid = true;
21656                    break;
21657                }
21658            }
21659
21660            if (!pathValid) {
21661                if (filesToDelete == null) {
21662                    filesToDelete = new ArrayList<>();
21663                }
21664                filesToDelete.add(file);
21665            }
21666        }
21667
21668        if (filesToDelete != null) {
21669            final int fileToDeleteCount = filesToDelete.size();
21670            for (int i = 0; i < fileToDeleteCount; i++) {
21671                File fileToDelete = filesToDelete.get(i);
21672                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21673                synchronized (mInstallLock) {
21674                    removeCodePathLI(fileToDelete);
21675                }
21676            }
21677        }
21678    }
21679
21680    /**
21681     * Reconcile all app data for the given user.
21682     * <p>
21683     * Verifies that directories exist and that ownership and labeling is
21684     * correct for all installed apps on all mounted volumes.
21685     */
21686    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21687        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21688        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21689            final String volumeUuid = vol.getFsUuid();
21690            synchronized (mInstallLock) {
21691                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21692            }
21693        }
21694    }
21695
21696    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21697            boolean migrateAppData) {
21698        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
21699    }
21700
21701    /**
21702     * Reconcile all app data on given mounted volume.
21703     * <p>
21704     * Destroys app data that isn't expected, either due to uninstallation or
21705     * reinstallation on another volume.
21706     * <p>
21707     * Verifies that directories exist and that ownership and labeling is
21708     * correct for all installed apps.
21709     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
21710     */
21711    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21712            boolean migrateAppData, boolean onlyCoreApps) {
21713        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21714                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21715        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
21716
21717        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21718        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21719
21720        // First look for stale data that doesn't belong, and check if things
21721        // have changed since we did our last restorecon
21722        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21723            if (StorageManager.isFileEncryptedNativeOrEmulated()
21724                    && !StorageManager.isUserKeyUnlocked(userId)) {
21725                throw new RuntimeException(
21726                        "Yikes, someone asked us to reconcile CE storage while " + userId
21727                                + " was still locked; this would have caused massive data loss!");
21728            }
21729
21730            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21731            for (File file : files) {
21732                final String packageName = file.getName();
21733                try {
21734                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21735                } catch (PackageManagerException e) {
21736                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21737                    try {
21738                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21739                                StorageManager.FLAG_STORAGE_CE, 0);
21740                    } catch (InstallerException e2) {
21741                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21742                    }
21743                }
21744            }
21745        }
21746        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21747            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21748            for (File file : files) {
21749                final String packageName = file.getName();
21750                try {
21751                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21752                } catch (PackageManagerException e) {
21753                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21754                    try {
21755                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21756                                StorageManager.FLAG_STORAGE_DE, 0);
21757                    } catch (InstallerException e2) {
21758                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21759                    }
21760                }
21761            }
21762        }
21763
21764        // Ensure that data directories are ready to roll for all packages
21765        // installed for this volume and user
21766        final List<PackageSetting> packages;
21767        synchronized (mPackages) {
21768            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21769        }
21770        int preparedCount = 0;
21771        for (PackageSetting ps : packages) {
21772            final String packageName = ps.name;
21773            if (ps.pkg == null) {
21774                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21775                // TODO: might be due to legacy ASEC apps; we should circle back
21776                // and reconcile again once they're scanned
21777                continue;
21778            }
21779            // Skip non-core apps if requested
21780            if (onlyCoreApps && !ps.pkg.coreApp) {
21781                result.add(packageName);
21782                continue;
21783            }
21784
21785            if (ps.getInstalled(userId)) {
21786                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
21787                preparedCount++;
21788            }
21789        }
21790
21791        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21792        return result;
21793    }
21794
21795    /**
21796     * Prepare app data for the given app just after it was installed or
21797     * upgraded. This method carefully only touches users that it's installed
21798     * for, and it forces a restorecon to handle any seinfo changes.
21799     * <p>
21800     * Verifies that directories exist and that ownership and labeling is
21801     * correct for all installed apps. If there is an ownership mismatch, it
21802     * will try recovering system apps by wiping data; third-party app data is
21803     * left intact.
21804     * <p>
21805     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21806     */
21807    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21808        final PackageSetting ps;
21809        synchronized (mPackages) {
21810            ps = mSettings.mPackages.get(pkg.packageName);
21811            mSettings.writeKernelMappingLPr(ps);
21812        }
21813
21814        final UserManager um = mContext.getSystemService(UserManager.class);
21815        UserManagerInternal umInternal = getUserManagerInternal();
21816        for (UserInfo user : um.getUsers()) {
21817            final int flags;
21818            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21819                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21820            } else if (umInternal.isUserRunning(user.id)) {
21821                flags = StorageManager.FLAG_STORAGE_DE;
21822            } else {
21823                continue;
21824            }
21825
21826            if (ps.getInstalled(user.id)) {
21827                // TODO: when user data is locked, mark that we're still dirty
21828                prepareAppDataLIF(pkg, user.id, flags);
21829            }
21830        }
21831    }
21832
21833    /**
21834     * Prepare app data for the given app.
21835     * <p>
21836     * Verifies that directories exist and that ownership and labeling is
21837     * correct for all installed apps. If there is an ownership mismatch, this
21838     * will try recovering system apps by wiping data; third-party app data is
21839     * left intact.
21840     */
21841    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21842        if (pkg == null) {
21843            Slog.wtf(TAG, "Package was null!", new Throwable());
21844            return;
21845        }
21846        prepareAppDataLeafLIF(pkg, userId, flags);
21847        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21848        for (int i = 0; i < childCount; i++) {
21849            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21850        }
21851    }
21852
21853    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
21854            boolean maybeMigrateAppData) {
21855        prepareAppDataLIF(pkg, userId, flags);
21856
21857        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
21858            // We may have just shuffled around app data directories, so
21859            // prepare them one more time
21860            prepareAppDataLIF(pkg, userId, flags);
21861        }
21862    }
21863
21864    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21865        if (DEBUG_APP_DATA) {
21866            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21867                    + Integer.toHexString(flags));
21868        }
21869
21870        final String volumeUuid = pkg.volumeUuid;
21871        final String packageName = pkg.packageName;
21872        final ApplicationInfo app = pkg.applicationInfo;
21873        final int appId = UserHandle.getAppId(app.uid);
21874
21875        Preconditions.checkNotNull(app.seInfo);
21876
21877        long ceDataInode = -1;
21878        try {
21879            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21880                    appId, app.seInfo, app.targetSdkVersion);
21881        } catch (InstallerException e) {
21882            if (app.isSystemApp()) {
21883                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21884                        + ", but trying to recover: " + e);
21885                destroyAppDataLeafLIF(pkg, userId, flags);
21886                try {
21887                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21888                            appId, app.seInfo, app.targetSdkVersion);
21889                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21890                } catch (InstallerException e2) {
21891                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21892                }
21893            } else {
21894                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21895            }
21896        }
21897
21898        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21899            // TODO: mark this structure as dirty so we persist it!
21900            synchronized (mPackages) {
21901                final PackageSetting ps = mSettings.mPackages.get(packageName);
21902                if (ps != null) {
21903                    ps.setCeDataInode(ceDataInode, userId);
21904                }
21905            }
21906        }
21907
21908        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21909    }
21910
21911    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21912        if (pkg == null) {
21913            Slog.wtf(TAG, "Package was null!", new Throwable());
21914            return;
21915        }
21916        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21917        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21918        for (int i = 0; i < childCount; i++) {
21919            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21920        }
21921    }
21922
21923    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21924        final String volumeUuid = pkg.volumeUuid;
21925        final String packageName = pkg.packageName;
21926        final ApplicationInfo app = pkg.applicationInfo;
21927
21928        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21929            // Create a native library symlink only if we have native libraries
21930            // and if the native libraries are 32 bit libraries. We do not provide
21931            // this symlink for 64 bit libraries.
21932            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21933                final String nativeLibPath = app.nativeLibraryDir;
21934                try {
21935                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21936                            nativeLibPath, userId);
21937                } catch (InstallerException e) {
21938                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21939                }
21940            }
21941        }
21942    }
21943
21944    /**
21945     * For system apps on non-FBE devices, this method migrates any existing
21946     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21947     * requested by the app.
21948     */
21949    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21950        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
21951                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21952            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21953                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21954            try {
21955                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21956                        storageTarget);
21957            } catch (InstallerException e) {
21958                logCriticalInfo(Log.WARN,
21959                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21960            }
21961            return true;
21962        } else {
21963            return false;
21964        }
21965    }
21966
21967    public PackageFreezer freezePackage(String packageName, String killReason) {
21968        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
21969    }
21970
21971    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
21972        return new PackageFreezer(packageName, userId, killReason);
21973    }
21974
21975    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
21976            String killReason) {
21977        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
21978    }
21979
21980    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
21981            String killReason) {
21982        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
21983            return new PackageFreezer();
21984        } else {
21985            return freezePackage(packageName, userId, killReason);
21986        }
21987    }
21988
21989    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
21990            String killReason) {
21991        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
21992    }
21993
21994    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
21995            String killReason) {
21996        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
21997            return new PackageFreezer();
21998        } else {
21999            return freezePackage(packageName, userId, killReason);
22000        }
22001    }
22002
22003    /**
22004     * Class that freezes and kills the given package upon creation, and
22005     * unfreezes it upon closing. This is typically used when doing surgery on
22006     * app code/data to prevent the app from running while you're working.
22007     */
22008    private class PackageFreezer implements AutoCloseable {
22009        private final String mPackageName;
22010        private final PackageFreezer[] mChildren;
22011
22012        private final boolean mWeFroze;
22013
22014        private final AtomicBoolean mClosed = new AtomicBoolean();
22015        private final CloseGuard mCloseGuard = CloseGuard.get();
22016
22017        /**
22018         * Create and return a stub freezer that doesn't actually do anything,
22019         * typically used when someone requested
22020         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22021         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22022         */
22023        public PackageFreezer() {
22024            mPackageName = null;
22025            mChildren = null;
22026            mWeFroze = false;
22027            mCloseGuard.open("close");
22028        }
22029
22030        public PackageFreezer(String packageName, int userId, String killReason) {
22031            synchronized (mPackages) {
22032                mPackageName = packageName;
22033                mWeFroze = mFrozenPackages.add(mPackageName);
22034
22035                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22036                if (ps != null) {
22037                    killApplication(ps.name, ps.appId, userId, killReason);
22038                }
22039
22040                final PackageParser.Package p = mPackages.get(packageName);
22041                if (p != null && p.childPackages != null) {
22042                    final int N = p.childPackages.size();
22043                    mChildren = new PackageFreezer[N];
22044                    for (int i = 0; i < N; i++) {
22045                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22046                                userId, killReason);
22047                    }
22048                } else {
22049                    mChildren = null;
22050                }
22051            }
22052            mCloseGuard.open("close");
22053        }
22054
22055        @Override
22056        protected void finalize() throws Throwable {
22057            try {
22058                if (mCloseGuard != null) {
22059                    mCloseGuard.warnIfOpen();
22060                }
22061
22062                close();
22063            } finally {
22064                super.finalize();
22065            }
22066        }
22067
22068        @Override
22069        public void close() {
22070            mCloseGuard.close();
22071            if (mClosed.compareAndSet(false, true)) {
22072                synchronized (mPackages) {
22073                    if (mWeFroze) {
22074                        mFrozenPackages.remove(mPackageName);
22075                    }
22076
22077                    if (mChildren != null) {
22078                        for (PackageFreezer freezer : mChildren) {
22079                            freezer.close();
22080                        }
22081                    }
22082                }
22083            }
22084        }
22085    }
22086
22087    /**
22088     * Verify that given package is currently frozen.
22089     */
22090    private void checkPackageFrozen(String packageName) {
22091        synchronized (mPackages) {
22092            if (!mFrozenPackages.contains(packageName)) {
22093                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22094            }
22095        }
22096    }
22097
22098    @Override
22099    public int movePackage(final String packageName, final String volumeUuid) {
22100        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22101
22102        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
22103        final int moveId = mNextMoveId.getAndIncrement();
22104        mHandler.post(new Runnable() {
22105            @Override
22106            public void run() {
22107                try {
22108                    movePackageInternal(packageName, volumeUuid, moveId, user);
22109                } catch (PackageManagerException e) {
22110                    Slog.w(TAG, "Failed to move " + packageName, e);
22111                    mMoveCallbacks.notifyStatusChanged(moveId,
22112                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22113                }
22114            }
22115        });
22116        return moveId;
22117    }
22118
22119    private void movePackageInternal(final String packageName, final String volumeUuid,
22120            final int moveId, UserHandle user) throws PackageManagerException {
22121        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22122        final PackageManager pm = mContext.getPackageManager();
22123
22124        final boolean currentAsec;
22125        final String currentVolumeUuid;
22126        final File codeFile;
22127        final String installerPackageName;
22128        final String packageAbiOverride;
22129        final int appId;
22130        final String seinfo;
22131        final String label;
22132        final int targetSdkVersion;
22133        final PackageFreezer freezer;
22134        final int[] installedUserIds;
22135
22136        // reader
22137        synchronized (mPackages) {
22138            final PackageParser.Package pkg = mPackages.get(packageName);
22139            final PackageSetting ps = mSettings.mPackages.get(packageName);
22140            if (pkg == null || ps == null) {
22141                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22142            }
22143
22144            if (pkg.applicationInfo.isSystemApp()) {
22145                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22146                        "Cannot move system application");
22147            }
22148
22149            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22150            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22151                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22152            if (isInternalStorage && !allow3rdPartyOnInternal) {
22153                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22154                        "3rd party apps are not allowed on internal storage");
22155            }
22156
22157            if (pkg.applicationInfo.isExternalAsec()) {
22158                currentAsec = true;
22159                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22160            } else if (pkg.applicationInfo.isForwardLocked()) {
22161                currentAsec = true;
22162                currentVolumeUuid = "forward_locked";
22163            } else {
22164                currentAsec = false;
22165                currentVolumeUuid = ps.volumeUuid;
22166
22167                final File probe = new File(pkg.codePath);
22168                final File probeOat = new File(probe, "oat");
22169                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22170                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22171                            "Move only supported for modern cluster style installs");
22172                }
22173            }
22174
22175            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22176                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22177                        "Package already moved to " + volumeUuid);
22178            }
22179            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22180                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22181                        "Device admin cannot be moved");
22182            }
22183
22184            if (mFrozenPackages.contains(packageName)) {
22185                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22186                        "Failed to move already frozen package");
22187            }
22188
22189            codeFile = new File(pkg.codePath);
22190            installerPackageName = ps.installerPackageName;
22191            packageAbiOverride = ps.cpuAbiOverrideString;
22192            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22193            seinfo = pkg.applicationInfo.seInfo;
22194            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22195            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22196            freezer = freezePackage(packageName, "movePackageInternal");
22197            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22198        }
22199
22200        final Bundle extras = new Bundle();
22201        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22202        extras.putString(Intent.EXTRA_TITLE, label);
22203        mMoveCallbacks.notifyCreated(moveId, extras);
22204
22205        int installFlags;
22206        final boolean moveCompleteApp;
22207        final File measurePath;
22208
22209        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22210            installFlags = INSTALL_INTERNAL;
22211            moveCompleteApp = !currentAsec;
22212            measurePath = Environment.getDataAppDirectory(volumeUuid);
22213        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22214            installFlags = INSTALL_EXTERNAL;
22215            moveCompleteApp = false;
22216            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22217        } else {
22218            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22219            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22220                    || !volume.isMountedWritable()) {
22221                freezer.close();
22222                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22223                        "Move location not mounted private volume");
22224            }
22225
22226            Preconditions.checkState(!currentAsec);
22227
22228            installFlags = INSTALL_INTERNAL;
22229            moveCompleteApp = true;
22230            measurePath = Environment.getDataAppDirectory(volumeUuid);
22231        }
22232
22233        final PackageStats stats = new PackageStats(null, -1);
22234        synchronized (mInstaller) {
22235            for (int userId : installedUserIds) {
22236                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22237                    freezer.close();
22238                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22239                            "Failed to measure package size");
22240                }
22241            }
22242        }
22243
22244        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22245                + stats.dataSize);
22246
22247        final long startFreeBytes = measurePath.getFreeSpace();
22248        final long sizeBytes;
22249        if (moveCompleteApp) {
22250            sizeBytes = stats.codeSize + stats.dataSize;
22251        } else {
22252            sizeBytes = stats.codeSize;
22253        }
22254
22255        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22256            freezer.close();
22257            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22258                    "Not enough free space to move");
22259        }
22260
22261        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22262
22263        final CountDownLatch installedLatch = new CountDownLatch(1);
22264        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22265            @Override
22266            public void onUserActionRequired(Intent intent) throws RemoteException {
22267                throw new IllegalStateException();
22268            }
22269
22270            @Override
22271            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22272                    Bundle extras) throws RemoteException {
22273                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22274                        + PackageManager.installStatusToString(returnCode, msg));
22275
22276                installedLatch.countDown();
22277                freezer.close();
22278
22279                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22280                switch (status) {
22281                    case PackageInstaller.STATUS_SUCCESS:
22282                        mMoveCallbacks.notifyStatusChanged(moveId,
22283                                PackageManager.MOVE_SUCCEEDED);
22284                        break;
22285                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22286                        mMoveCallbacks.notifyStatusChanged(moveId,
22287                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22288                        break;
22289                    default:
22290                        mMoveCallbacks.notifyStatusChanged(moveId,
22291                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22292                        break;
22293                }
22294            }
22295        };
22296
22297        final MoveInfo move;
22298        if (moveCompleteApp) {
22299            // Kick off a thread to report progress estimates
22300            new Thread() {
22301                @Override
22302                public void run() {
22303                    while (true) {
22304                        try {
22305                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22306                                break;
22307                            }
22308                        } catch (InterruptedException ignored) {
22309                        }
22310
22311                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
22312                        final int progress = 10 + (int) MathUtils.constrain(
22313                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22314                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22315                    }
22316                }
22317            }.start();
22318
22319            final String dataAppName = codeFile.getName();
22320            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22321                    dataAppName, appId, seinfo, targetSdkVersion);
22322        } else {
22323            move = null;
22324        }
22325
22326        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22327
22328        final Message msg = mHandler.obtainMessage(INIT_COPY);
22329        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22330        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22331                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22332                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22333                PackageManager.INSTALL_REASON_UNKNOWN);
22334        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22335        msg.obj = params;
22336
22337        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22338                System.identityHashCode(msg.obj));
22339        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22340                System.identityHashCode(msg.obj));
22341
22342        mHandler.sendMessage(msg);
22343    }
22344
22345    @Override
22346    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22347        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22348
22349        final int realMoveId = mNextMoveId.getAndIncrement();
22350        final Bundle extras = new Bundle();
22351        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22352        mMoveCallbacks.notifyCreated(realMoveId, extras);
22353
22354        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22355            @Override
22356            public void onCreated(int moveId, Bundle extras) {
22357                // Ignored
22358            }
22359
22360            @Override
22361            public void onStatusChanged(int moveId, int status, long estMillis) {
22362                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22363            }
22364        };
22365
22366        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22367        storage.setPrimaryStorageUuid(volumeUuid, callback);
22368        return realMoveId;
22369    }
22370
22371    @Override
22372    public int getMoveStatus(int moveId) {
22373        mContext.enforceCallingOrSelfPermission(
22374                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22375        return mMoveCallbacks.mLastStatus.get(moveId);
22376    }
22377
22378    @Override
22379    public void registerMoveCallback(IPackageMoveObserver callback) {
22380        mContext.enforceCallingOrSelfPermission(
22381                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22382        mMoveCallbacks.register(callback);
22383    }
22384
22385    @Override
22386    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22387        mContext.enforceCallingOrSelfPermission(
22388                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22389        mMoveCallbacks.unregister(callback);
22390    }
22391
22392    @Override
22393    public boolean setInstallLocation(int loc) {
22394        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22395                null);
22396        if (getInstallLocation() == loc) {
22397            return true;
22398        }
22399        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22400                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22401            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22402                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22403            return true;
22404        }
22405        return false;
22406   }
22407
22408    @Override
22409    public int getInstallLocation() {
22410        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22411                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22412                PackageHelper.APP_INSTALL_AUTO);
22413    }
22414
22415    /** Called by UserManagerService */
22416    void cleanUpUser(UserManagerService userManager, int userHandle) {
22417        synchronized (mPackages) {
22418            mDirtyUsers.remove(userHandle);
22419            mUserNeedsBadging.delete(userHandle);
22420            mSettings.removeUserLPw(userHandle);
22421            mPendingBroadcasts.remove(userHandle);
22422            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22423            removeUnusedPackagesLPw(userManager, userHandle);
22424        }
22425    }
22426
22427    /**
22428     * We're removing userHandle and would like to remove any downloaded packages
22429     * that are no longer in use by any other user.
22430     * @param userHandle the user being removed
22431     */
22432    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22433        final boolean DEBUG_CLEAN_APKS = false;
22434        int [] users = userManager.getUserIds();
22435        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22436        while (psit.hasNext()) {
22437            PackageSetting ps = psit.next();
22438            if (ps.pkg == null) {
22439                continue;
22440            }
22441            final String packageName = ps.pkg.packageName;
22442            // Skip over if system app
22443            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22444                continue;
22445            }
22446            if (DEBUG_CLEAN_APKS) {
22447                Slog.i(TAG, "Checking package " + packageName);
22448            }
22449            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22450            if (keep) {
22451                if (DEBUG_CLEAN_APKS) {
22452                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22453                }
22454            } else {
22455                for (int i = 0; i < users.length; i++) {
22456                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22457                        keep = true;
22458                        if (DEBUG_CLEAN_APKS) {
22459                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22460                                    + users[i]);
22461                        }
22462                        break;
22463                    }
22464                }
22465            }
22466            if (!keep) {
22467                if (DEBUG_CLEAN_APKS) {
22468                    Slog.i(TAG, "  Removing package " + packageName);
22469                }
22470                mHandler.post(new Runnable() {
22471                    public void run() {
22472                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22473                                userHandle, 0);
22474                    } //end run
22475                });
22476            }
22477        }
22478    }
22479
22480    /** Called by UserManagerService */
22481    void createNewUser(int userId, String[] disallowedPackages) {
22482        synchronized (mInstallLock) {
22483            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22484        }
22485        synchronized (mPackages) {
22486            scheduleWritePackageRestrictionsLocked(userId);
22487            scheduleWritePackageListLocked(userId);
22488            applyFactoryDefaultBrowserLPw(userId);
22489            primeDomainVerificationsLPw(userId);
22490        }
22491    }
22492
22493    void onNewUserCreated(final int userId) {
22494        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22495        // If permission review for legacy apps is required, we represent
22496        // dagerous permissions for such apps as always granted runtime
22497        // permissions to keep per user flag state whether review is needed.
22498        // Hence, if a new user is added we have to propagate dangerous
22499        // permission grants for these legacy apps.
22500        if (mPermissionReviewRequired) {
22501            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
22502                    | UPDATE_PERMISSIONS_REPLACE_ALL);
22503        }
22504    }
22505
22506    @Override
22507    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22508        mContext.enforceCallingOrSelfPermission(
22509                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22510                "Only package verification agents can read the verifier device identity");
22511
22512        synchronized (mPackages) {
22513            return mSettings.getVerifierDeviceIdentityLPw();
22514        }
22515    }
22516
22517    @Override
22518    public void setPermissionEnforced(String permission, boolean enforced) {
22519        // TODO: Now that we no longer change GID for storage, this should to away.
22520        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22521                "setPermissionEnforced");
22522        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22523            synchronized (mPackages) {
22524                if (mSettings.mReadExternalStorageEnforced == null
22525                        || mSettings.mReadExternalStorageEnforced != enforced) {
22526                    mSettings.mReadExternalStorageEnforced = enforced;
22527                    mSettings.writeLPr();
22528                }
22529            }
22530            // kill any non-foreground processes so we restart them and
22531            // grant/revoke the GID.
22532            final IActivityManager am = ActivityManager.getService();
22533            if (am != null) {
22534                final long token = Binder.clearCallingIdentity();
22535                try {
22536                    am.killProcessesBelowForeground("setPermissionEnforcement");
22537                } catch (RemoteException e) {
22538                } finally {
22539                    Binder.restoreCallingIdentity(token);
22540                }
22541            }
22542        } else {
22543            throw new IllegalArgumentException("No selective enforcement for " + permission);
22544        }
22545    }
22546
22547    @Override
22548    @Deprecated
22549    public boolean isPermissionEnforced(String permission) {
22550        return true;
22551    }
22552
22553    @Override
22554    public boolean isStorageLow() {
22555        final long token = Binder.clearCallingIdentity();
22556        try {
22557            final DeviceStorageMonitorInternal
22558                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22559            if (dsm != null) {
22560                return dsm.isMemoryLow();
22561            } else {
22562                return false;
22563            }
22564        } finally {
22565            Binder.restoreCallingIdentity(token);
22566        }
22567    }
22568
22569    @Override
22570    public IPackageInstaller getPackageInstaller() {
22571        return mInstallerService;
22572    }
22573
22574    private boolean userNeedsBadging(int userId) {
22575        int index = mUserNeedsBadging.indexOfKey(userId);
22576        if (index < 0) {
22577            final UserInfo userInfo;
22578            final long token = Binder.clearCallingIdentity();
22579            try {
22580                userInfo = sUserManager.getUserInfo(userId);
22581            } finally {
22582                Binder.restoreCallingIdentity(token);
22583            }
22584            final boolean b;
22585            if (userInfo != null && userInfo.isManagedProfile()) {
22586                b = true;
22587            } else {
22588                b = false;
22589            }
22590            mUserNeedsBadging.put(userId, b);
22591            return b;
22592        }
22593        return mUserNeedsBadging.valueAt(index);
22594    }
22595
22596    @Override
22597    public KeySet getKeySetByAlias(String packageName, String alias) {
22598        if (packageName == null || alias == null) {
22599            return null;
22600        }
22601        synchronized(mPackages) {
22602            final PackageParser.Package pkg = mPackages.get(packageName);
22603            if (pkg == null) {
22604                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22605                throw new IllegalArgumentException("Unknown package: " + packageName);
22606            }
22607            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22608            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22609        }
22610    }
22611
22612    @Override
22613    public KeySet getSigningKeySet(String packageName) {
22614        if (packageName == null) {
22615            return null;
22616        }
22617        synchronized(mPackages) {
22618            final PackageParser.Package pkg = mPackages.get(packageName);
22619            if (pkg == null) {
22620                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22621                throw new IllegalArgumentException("Unknown package: " + packageName);
22622            }
22623            if (pkg.applicationInfo.uid != Binder.getCallingUid()
22624                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
22625                throw new SecurityException("May not access signing KeySet of other apps.");
22626            }
22627            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22628            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22629        }
22630    }
22631
22632    @Override
22633    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22634        if (packageName == null || ks == null) {
22635            return false;
22636        }
22637        synchronized(mPackages) {
22638            final PackageParser.Package pkg = mPackages.get(packageName);
22639            if (pkg == null) {
22640                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22641                throw new IllegalArgumentException("Unknown package: " + packageName);
22642            }
22643            IBinder ksh = ks.getToken();
22644            if (ksh instanceof KeySetHandle) {
22645                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22646                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22647            }
22648            return false;
22649        }
22650    }
22651
22652    @Override
22653    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22654        if (packageName == null || ks == null) {
22655            return false;
22656        }
22657        synchronized(mPackages) {
22658            final PackageParser.Package pkg = mPackages.get(packageName);
22659            if (pkg == null) {
22660                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22661                throw new IllegalArgumentException("Unknown package: " + packageName);
22662            }
22663            IBinder ksh = ks.getToken();
22664            if (ksh instanceof KeySetHandle) {
22665                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22666                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22667            }
22668            return false;
22669        }
22670    }
22671
22672    private void deletePackageIfUnusedLPr(final String packageName) {
22673        PackageSetting ps = mSettings.mPackages.get(packageName);
22674        if (ps == null) {
22675            return;
22676        }
22677        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22678            // TODO Implement atomic delete if package is unused
22679            // It is currently possible that the package will be deleted even if it is installed
22680            // after this method returns.
22681            mHandler.post(new Runnable() {
22682                public void run() {
22683                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22684                            0, PackageManager.DELETE_ALL_USERS);
22685                }
22686            });
22687        }
22688    }
22689
22690    /**
22691     * Check and throw if the given before/after packages would be considered a
22692     * downgrade.
22693     */
22694    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22695            throws PackageManagerException {
22696        if (after.versionCode < before.mVersionCode) {
22697            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22698                    "Update version code " + after.versionCode + " is older than current "
22699                    + before.mVersionCode);
22700        } else if (after.versionCode == before.mVersionCode) {
22701            if (after.baseRevisionCode < before.baseRevisionCode) {
22702                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22703                        "Update base revision code " + after.baseRevisionCode
22704                        + " is older than current " + before.baseRevisionCode);
22705            }
22706
22707            if (!ArrayUtils.isEmpty(after.splitNames)) {
22708                for (int i = 0; i < after.splitNames.length; i++) {
22709                    final String splitName = after.splitNames[i];
22710                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22711                    if (j != -1) {
22712                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22713                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22714                                    "Update split " + splitName + " revision code "
22715                                    + after.splitRevisionCodes[i] + " is older than current "
22716                                    + before.splitRevisionCodes[j]);
22717                        }
22718                    }
22719                }
22720            }
22721        }
22722    }
22723
22724    private static class MoveCallbacks extends Handler {
22725        private static final int MSG_CREATED = 1;
22726        private static final int MSG_STATUS_CHANGED = 2;
22727
22728        private final RemoteCallbackList<IPackageMoveObserver>
22729                mCallbacks = new RemoteCallbackList<>();
22730
22731        private final SparseIntArray mLastStatus = new SparseIntArray();
22732
22733        public MoveCallbacks(Looper looper) {
22734            super(looper);
22735        }
22736
22737        public void register(IPackageMoveObserver callback) {
22738            mCallbacks.register(callback);
22739        }
22740
22741        public void unregister(IPackageMoveObserver callback) {
22742            mCallbacks.unregister(callback);
22743        }
22744
22745        @Override
22746        public void handleMessage(Message msg) {
22747            final SomeArgs args = (SomeArgs) msg.obj;
22748            final int n = mCallbacks.beginBroadcast();
22749            for (int i = 0; i < n; i++) {
22750                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22751                try {
22752                    invokeCallback(callback, msg.what, args);
22753                } catch (RemoteException ignored) {
22754                }
22755            }
22756            mCallbacks.finishBroadcast();
22757            args.recycle();
22758        }
22759
22760        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22761                throws RemoteException {
22762            switch (what) {
22763                case MSG_CREATED: {
22764                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22765                    break;
22766                }
22767                case MSG_STATUS_CHANGED: {
22768                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22769                    break;
22770                }
22771            }
22772        }
22773
22774        private void notifyCreated(int moveId, Bundle extras) {
22775            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22776
22777            final SomeArgs args = SomeArgs.obtain();
22778            args.argi1 = moveId;
22779            args.arg2 = extras;
22780            obtainMessage(MSG_CREATED, args).sendToTarget();
22781        }
22782
22783        private void notifyStatusChanged(int moveId, int status) {
22784            notifyStatusChanged(moveId, status, -1);
22785        }
22786
22787        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22788            Slog.v(TAG, "Move " + moveId + " status " + status);
22789
22790            final SomeArgs args = SomeArgs.obtain();
22791            args.argi1 = moveId;
22792            args.argi2 = status;
22793            args.arg3 = estMillis;
22794            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22795
22796            synchronized (mLastStatus) {
22797                mLastStatus.put(moveId, status);
22798            }
22799        }
22800    }
22801
22802    private final static class OnPermissionChangeListeners extends Handler {
22803        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22804
22805        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22806                new RemoteCallbackList<>();
22807
22808        public OnPermissionChangeListeners(Looper looper) {
22809            super(looper);
22810        }
22811
22812        @Override
22813        public void handleMessage(Message msg) {
22814            switch (msg.what) {
22815                case MSG_ON_PERMISSIONS_CHANGED: {
22816                    final int uid = msg.arg1;
22817                    handleOnPermissionsChanged(uid);
22818                } break;
22819            }
22820        }
22821
22822        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22823            mPermissionListeners.register(listener);
22824
22825        }
22826
22827        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22828            mPermissionListeners.unregister(listener);
22829        }
22830
22831        public void onPermissionsChanged(int uid) {
22832            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22833                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22834            }
22835        }
22836
22837        private void handleOnPermissionsChanged(int uid) {
22838            final int count = mPermissionListeners.beginBroadcast();
22839            try {
22840                for (int i = 0; i < count; i++) {
22841                    IOnPermissionsChangeListener callback = mPermissionListeners
22842                            .getBroadcastItem(i);
22843                    try {
22844                        callback.onPermissionsChanged(uid);
22845                    } catch (RemoteException e) {
22846                        Log.e(TAG, "Permission listener is dead", e);
22847                    }
22848                }
22849            } finally {
22850                mPermissionListeners.finishBroadcast();
22851            }
22852        }
22853    }
22854
22855    private class PackageManagerInternalImpl extends PackageManagerInternal {
22856        @Override
22857        public void setLocationPackagesProvider(PackagesProvider provider) {
22858            synchronized (mPackages) {
22859                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
22860            }
22861        }
22862
22863        @Override
22864        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22865            synchronized (mPackages) {
22866                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
22867            }
22868        }
22869
22870        @Override
22871        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22872            synchronized (mPackages) {
22873                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
22874            }
22875        }
22876
22877        @Override
22878        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22879            synchronized (mPackages) {
22880                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
22881            }
22882        }
22883
22884        @Override
22885        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22886            synchronized (mPackages) {
22887                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
22888            }
22889        }
22890
22891        @Override
22892        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22893            synchronized (mPackages) {
22894                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
22895            }
22896        }
22897
22898        @Override
22899        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
22900            synchronized (mPackages) {
22901                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
22902                        packageName, userId);
22903            }
22904        }
22905
22906        @Override
22907        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
22908            synchronized (mPackages) {
22909                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
22910                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
22911                        packageName, userId);
22912            }
22913        }
22914
22915        @Override
22916        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
22917            synchronized (mPackages) {
22918                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
22919                        packageName, userId);
22920            }
22921        }
22922
22923        @Override
22924        public void setKeepUninstalledPackages(final List<String> packageList) {
22925            Preconditions.checkNotNull(packageList);
22926            List<String> removedFromList = null;
22927            synchronized (mPackages) {
22928                if (mKeepUninstalledPackages != null) {
22929                    final int packagesCount = mKeepUninstalledPackages.size();
22930                    for (int i = 0; i < packagesCount; i++) {
22931                        String oldPackage = mKeepUninstalledPackages.get(i);
22932                        if (packageList != null && packageList.contains(oldPackage)) {
22933                            continue;
22934                        }
22935                        if (removedFromList == null) {
22936                            removedFromList = new ArrayList<>();
22937                        }
22938                        removedFromList.add(oldPackage);
22939                    }
22940                }
22941                mKeepUninstalledPackages = new ArrayList<>(packageList);
22942                if (removedFromList != null) {
22943                    final int removedCount = removedFromList.size();
22944                    for (int i = 0; i < removedCount; i++) {
22945                        deletePackageIfUnusedLPr(removedFromList.get(i));
22946                    }
22947                }
22948            }
22949        }
22950
22951        @Override
22952        public boolean isPermissionsReviewRequired(String packageName, int userId) {
22953            synchronized (mPackages) {
22954                // If we do not support permission review, done.
22955                if (!mPermissionReviewRequired) {
22956                    return false;
22957                }
22958
22959                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
22960                if (packageSetting == null) {
22961                    return false;
22962                }
22963
22964                // Permission review applies only to apps not supporting the new permission model.
22965                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
22966                    return false;
22967                }
22968
22969                // Legacy apps have the permission and get user consent on launch.
22970                PermissionsState permissionsState = packageSetting.getPermissionsState();
22971                return permissionsState.isPermissionReviewRequired(userId);
22972            }
22973        }
22974
22975        @Override
22976        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
22977            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
22978        }
22979
22980        @Override
22981        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
22982                int userId) {
22983            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
22984        }
22985
22986        @Override
22987        public void setDeviceAndProfileOwnerPackages(
22988                int deviceOwnerUserId, String deviceOwnerPackage,
22989                SparseArray<String> profileOwnerPackages) {
22990            mProtectedPackages.setDeviceAndProfileOwnerPackages(
22991                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
22992        }
22993
22994        @Override
22995        public boolean isPackageDataProtected(int userId, String packageName) {
22996            return mProtectedPackages.isPackageDataProtected(userId, packageName);
22997        }
22998
22999        @Override
23000        public boolean isPackageEphemeral(int userId, String packageName) {
23001            synchronized (mPackages) {
23002                final PackageSetting ps = mSettings.mPackages.get(packageName);
23003                return ps != null ? ps.getInstantApp(userId) : false;
23004            }
23005        }
23006
23007        @Override
23008        public boolean wasPackageEverLaunched(String packageName, int userId) {
23009            synchronized (mPackages) {
23010                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23011            }
23012        }
23013
23014        @Override
23015        public void grantRuntimePermission(String packageName, String name, int userId,
23016                boolean overridePolicy) {
23017            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
23018                    overridePolicy);
23019        }
23020
23021        @Override
23022        public void revokeRuntimePermission(String packageName, String name, int userId,
23023                boolean overridePolicy) {
23024            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
23025                    overridePolicy);
23026        }
23027
23028        @Override
23029        public String getNameForUid(int uid) {
23030            return PackageManagerService.this.getNameForUid(uid);
23031        }
23032
23033        @Override
23034        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23035                Intent origIntent, String resolvedType, String callingPackage, int userId) {
23036            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23037                    responseObj, origIntent, resolvedType, callingPackage, userId);
23038        }
23039
23040        @Override
23041        public void grantEphemeralAccess(int userId, Intent intent,
23042                int targetAppId, int ephemeralAppId) {
23043            synchronized (mPackages) {
23044                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23045                        targetAppId, ephemeralAppId);
23046            }
23047        }
23048
23049        @Override
23050        public boolean isInstantAppInstallerComponent(ComponentName component) {
23051            synchronized (mPackages) {
23052                return component != null && component.equals(mInstantAppInstallerComponent);
23053            }
23054        }
23055
23056        @Override
23057        public void pruneInstantApps() {
23058            synchronized (mPackages) {
23059                mInstantAppRegistry.pruneInstantAppsLPw();
23060            }
23061        }
23062
23063        @Override
23064        public String getSetupWizardPackageName() {
23065            return mSetupWizardPackage;
23066        }
23067
23068        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23069            if (policy != null) {
23070                mExternalSourcesPolicy = policy;
23071            }
23072        }
23073
23074        @Override
23075        public boolean isPackagePersistent(String packageName) {
23076            synchronized (mPackages) {
23077                PackageParser.Package pkg = mPackages.get(packageName);
23078                return pkg != null
23079                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23080                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23081                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23082                        : false;
23083            }
23084        }
23085
23086        @Override
23087        public List<PackageInfo> getOverlayPackages(int userId) {
23088            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23089            synchronized (mPackages) {
23090                for (PackageParser.Package p : mPackages.values()) {
23091                    if (p.mOverlayTarget != null) {
23092                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23093                        if (pkg != null) {
23094                            overlayPackages.add(pkg);
23095                        }
23096                    }
23097                }
23098            }
23099            return overlayPackages;
23100        }
23101
23102        @Override
23103        public List<String> getTargetPackageNames(int userId) {
23104            List<String> targetPackages = new ArrayList<>();
23105            synchronized (mPackages) {
23106                for (PackageParser.Package p : mPackages.values()) {
23107                    if (p.mOverlayTarget == null) {
23108                        targetPackages.add(p.packageName);
23109                    }
23110                }
23111            }
23112            return targetPackages;
23113        }
23114
23115        @Override
23116        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23117                @Nullable List<String> overlayPackageNames) {
23118            synchronized (mPackages) {
23119                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23120                    Slog.e(TAG, "failed to find package " + targetPackageName);
23121                    return false;
23122                }
23123
23124                ArrayList<String> paths = null;
23125                if (overlayPackageNames != null) {
23126                    final int N = overlayPackageNames.size();
23127                    paths = new ArrayList<>(N);
23128                    for (int i = 0; i < N; i++) {
23129                        final String packageName = overlayPackageNames.get(i);
23130                        final PackageParser.Package pkg = mPackages.get(packageName);
23131                        if (pkg == null) {
23132                            Slog.e(TAG, "failed to find package " + packageName);
23133                            return false;
23134                        }
23135                        paths.add(pkg.baseCodePath);
23136                    }
23137                }
23138
23139                ArrayMap<String, ArrayList<String>> userSpecificOverlays =
23140                    mEnabledOverlayPaths.get(userId);
23141                if (userSpecificOverlays == null) {
23142                    userSpecificOverlays = new ArrayMap<>();
23143                    mEnabledOverlayPaths.put(userId, userSpecificOverlays);
23144                }
23145
23146                if (paths != null && paths.size() > 0) {
23147                    userSpecificOverlays.put(targetPackageName, paths);
23148                } else {
23149                    userSpecificOverlays.remove(targetPackageName);
23150                }
23151                return true;
23152            }
23153        }
23154
23155        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23156                int flags, int userId) {
23157            return resolveIntentInternal(
23158                    intent, resolvedType, flags, userId, true /*includeInstantApp*/);
23159        }
23160
23161
23162        @Override
23163        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23164            synchronized (mPackages) {
23165                mIsolatedOwners.put(isolatedUid, ownerUid);
23166            }
23167        }
23168
23169        @Override
23170        public void removeIsolatedUid(int isolatedUid) {
23171            synchronized (mPackages) {
23172                mIsolatedOwners.delete(isolatedUid);
23173            }
23174        }
23175    }
23176
23177    @Override
23178    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23179        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23180        synchronized (mPackages) {
23181            final long identity = Binder.clearCallingIdentity();
23182            try {
23183                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
23184                        packageNames, userId);
23185            } finally {
23186                Binder.restoreCallingIdentity(identity);
23187            }
23188        }
23189    }
23190
23191    @Override
23192    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23193        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23194        synchronized (mPackages) {
23195            final long identity = Binder.clearCallingIdentity();
23196            try {
23197                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
23198                        packageNames, userId);
23199            } finally {
23200                Binder.restoreCallingIdentity(identity);
23201            }
23202        }
23203    }
23204
23205    private static void enforceSystemOrPhoneCaller(String tag) {
23206        int callingUid = Binder.getCallingUid();
23207        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23208            throw new SecurityException(
23209                    "Cannot call " + tag + " from UID " + callingUid);
23210        }
23211    }
23212
23213    boolean isHistoricalPackageUsageAvailable() {
23214        return mPackageUsage.isHistoricalPackageUsageAvailable();
23215    }
23216
23217    /**
23218     * Return a <b>copy</b> of the collection of packages known to the package manager.
23219     * @return A copy of the values of mPackages.
23220     */
23221    Collection<PackageParser.Package> getPackages() {
23222        synchronized (mPackages) {
23223            return new ArrayList<>(mPackages.values());
23224        }
23225    }
23226
23227    /**
23228     * Logs process start information (including base APK hash) to the security log.
23229     * @hide
23230     */
23231    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
23232            String apkFile, int pid) {
23233        if (!SecurityLog.isLoggingEnabled()) {
23234            return;
23235        }
23236        Bundle data = new Bundle();
23237        data.putLong("startTimestamp", System.currentTimeMillis());
23238        data.putString("processName", processName);
23239        data.putInt("uid", uid);
23240        data.putString("seinfo", seinfo);
23241        data.putString("apkFile", apkFile);
23242        data.putInt("pid", pid);
23243        Message msg = mProcessLoggingHandler.obtainMessage(
23244                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
23245        msg.setData(data);
23246        mProcessLoggingHandler.sendMessage(msg);
23247    }
23248
23249    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
23250        return mCompilerStats.getPackageStats(pkgName);
23251    }
23252
23253    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
23254        return getOrCreateCompilerPackageStats(pkg.packageName);
23255    }
23256
23257    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
23258        return mCompilerStats.getOrCreatePackageStats(pkgName);
23259    }
23260
23261    public void deleteCompilerPackageStats(String pkgName) {
23262        mCompilerStats.deletePackageStats(pkgName);
23263    }
23264
23265    @Override
23266    public int getInstallReason(String packageName, int userId) {
23267        enforceCrossUserPermission(Binder.getCallingUid(), userId,
23268                true /* requireFullPermission */, false /* checkShell */,
23269                "get install reason");
23270        synchronized (mPackages) {
23271            final PackageSetting ps = mSettings.mPackages.get(packageName);
23272            if (ps != null) {
23273                return ps.getInstallReason(userId);
23274            }
23275        }
23276        return PackageManager.INSTALL_REASON_UNKNOWN;
23277    }
23278
23279    @Override
23280    public boolean canRequestPackageInstalls(String packageName, int userId) {
23281        int callingUid = Binder.getCallingUid();
23282        int uid = getPackageUid(packageName, 0, userId);
23283        if (callingUid != uid && callingUid != Process.ROOT_UID
23284                && callingUid != Process.SYSTEM_UID) {
23285            throw new SecurityException(
23286                    "Caller uid " + callingUid + " does not own package " + packageName);
23287        }
23288        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
23289        if (info == null) {
23290            return false;
23291        }
23292        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
23293            throw new UnsupportedOperationException(
23294                    "Operation only supported on apps targeting Android O or higher");
23295        }
23296        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
23297        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
23298        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
23299            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
23300        }
23301        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
23302            return false;
23303        }
23304        if (mExternalSourcesPolicy != null) {
23305            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
23306            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
23307                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
23308            }
23309        }
23310        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23311    }
23312
23313    @Override
23314    public ComponentName getInstantAppResolverSettingsComponent() {
23315        return mInstantAppResolverSettingsComponent;
23316    }
23317}
23318