PackageManagerService.java revision a27780e0aa7eab16ea42ad4f93957cf523c82002
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_EPHEMERAL_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.ComponentInfo;
130import android.content.pm.InstantAppInfo;
131import android.content.pm.EphemeralRequest;
132import android.content.pm.EphemeralResolveInfo;
133import android.content.pm.EphemeralResponse;
134import android.content.pm.FallbackCategoryProvider;
135import android.content.pm.FeatureInfo;
136import android.content.pm.IOnPermissionsChangeListener;
137import android.content.pm.IPackageDataObserver;
138import android.content.pm.IPackageDeleteObserver;
139import android.content.pm.IPackageDeleteObserver2;
140import android.content.pm.IPackageInstallObserver2;
141import android.content.pm.IPackageInstaller;
142import android.content.pm.IPackageManager;
143import android.content.pm.IPackageMoveObserver;
144import android.content.pm.IPackageStatsObserver;
145import android.content.pm.InstrumentationInfo;
146import android.content.pm.IntentFilterVerificationInfo;
147import android.content.pm.KeySet;
148import android.content.pm.PackageCleanItem;
149import android.content.pm.PackageInfo;
150import android.content.pm.PackageInfoLite;
151import android.content.pm.PackageInstaller;
152import android.content.pm.PackageManager;
153import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
154import android.content.pm.PackageManagerInternal;
155import android.content.pm.PackageParser;
156import android.content.pm.PackageParser.ActivityIntentInfo;
157import android.content.pm.PackageParser.PackageLite;
158import android.content.pm.PackageParser.PackageParserException;
159import android.content.pm.PackageStats;
160import android.content.pm.PackageUserState;
161import android.content.pm.ParceledListSlice;
162import android.content.pm.PermissionGroupInfo;
163import android.content.pm.PermissionInfo;
164import android.content.pm.ProviderInfo;
165import android.content.pm.ResolveInfo;
166import android.content.pm.ServiceInfo;
167import android.content.pm.SharedLibraryInfo;
168import android.content.pm.Signature;
169import android.content.pm.UserInfo;
170import android.content.pm.VerifierDeviceIdentity;
171import android.content.pm.VerifierInfo;
172import android.content.pm.VersionedPackage;
173import android.content.res.Resources;
174import android.graphics.Bitmap;
175import android.hardware.display.DisplayManager;
176import android.net.Uri;
177import android.os.Binder;
178import android.os.Build;
179import android.os.Bundle;
180import android.os.Debug;
181import android.os.Environment;
182import android.os.Environment.UserEnvironment;
183import android.os.FileUtils;
184import android.os.Handler;
185import android.os.IBinder;
186import android.os.Looper;
187import android.os.Message;
188import android.os.Parcel;
189import android.os.ParcelFileDescriptor;
190import android.os.PatternMatcher;
191import android.os.Process;
192import android.os.RemoteCallbackList;
193import android.os.RemoteException;
194import android.os.ResultReceiver;
195import android.os.SELinux;
196import android.os.ServiceManager;
197import android.os.ShellCallback;
198import android.os.SystemClock;
199import android.os.SystemProperties;
200import android.os.Trace;
201import android.os.UserHandle;
202import android.os.UserManager;
203import android.os.UserManagerInternal;
204import android.os.storage.IStorageManager;
205import android.os.storage.StorageManagerInternal;
206import android.os.storage.StorageEventListener;
207import android.os.storage.StorageManager;
208import android.os.storage.VolumeInfo;
209import android.os.storage.VolumeRecord;
210import android.provider.Settings.Global;
211import android.provider.Settings.Secure;
212import android.security.KeyStore;
213import android.security.SystemKeyStore;
214import android.system.ErrnoException;
215import android.system.Os;
216import android.text.TextUtils;
217import android.text.format.DateUtils;
218import android.util.ArrayMap;
219import android.util.ArraySet;
220import android.util.Base64;
221import android.util.DisplayMetrics;
222import android.util.EventLog;
223import android.util.ExceptionUtils;
224import android.util.Log;
225import android.util.LogPrinter;
226import android.util.MathUtils;
227import android.util.PackageUtils;
228import android.util.Pair;
229import android.util.PrintStreamPrinter;
230import android.util.Slog;
231import android.util.SparseArray;
232import android.util.SparseBooleanArray;
233import android.util.SparseIntArray;
234import android.util.Xml;
235import android.util.jar.StrictJarFile;
236import android.view.Display;
237
238import com.android.internal.R;
239import com.android.internal.annotations.GuardedBy;
240import com.android.internal.app.IMediaContainerService;
241import com.android.internal.app.ResolverActivity;
242import com.android.internal.content.NativeLibraryHelper;
243import com.android.internal.content.PackageHelper;
244import com.android.internal.logging.MetricsLogger;
245import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
246import com.android.internal.os.IParcelFileDescriptorFactory;
247import com.android.internal.os.RoSystemProperties;
248import com.android.internal.os.SomeArgs;
249import com.android.internal.os.Zygote;
250import com.android.internal.telephony.CarrierAppUtils;
251import com.android.internal.util.ArrayUtils;
252import com.android.internal.util.FastPrintWriter;
253import com.android.internal.util.FastXmlSerializer;
254import com.android.internal.util.IndentingPrintWriter;
255import com.android.internal.util.Preconditions;
256import com.android.internal.util.XmlUtils;
257import com.android.server.AttributeCache;
258import com.android.server.BackgroundDexOptJobService;
259import com.android.server.EventLogTags;
260import com.android.server.FgThread;
261import com.android.server.IntentResolver;
262import com.android.server.LocalServices;
263import com.android.server.ServiceThread;
264import com.android.server.SystemConfig;
265import com.android.server.Watchdog;
266import com.android.server.net.NetworkPolicyManagerInternal;
267import com.android.server.pm.Installer.InstallerException;
268import com.android.server.pm.PermissionsState.PermissionState;
269import com.android.server.pm.Settings.DatabaseVersion;
270import com.android.server.pm.Settings.VersionInfo;
271import com.android.server.pm.dex.DexManager;
272import com.android.server.storage.DeviceStorageMonitorInternal;
273
274import dalvik.system.CloseGuard;
275import dalvik.system.DexFile;
276import dalvik.system.VMRuntime;
277
278import libcore.io.IoUtils;
279import libcore.util.EmptyArray;
280
281import org.xmlpull.v1.XmlPullParser;
282import org.xmlpull.v1.XmlPullParserException;
283import org.xmlpull.v1.XmlSerializer;
284
285import java.io.BufferedOutputStream;
286import java.io.BufferedReader;
287import java.io.ByteArrayInputStream;
288import java.io.ByteArrayOutputStream;
289import java.io.File;
290import java.io.FileDescriptor;
291import java.io.FileInputStream;
292import java.io.FileNotFoundException;
293import java.io.FileOutputStream;
294import java.io.FileReader;
295import java.io.FilenameFilter;
296import java.io.IOException;
297import java.io.PrintWriter;
298import java.nio.charset.StandardCharsets;
299import java.security.DigestInputStream;
300import java.security.MessageDigest;
301import java.security.NoSuchAlgorithmException;
302import java.security.PublicKey;
303import java.security.SecureRandom;
304import java.security.cert.Certificate;
305import java.security.cert.CertificateEncodingException;
306import java.security.cert.CertificateException;
307import java.text.SimpleDateFormat;
308import java.util.ArrayList;
309import java.util.Arrays;
310import java.util.Collection;
311import java.util.Collections;
312import java.util.Comparator;
313import java.util.Date;
314import java.util.HashSet;
315import java.util.HashMap;
316import java.util.Iterator;
317import java.util.List;
318import java.util.Map;
319import java.util.Objects;
320import java.util.Set;
321import java.util.concurrent.CountDownLatch;
322import java.util.concurrent.TimeUnit;
323import java.util.concurrent.atomic.AtomicBoolean;
324import java.util.concurrent.atomic.AtomicInteger;
325
326/**
327 * Keep track of all those APKs everywhere.
328 * <p>
329 * Internally there are two important locks:
330 * <ul>
331 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
332 * and other related state. It is a fine-grained lock that should only be held
333 * momentarily, as it's one of the most contended locks in the system.
334 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
335 * operations typically involve heavy lifting of application data on disk. Since
336 * {@code installd} is single-threaded, and it's operations can often be slow,
337 * this lock should never be acquired while already holding {@link #mPackages}.
338 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
339 * holding {@link #mInstallLock}.
340 * </ul>
341 * Many internal methods rely on the caller to hold the appropriate locks, and
342 * this contract is expressed through method name suffixes:
343 * <ul>
344 * <li>fooLI(): the caller must hold {@link #mInstallLock}
345 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
346 * being modified must be frozen
347 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
348 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
349 * </ul>
350 * <p>
351 * Because this class is very central to the platform's security; please run all
352 * CTS and unit tests whenever making modifications:
353 *
354 * <pre>
355 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
356 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
357 * </pre>
358 */
359public class PackageManagerService extends IPackageManager.Stub {
360    static final String TAG = "PackageManager";
361    static final boolean DEBUG_SETTINGS = false;
362    static final boolean DEBUG_PREFERRED = false;
363    static final boolean DEBUG_UPGRADE = false;
364    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
365    private static final boolean DEBUG_BACKUP = false;
366    private static final boolean DEBUG_INSTALL = false;
367    private static final boolean DEBUG_REMOVE = false;
368    private static final boolean DEBUG_BROADCASTS = false;
369    private static final boolean DEBUG_SHOW_INFO = false;
370    private static final boolean DEBUG_PACKAGE_INFO = false;
371    private static final boolean DEBUG_INTENT_MATCHING = false;
372    private static final boolean DEBUG_PACKAGE_SCANNING = false;
373    private static final boolean DEBUG_VERIFY = false;
374    private static final boolean DEBUG_FILTERS = false;
375
376    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
377    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
378    // user, but by default initialize to this.
379    public static final boolean DEBUG_DEXOPT = false;
380
381    private static final boolean DEBUG_ABI_SELECTION = false;
382    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
383    private static final boolean DEBUG_TRIAGED_MISSING = false;
384    private static final boolean DEBUG_APP_DATA = false;
385
386    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
387    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
388
389    private static final boolean DISABLE_EPHEMERAL_APPS = false;
390    private static final boolean HIDE_EPHEMERAL_APIS = false;
391
392    private static final boolean ENABLE_QUOTA =
393            SystemProperties.getBoolean("persist.fw.quota", false);
394
395    private static final int RADIO_UID = Process.PHONE_UID;
396    private static final int LOG_UID = Process.LOG_UID;
397    private static final int NFC_UID = Process.NFC_UID;
398    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
399    private static final int SHELL_UID = Process.SHELL_UID;
400
401    // Cap the size of permission trees that 3rd party apps can define
402    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
403
404    // Suffix used during package installation when copying/moving
405    // package apks to install directory.
406    private static final String INSTALL_PACKAGE_SUFFIX = "-";
407
408    static final int SCAN_NO_DEX = 1<<1;
409    static final int SCAN_FORCE_DEX = 1<<2;
410    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
411    static final int SCAN_NEW_INSTALL = 1<<4;
412    static final int SCAN_UPDATE_TIME = 1<<5;
413    static final int SCAN_BOOTING = 1<<6;
414    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
415    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
416    static final int SCAN_REPLACING = 1<<9;
417    static final int SCAN_REQUIRE_KNOWN = 1<<10;
418    static final int SCAN_MOVE = 1<<11;
419    static final int SCAN_INITIAL = 1<<12;
420    static final int SCAN_CHECK_ONLY = 1<<13;
421    static final int SCAN_DONT_KILL_APP = 1<<14;
422    static final int SCAN_IGNORE_FROZEN = 1<<15;
423    static final int REMOVE_CHATTY = 1<<16;
424    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<17;
425
426    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
427
428    private static final int[] EMPTY_INT_ARRAY = new int[0];
429
430    /**
431     * Timeout (in milliseconds) after which the watchdog should declare that
432     * our handler thread is wedged.  The usual default for such things is one
433     * minute but we sometimes do very lengthy I/O operations on this thread,
434     * such as installing multi-gigabyte applications, so ours needs to be longer.
435     */
436    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
437
438    /**
439     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
440     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
441     * settings entry if available, otherwise we use the hardcoded default.  If it's been
442     * more than this long since the last fstrim, we force one during the boot sequence.
443     *
444     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
445     * one gets run at the next available charging+idle time.  This final mandatory
446     * no-fstrim check kicks in only of the other scheduling criteria is never met.
447     */
448    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
449
450    /**
451     * Whether verification is enabled by default.
452     */
453    private static final boolean DEFAULT_VERIFY_ENABLE = true;
454
455    /**
456     * The default maximum time to wait for the verification agent to return in
457     * milliseconds.
458     */
459    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
460
461    /**
462     * The default response for package verification timeout.
463     *
464     * This can be either PackageManager.VERIFICATION_ALLOW or
465     * PackageManager.VERIFICATION_REJECT.
466     */
467    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
468
469    static final String PLATFORM_PACKAGE_NAME = "android";
470
471    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
472
473    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
474            DEFAULT_CONTAINER_PACKAGE,
475            "com.android.defcontainer.DefaultContainerService");
476
477    private static final String KILL_APP_REASON_GIDS_CHANGED =
478            "permission grant or revoke changed gids";
479
480    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
481            "permissions revoked";
482
483    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
484
485    private static final String PACKAGE_SCHEME = "package";
486
487    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
488    /**
489     * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in
490     * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to
491     * VENDOR_OVERLAY_DIR.
492     */
493    private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme";
494    /**
495     * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever
496     * is in VENDOR_OVERLAY_THEME_PROPERTY.
497     */
498    private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY
499            = "persist.vendor.overlay.theme";
500
501    /** Permission grant: not grant the permission. */
502    private static final int GRANT_DENIED = 1;
503
504    /** Permission grant: grant the permission as an install permission. */
505    private static final int GRANT_INSTALL = 2;
506
507    /** Permission grant: grant the permission as a runtime one. */
508    private static final int GRANT_RUNTIME = 3;
509
510    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
511    private static final int GRANT_UPGRADE = 4;
512
513    /** Canonical intent used to identify what counts as a "web browser" app */
514    private static final Intent sBrowserIntent;
515    static {
516        sBrowserIntent = new Intent();
517        sBrowserIntent.setAction(Intent.ACTION_VIEW);
518        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
519        sBrowserIntent.setData(Uri.parse("http:"));
520    }
521
522    /**
523     * The set of all protected actions [i.e. those actions for which a high priority
524     * intent filter is disallowed].
525     */
526    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
527    static {
528        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
529        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
530        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
531        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
532    }
533
534    // Compilation reasons.
535    public static final int REASON_FIRST_BOOT = 0;
536    public static final int REASON_BOOT = 1;
537    public static final int REASON_INSTALL = 2;
538    public static final int REASON_BACKGROUND_DEXOPT = 3;
539    public static final int REASON_AB_OTA = 4;
540    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
541    public static final int REASON_SHARED_APK = 6;
542    public static final int REASON_FORCED_DEXOPT = 7;
543    public static final int REASON_CORE_APP = 8;
544
545    public static final int REASON_LAST = REASON_CORE_APP;
546
547    /** Special library name that skips shared libraries check during compilation. */
548    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
549
550    /** All dangerous permission names in the same order as the events in MetricsEvent */
551    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
552            Manifest.permission.READ_CALENDAR,
553            Manifest.permission.WRITE_CALENDAR,
554            Manifest.permission.CAMERA,
555            Manifest.permission.READ_CONTACTS,
556            Manifest.permission.WRITE_CONTACTS,
557            Manifest.permission.GET_ACCOUNTS,
558            Manifest.permission.ACCESS_FINE_LOCATION,
559            Manifest.permission.ACCESS_COARSE_LOCATION,
560            Manifest.permission.RECORD_AUDIO,
561            Manifest.permission.READ_PHONE_STATE,
562            Manifest.permission.CALL_PHONE,
563            Manifest.permission.READ_CALL_LOG,
564            Manifest.permission.WRITE_CALL_LOG,
565            Manifest.permission.ADD_VOICEMAIL,
566            Manifest.permission.USE_SIP,
567            Manifest.permission.PROCESS_OUTGOING_CALLS,
568            Manifest.permission.READ_CELL_BROADCASTS,
569            Manifest.permission.BODY_SENSORS,
570            Manifest.permission.SEND_SMS,
571            Manifest.permission.RECEIVE_SMS,
572            Manifest.permission.READ_SMS,
573            Manifest.permission.RECEIVE_WAP_PUSH,
574            Manifest.permission.RECEIVE_MMS,
575            Manifest.permission.READ_EXTERNAL_STORAGE,
576            Manifest.permission.WRITE_EXTERNAL_STORAGE,
577            Manifest.permission.READ_PHONE_NUMBER);
578
579
580    /**
581     * Version number for the package parser cache. Increment this whenever the format or
582     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
583     */
584    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
585
586    /**
587     * Whether the package parser cache is enabled.
588     */
589    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
590
591    final ServiceThread mHandlerThread;
592
593    final PackageHandler mHandler;
594
595    private final ProcessLoggingHandler mProcessLoggingHandler;
596
597    /**
598     * Messages for {@link #mHandler} that need to wait for system ready before
599     * being dispatched.
600     */
601    private ArrayList<Message> mPostSystemReadyMessages;
602
603    final int mSdkVersion = Build.VERSION.SDK_INT;
604
605    final Context mContext;
606    final boolean mFactoryTest;
607    final boolean mOnlyCore;
608    final DisplayMetrics mMetrics;
609    final int mDefParseFlags;
610    final String[] mSeparateProcesses;
611    final boolean mIsUpgrade;
612    final boolean mIsPreNUpgrade;
613    final boolean mIsPreNMR1Upgrade;
614
615    @GuardedBy("mPackages")
616    private boolean mDexOptDialogShown;
617
618    /** The location for ASEC container files on internal storage. */
619    final String mAsecInternalPath;
620
621    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
622    // LOCK HELD.  Can be called with mInstallLock held.
623    @GuardedBy("mInstallLock")
624    final Installer mInstaller;
625
626    /** Directory where installed third-party apps stored */
627    final File mAppInstallDir;
628    final File mEphemeralInstallDir;
629
630    /**
631     * Directory to which applications installed internally have their
632     * 32 bit native libraries copied.
633     */
634    private File mAppLib32InstallDir;
635
636    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
637    // apps.
638    final File mDrmAppPrivateInstallDir;
639
640    // ----------------------------------------------------------------
641
642    // Lock for state used when installing and doing other long running
643    // operations.  Methods that must be called with this lock held have
644    // the suffix "LI".
645    final Object mInstallLock = new Object();
646
647    // ----------------------------------------------------------------
648
649    // Keys are String (package name), values are Package.  This also serves
650    // as the lock for the global state.  Methods that must be called with
651    // this lock held have the prefix "LP".
652    @GuardedBy("mPackages")
653    final ArrayMap<String, PackageParser.Package> mPackages =
654            new ArrayMap<String, PackageParser.Package>();
655
656    final ArrayMap<String, Set<String>> mKnownCodebase =
657            new ArrayMap<String, Set<String>>();
658
659    // Tracks available target package names -> overlay package paths.
660    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
661        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
662
663    /**
664     * Tracks new system packages [received in an OTA] that we expect to
665     * find updated user-installed versions. Keys are package name, values
666     * are package location.
667     */
668    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
669    /**
670     * Tracks high priority intent filters for protected actions. During boot, certain
671     * filter actions are protected and should never be allowed to have a high priority
672     * intent filter for them. However, there is one, and only one exception -- the
673     * setup wizard. It must be able to define a high priority intent filter for these
674     * actions to ensure there are no escapes from the wizard. We need to delay processing
675     * of these during boot as we need to look at all of the system packages in order
676     * to know which component is the setup wizard.
677     */
678    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
679    /**
680     * Whether or not processing protected filters should be deferred.
681     */
682    private boolean mDeferProtectedFilters = true;
683
684    /**
685     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
686     */
687    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
688    /**
689     * Whether or not system app permissions should be promoted from install to runtime.
690     */
691    boolean mPromoteSystemApps;
692
693    @GuardedBy("mPackages")
694    final Settings mSettings;
695
696    /**
697     * Set of package names that are currently "frozen", which means active
698     * surgery is being done on the code/data for that package. The platform
699     * will refuse to launch frozen packages to avoid race conditions.
700     *
701     * @see PackageFreezer
702     */
703    @GuardedBy("mPackages")
704    final ArraySet<String> mFrozenPackages = new ArraySet<>();
705
706    final ProtectedPackages mProtectedPackages;
707
708    boolean mFirstBoot;
709
710    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
711
712    // System configuration read by SystemConfig.
713    final int[] mGlobalGids;
714    final SparseArray<ArraySet<String>> mSystemPermissions;
715    @GuardedBy("mAvailableFeatures")
716    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
717
718    // If mac_permissions.xml was found for seinfo labeling.
719    boolean mFoundPolicyFile;
720
721    private final InstantAppRegistry mInstantAppRegistry;
722
723    public static final class SharedLibraryEntry {
724        public final String path;
725        public final String apk;
726        public final SharedLibraryInfo info;
727
728        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
729                String declaringPackageName, int declaringPackageVersionCode) {
730            path = _path;
731            apk = _apk;
732            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
733                    declaringPackageName, declaringPackageVersionCode), null);
734        }
735    }
736
737    // Currently known shared libraries.
738    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
739    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
740            new ArrayMap<>();
741
742    // All available activities, for your resolving pleasure.
743    final ActivityIntentResolver mActivities =
744            new ActivityIntentResolver();
745
746    // All available receivers, for your resolving pleasure.
747    final ActivityIntentResolver mReceivers =
748            new ActivityIntentResolver();
749
750    // All available services, for your resolving pleasure.
751    final ServiceIntentResolver mServices = new ServiceIntentResolver();
752
753    // All available providers, for your resolving pleasure.
754    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
755
756    // Mapping from provider base names (first directory in content URI codePath)
757    // to the provider information.
758    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
759            new ArrayMap<String, PackageParser.Provider>();
760
761    // Mapping from instrumentation class names to info about them.
762    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
763            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
764
765    // Mapping from permission names to info about them.
766    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
767            new ArrayMap<String, PackageParser.PermissionGroup>();
768
769    // Packages whose data we have transfered into another package, thus
770    // should no longer exist.
771    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
772
773    // Broadcast actions that are only available to the system.
774    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
775
776    /** List of packages waiting for verification. */
777    final SparseArray<PackageVerificationState> mPendingVerification
778            = new SparseArray<PackageVerificationState>();
779
780    /** Set of packages associated with each app op permission. */
781    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
782
783    final PackageInstallerService mInstallerService;
784
785    private final PackageDexOptimizer mPackageDexOptimizer;
786    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
787    // is used by other apps).
788    private final DexManager mDexManager;
789
790    private AtomicInteger mNextMoveId = new AtomicInteger();
791    private final MoveCallbacks mMoveCallbacks;
792
793    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
794
795    // Cache of users who need badging.
796    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
797
798    /** Token for keys in mPendingVerification. */
799    private int mPendingVerificationToken = 0;
800
801    volatile boolean mSystemReady;
802    volatile boolean mSafeMode;
803    volatile boolean mHasSystemUidErrors;
804
805    ApplicationInfo mAndroidApplication;
806    final ActivityInfo mResolveActivity = new ActivityInfo();
807    final ResolveInfo mResolveInfo = new ResolveInfo();
808    ComponentName mResolveComponentName;
809    PackageParser.Package mPlatformPackage;
810    ComponentName mCustomResolverComponentName;
811
812    boolean mResolverReplaced = false;
813
814    private final @Nullable ComponentName mIntentFilterVerifierComponent;
815    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
816
817    private int mIntentFilterVerificationToken = 0;
818
819    /** The service connection to the ephemeral resolver */
820    final EphemeralResolverConnection mEphemeralResolverConnection;
821
822    /** Component used to install ephemeral applications */
823    ComponentName mEphemeralInstallerComponent;
824    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
825    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
826
827    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
828            = new SparseArray<IntentFilterVerificationState>();
829
830    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
831
832    // List of packages names to keep cached, even if they are uninstalled for all users
833    private List<String> mKeepUninstalledPackages;
834
835    private UserManagerInternal mUserManagerInternal;
836    private final UserDataPreparer mUserDataPreparer;
837
838    private File mCacheDir;
839
840    private static class IFVerificationParams {
841        PackageParser.Package pkg;
842        boolean replacing;
843        int userId;
844        int verifierUid;
845
846        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
847                int _userId, int _verifierUid) {
848            pkg = _pkg;
849            replacing = _replacing;
850            userId = _userId;
851            replacing = _replacing;
852            verifierUid = _verifierUid;
853        }
854    }
855
856    private interface IntentFilterVerifier<T extends IntentFilter> {
857        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
858                                               T filter, String packageName);
859        void startVerifications(int userId);
860        void receiveVerificationResponse(int verificationId);
861    }
862
863    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
864        private Context mContext;
865        private ComponentName mIntentFilterVerifierComponent;
866        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
867
868        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
869            mContext = context;
870            mIntentFilterVerifierComponent = verifierComponent;
871        }
872
873        private String getDefaultScheme() {
874            return IntentFilter.SCHEME_HTTPS;
875        }
876
877        @Override
878        public void startVerifications(int userId) {
879            // Launch verifications requests
880            int count = mCurrentIntentFilterVerifications.size();
881            for (int n=0; n<count; n++) {
882                int verificationId = mCurrentIntentFilterVerifications.get(n);
883                final IntentFilterVerificationState ivs =
884                        mIntentFilterVerificationStates.get(verificationId);
885
886                String packageName = ivs.getPackageName();
887
888                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
889                final int filterCount = filters.size();
890                ArraySet<String> domainsSet = new ArraySet<>();
891                for (int m=0; m<filterCount; m++) {
892                    PackageParser.ActivityIntentInfo filter = filters.get(m);
893                    domainsSet.addAll(filter.getHostsList());
894                }
895                synchronized (mPackages) {
896                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
897                            packageName, domainsSet) != null) {
898                        scheduleWriteSettingsLocked();
899                    }
900                }
901                sendVerificationRequest(userId, verificationId, ivs);
902            }
903            mCurrentIntentFilterVerifications.clear();
904        }
905
906        private void sendVerificationRequest(int userId, int verificationId,
907                IntentFilterVerificationState ivs) {
908
909            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
910            verificationIntent.putExtra(
911                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
912                    verificationId);
913            verificationIntent.putExtra(
914                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
915                    getDefaultScheme());
916            verificationIntent.putExtra(
917                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
918                    ivs.getHostsString());
919            verificationIntent.putExtra(
920                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
921                    ivs.getPackageName());
922            verificationIntent.setComponent(mIntentFilterVerifierComponent);
923            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
924
925            UserHandle user = new UserHandle(userId);
926            mContext.sendBroadcastAsUser(verificationIntent, user);
927            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
928                    "Sending IntentFilter verification broadcast");
929        }
930
931        public void receiveVerificationResponse(int verificationId) {
932            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
933
934            final boolean verified = ivs.isVerified();
935
936            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
937            final int count = filters.size();
938            if (DEBUG_DOMAIN_VERIFICATION) {
939                Slog.i(TAG, "Received verification response " + verificationId
940                        + " for " + count + " filters, verified=" + verified);
941            }
942            for (int n=0; n<count; n++) {
943                PackageParser.ActivityIntentInfo filter = filters.get(n);
944                filter.setVerified(verified);
945
946                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
947                        + " verified with result:" + verified + " and hosts:"
948                        + ivs.getHostsString());
949            }
950
951            mIntentFilterVerificationStates.remove(verificationId);
952
953            final String packageName = ivs.getPackageName();
954            IntentFilterVerificationInfo ivi = null;
955
956            synchronized (mPackages) {
957                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
958            }
959            if (ivi == null) {
960                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
961                        + verificationId + " packageName:" + packageName);
962                return;
963            }
964            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
965                    "Updating IntentFilterVerificationInfo for package " + packageName
966                            +" verificationId:" + verificationId);
967
968            synchronized (mPackages) {
969                if (verified) {
970                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
971                } else {
972                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
973                }
974                scheduleWriteSettingsLocked();
975
976                final int userId = ivs.getUserId();
977                if (userId != UserHandle.USER_ALL) {
978                    final int userStatus =
979                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
980
981                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
982                    boolean needUpdate = false;
983
984                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
985                    // already been set by the User thru the Disambiguation dialog
986                    switch (userStatus) {
987                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
988                            if (verified) {
989                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
990                            } else {
991                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
992                            }
993                            needUpdate = true;
994                            break;
995
996                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
997                            if (verified) {
998                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
999                                needUpdate = true;
1000                            }
1001                            break;
1002
1003                        default:
1004                            // Nothing to do
1005                    }
1006
1007                    if (needUpdate) {
1008                        mSettings.updateIntentFilterVerificationStatusLPw(
1009                                packageName, updatedStatus, userId);
1010                        scheduleWritePackageRestrictionsLocked(userId);
1011                    }
1012                }
1013            }
1014        }
1015
1016        @Override
1017        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1018                    ActivityIntentInfo filter, String packageName) {
1019            if (!hasValidDomains(filter)) {
1020                return false;
1021            }
1022            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1023            if (ivs == null) {
1024                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1025                        packageName);
1026            }
1027            if (DEBUG_DOMAIN_VERIFICATION) {
1028                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1029            }
1030            ivs.addFilter(filter);
1031            return true;
1032        }
1033
1034        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1035                int userId, int verificationId, String packageName) {
1036            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1037                    verifierUid, userId, packageName);
1038            ivs.setPendingState();
1039            synchronized (mPackages) {
1040                mIntentFilterVerificationStates.append(verificationId, ivs);
1041                mCurrentIntentFilterVerifications.add(verificationId);
1042            }
1043            return ivs;
1044        }
1045    }
1046
1047    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1048        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1049                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1050                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1051    }
1052
1053    // Set of pending broadcasts for aggregating enable/disable of components.
1054    static class PendingPackageBroadcasts {
1055        // for each user id, a map of <package name -> components within that package>
1056        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1057
1058        public PendingPackageBroadcasts() {
1059            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1060        }
1061
1062        public ArrayList<String> get(int userId, String packageName) {
1063            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1064            return packages.get(packageName);
1065        }
1066
1067        public void put(int userId, String packageName, ArrayList<String> components) {
1068            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1069            packages.put(packageName, components);
1070        }
1071
1072        public void remove(int userId, String packageName) {
1073            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1074            if (packages != null) {
1075                packages.remove(packageName);
1076            }
1077        }
1078
1079        public void remove(int userId) {
1080            mUidMap.remove(userId);
1081        }
1082
1083        public int userIdCount() {
1084            return mUidMap.size();
1085        }
1086
1087        public int userIdAt(int n) {
1088            return mUidMap.keyAt(n);
1089        }
1090
1091        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1092            return mUidMap.get(userId);
1093        }
1094
1095        public int size() {
1096            // total number of pending broadcast entries across all userIds
1097            int num = 0;
1098            for (int i = 0; i< mUidMap.size(); i++) {
1099                num += mUidMap.valueAt(i).size();
1100            }
1101            return num;
1102        }
1103
1104        public void clear() {
1105            mUidMap.clear();
1106        }
1107
1108        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1109            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1110            if (map == null) {
1111                map = new ArrayMap<String, ArrayList<String>>();
1112                mUidMap.put(userId, map);
1113            }
1114            return map;
1115        }
1116    }
1117    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1118
1119    // Service Connection to remote media container service to copy
1120    // package uri's from external media onto secure containers
1121    // or internal storage.
1122    private IMediaContainerService mContainerService = null;
1123
1124    static final int SEND_PENDING_BROADCAST = 1;
1125    static final int MCS_BOUND = 3;
1126    static final int END_COPY = 4;
1127    static final int INIT_COPY = 5;
1128    static final int MCS_UNBIND = 6;
1129    static final int START_CLEANING_PACKAGE = 7;
1130    static final int FIND_INSTALL_LOC = 8;
1131    static final int POST_INSTALL = 9;
1132    static final int MCS_RECONNECT = 10;
1133    static final int MCS_GIVE_UP = 11;
1134    static final int UPDATED_MEDIA_STATUS = 12;
1135    static final int WRITE_SETTINGS = 13;
1136    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1137    static final int PACKAGE_VERIFIED = 15;
1138    static final int CHECK_PENDING_VERIFICATION = 16;
1139    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1140    static final int INTENT_FILTER_VERIFIED = 18;
1141    static final int WRITE_PACKAGE_LIST = 19;
1142    static final int EPHEMERAL_RESOLUTION_PHASE_TWO = 20;
1143
1144    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1145
1146    // Delay time in millisecs
1147    static final int BROADCAST_DELAY = 10 * 1000;
1148
1149    static UserManagerService sUserManager;
1150
1151    // Stores a list of users whose package restrictions file needs to be updated
1152    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1153
1154    final private DefaultContainerConnection mDefContainerConn =
1155            new DefaultContainerConnection();
1156    class DefaultContainerConnection implements ServiceConnection {
1157        public void onServiceConnected(ComponentName name, IBinder service) {
1158            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1159            final IMediaContainerService imcs = IMediaContainerService.Stub
1160                    .asInterface(Binder.allowBlocking(service));
1161            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1162        }
1163
1164        public void onServiceDisconnected(ComponentName name) {
1165            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1166        }
1167    }
1168
1169    // Recordkeeping of restore-after-install operations that are currently in flight
1170    // between the Package Manager and the Backup Manager
1171    static class PostInstallData {
1172        public InstallArgs args;
1173        public PackageInstalledInfo res;
1174
1175        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1176            args = _a;
1177            res = _r;
1178        }
1179    }
1180
1181    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1182    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1183
1184    // XML tags for backup/restore of various bits of state
1185    private static final String TAG_PREFERRED_BACKUP = "pa";
1186    private static final String TAG_DEFAULT_APPS = "da";
1187    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1188
1189    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1190    private static final String TAG_ALL_GRANTS = "rt-grants";
1191    private static final String TAG_GRANT = "grant";
1192    private static final String ATTR_PACKAGE_NAME = "pkg";
1193
1194    private static final String TAG_PERMISSION = "perm";
1195    private static final String ATTR_PERMISSION_NAME = "name";
1196    private static final String ATTR_IS_GRANTED = "g";
1197    private static final String ATTR_USER_SET = "set";
1198    private static final String ATTR_USER_FIXED = "fixed";
1199    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1200
1201    // System/policy permission grants are not backed up
1202    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1203            FLAG_PERMISSION_POLICY_FIXED
1204            | FLAG_PERMISSION_SYSTEM_FIXED
1205            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1206
1207    // And we back up these user-adjusted states
1208    private static final int USER_RUNTIME_GRANT_MASK =
1209            FLAG_PERMISSION_USER_SET
1210            | FLAG_PERMISSION_USER_FIXED
1211            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1212
1213    final @Nullable String mRequiredVerifierPackage;
1214    final @NonNull String mRequiredInstallerPackage;
1215    final @NonNull String mRequiredUninstallerPackage;
1216    final @Nullable String mSetupWizardPackage;
1217    final @Nullable String mStorageManagerPackage;
1218    final @NonNull String mServicesSystemSharedLibraryPackageName;
1219    final @NonNull String mSharedSystemSharedLibraryPackageName;
1220
1221    final boolean mPermissionReviewRequired;
1222
1223    private final PackageUsage mPackageUsage = new PackageUsage();
1224    private final CompilerStats mCompilerStats = new CompilerStats();
1225
1226    class PackageHandler extends Handler {
1227        private boolean mBound = false;
1228        final ArrayList<HandlerParams> mPendingInstalls =
1229            new ArrayList<HandlerParams>();
1230
1231        private boolean connectToService() {
1232            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1233                    " DefaultContainerService");
1234            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1235            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1236            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1237                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1238                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1239                mBound = true;
1240                return true;
1241            }
1242            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1243            return false;
1244        }
1245
1246        private void disconnectService() {
1247            mContainerService = null;
1248            mBound = false;
1249            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1250            mContext.unbindService(mDefContainerConn);
1251            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1252        }
1253
1254        PackageHandler(Looper looper) {
1255            super(looper);
1256        }
1257
1258        public void handleMessage(Message msg) {
1259            try {
1260                doHandleMessage(msg);
1261            } finally {
1262                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1263            }
1264        }
1265
1266        void doHandleMessage(Message msg) {
1267            switch (msg.what) {
1268                case INIT_COPY: {
1269                    HandlerParams params = (HandlerParams) msg.obj;
1270                    int idx = mPendingInstalls.size();
1271                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1272                    // If a bind was already initiated we dont really
1273                    // need to do anything. The pending install
1274                    // will be processed later on.
1275                    if (!mBound) {
1276                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1277                                System.identityHashCode(mHandler));
1278                        // If this is the only one pending we might
1279                        // have to bind to the service again.
1280                        if (!connectToService()) {
1281                            Slog.e(TAG, "Failed to bind to media container service");
1282                            params.serviceError();
1283                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1284                                    System.identityHashCode(mHandler));
1285                            if (params.traceMethod != null) {
1286                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1287                                        params.traceCookie);
1288                            }
1289                            return;
1290                        } else {
1291                            // Once we bind to the service, the first
1292                            // pending request will be processed.
1293                            mPendingInstalls.add(idx, params);
1294                        }
1295                    } else {
1296                        mPendingInstalls.add(idx, params);
1297                        // Already bound to the service. Just make
1298                        // sure we trigger off processing the first request.
1299                        if (idx == 0) {
1300                            mHandler.sendEmptyMessage(MCS_BOUND);
1301                        }
1302                    }
1303                    break;
1304                }
1305                case MCS_BOUND: {
1306                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1307                    if (msg.obj != null) {
1308                        mContainerService = (IMediaContainerService) msg.obj;
1309                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1310                                System.identityHashCode(mHandler));
1311                    }
1312                    if (mContainerService == null) {
1313                        if (!mBound) {
1314                            // Something seriously wrong since we are not bound and we are not
1315                            // waiting for connection. Bail out.
1316                            Slog.e(TAG, "Cannot bind to media container service");
1317                            for (HandlerParams params : mPendingInstalls) {
1318                                // Indicate service bind error
1319                                params.serviceError();
1320                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1321                                        System.identityHashCode(params));
1322                                if (params.traceMethod != null) {
1323                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1324                                            params.traceMethod, params.traceCookie);
1325                                }
1326                                return;
1327                            }
1328                            mPendingInstalls.clear();
1329                        } else {
1330                            Slog.w(TAG, "Waiting to connect to media container service");
1331                        }
1332                    } else if (mPendingInstalls.size() > 0) {
1333                        HandlerParams params = mPendingInstalls.get(0);
1334                        if (params != null) {
1335                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1336                                    System.identityHashCode(params));
1337                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1338                            if (params.startCopy()) {
1339                                // We are done...  look for more work or to
1340                                // go idle.
1341                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1342                                        "Checking for more work or unbind...");
1343                                // Delete pending install
1344                                if (mPendingInstalls.size() > 0) {
1345                                    mPendingInstalls.remove(0);
1346                                }
1347                                if (mPendingInstalls.size() == 0) {
1348                                    if (mBound) {
1349                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1350                                                "Posting delayed MCS_UNBIND");
1351                                        removeMessages(MCS_UNBIND);
1352                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1353                                        // Unbind after a little delay, to avoid
1354                                        // continual thrashing.
1355                                        sendMessageDelayed(ubmsg, 10000);
1356                                    }
1357                                } else {
1358                                    // There are more pending requests in queue.
1359                                    // Just post MCS_BOUND message to trigger processing
1360                                    // of next pending install.
1361                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1362                                            "Posting MCS_BOUND for next work");
1363                                    mHandler.sendEmptyMessage(MCS_BOUND);
1364                                }
1365                            }
1366                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1367                        }
1368                    } else {
1369                        // Should never happen ideally.
1370                        Slog.w(TAG, "Empty queue");
1371                    }
1372                    break;
1373                }
1374                case MCS_RECONNECT: {
1375                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1376                    if (mPendingInstalls.size() > 0) {
1377                        if (mBound) {
1378                            disconnectService();
1379                        }
1380                        if (!connectToService()) {
1381                            Slog.e(TAG, "Failed to bind to media container service");
1382                            for (HandlerParams params : mPendingInstalls) {
1383                                // Indicate service bind error
1384                                params.serviceError();
1385                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1386                                        System.identityHashCode(params));
1387                            }
1388                            mPendingInstalls.clear();
1389                        }
1390                    }
1391                    break;
1392                }
1393                case MCS_UNBIND: {
1394                    // If there is no actual work left, then time to unbind.
1395                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1396
1397                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1398                        if (mBound) {
1399                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1400
1401                            disconnectService();
1402                        }
1403                    } else if (mPendingInstalls.size() > 0) {
1404                        // There are more pending requests in queue.
1405                        // Just post MCS_BOUND message to trigger processing
1406                        // of next pending install.
1407                        mHandler.sendEmptyMessage(MCS_BOUND);
1408                    }
1409
1410                    break;
1411                }
1412                case MCS_GIVE_UP: {
1413                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1414                    HandlerParams params = mPendingInstalls.remove(0);
1415                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1416                            System.identityHashCode(params));
1417                    break;
1418                }
1419                case SEND_PENDING_BROADCAST: {
1420                    String packages[];
1421                    ArrayList<String> components[];
1422                    int size = 0;
1423                    int uids[];
1424                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1425                    synchronized (mPackages) {
1426                        if (mPendingBroadcasts == null) {
1427                            return;
1428                        }
1429                        size = mPendingBroadcasts.size();
1430                        if (size <= 0) {
1431                            // Nothing to be done. Just return
1432                            return;
1433                        }
1434                        packages = new String[size];
1435                        components = new ArrayList[size];
1436                        uids = new int[size];
1437                        int i = 0;  // filling out the above arrays
1438
1439                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1440                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1441                            Iterator<Map.Entry<String, ArrayList<String>>> it
1442                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1443                                            .entrySet().iterator();
1444                            while (it.hasNext() && i < size) {
1445                                Map.Entry<String, ArrayList<String>> ent = it.next();
1446                                packages[i] = ent.getKey();
1447                                components[i] = ent.getValue();
1448                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1449                                uids[i] = (ps != null)
1450                                        ? UserHandle.getUid(packageUserId, ps.appId)
1451                                        : -1;
1452                                i++;
1453                            }
1454                        }
1455                        size = i;
1456                        mPendingBroadcasts.clear();
1457                    }
1458                    // Send broadcasts
1459                    for (int i = 0; i < size; i++) {
1460                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1461                    }
1462                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1463                    break;
1464                }
1465                case START_CLEANING_PACKAGE: {
1466                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1467                    final String packageName = (String)msg.obj;
1468                    final int userId = msg.arg1;
1469                    final boolean andCode = msg.arg2 != 0;
1470                    synchronized (mPackages) {
1471                        if (userId == UserHandle.USER_ALL) {
1472                            int[] users = sUserManager.getUserIds();
1473                            for (int user : users) {
1474                                mSettings.addPackageToCleanLPw(
1475                                        new PackageCleanItem(user, packageName, andCode));
1476                            }
1477                        } else {
1478                            mSettings.addPackageToCleanLPw(
1479                                    new PackageCleanItem(userId, packageName, andCode));
1480                        }
1481                    }
1482                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1483                    startCleaningPackages();
1484                } break;
1485                case POST_INSTALL: {
1486                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1487
1488                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1489                    final boolean didRestore = (msg.arg2 != 0);
1490                    mRunningInstalls.delete(msg.arg1);
1491
1492                    if (data != null) {
1493                        InstallArgs args = data.args;
1494                        PackageInstalledInfo parentRes = data.res;
1495
1496                        final boolean grantPermissions = (args.installFlags
1497                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1498                        final boolean killApp = (args.installFlags
1499                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1500                        final String[] grantedPermissions = args.installGrantPermissions;
1501
1502                        // Handle the parent package
1503                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1504                                grantedPermissions, didRestore, args.installerPackageName,
1505                                args.observer);
1506
1507                        // Handle the child packages
1508                        final int childCount = (parentRes.addedChildPackages != null)
1509                                ? parentRes.addedChildPackages.size() : 0;
1510                        for (int i = 0; i < childCount; i++) {
1511                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1512                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1513                                    grantedPermissions, false, args.installerPackageName,
1514                                    args.observer);
1515                        }
1516
1517                        // Log tracing if needed
1518                        if (args.traceMethod != null) {
1519                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1520                                    args.traceCookie);
1521                        }
1522                    } else {
1523                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1524                    }
1525
1526                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1527                } break;
1528                case UPDATED_MEDIA_STATUS: {
1529                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1530                    boolean reportStatus = msg.arg1 == 1;
1531                    boolean doGc = msg.arg2 == 1;
1532                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1533                    if (doGc) {
1534                        // Force a gc to clear up stale containers.
1535                        Runtime.getRuntime().gc();
1536                    }
1537                    if (msg.obj != null) {
1538                        @SuppressWarnings("unchecked")
1539                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1540                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1541                        // Unload containers
1542                        unloadAllContainers(args);
1543                    }
1544                    if (reportStatus) {
1545                        try {
1546                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1547                                    "Invoking StorageManagerService call back");
1548                            PackageHelper.getStorageManager().finishMediaUpdate();
1549                        } catch (RemoteException e) {
1550                            Log.e(TAG, "StorageManagerService not running?");
1551                        }
1552                    }
1553                } break;
1554                case WRITE_SETTINGS: {
1555                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1556                    synchronized (mPackages) {
1557                        removeMessages(WRITE_SETTINGS);
1558                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1559                        mSettings.writeLPr();
1560                        mDirtyUsers.clear();
1561                    }
1562                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1563                } break;
1564                case WRITE_PACKAGE_RESTRICTIONS: {
1565                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1566                    synchronized (mPackages) {
1567                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1568                        for (int userId : mDirtyUsers) {
1569                            mSettings.writePackageRestrictionsLPr(userId);
1570                        }
1571                        mDirtyUsers.clear();
1572                    }
1573                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1574                } break;
1575                case WRITE_PACKAGE_LIST: {
1576                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1577                    synchronized (mPackages) {
1578                        removeMessages(WRITE_PACKAGE_LIST);
1579                        mSettings.writePackageListLPr(msg.arg1);
1580                    }
1581                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1582                } break;
1583                case CHECK_PENDING_VERIFICATION: {
1584                    final int verificationId = msg.arg1;
1585                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1586
1587                    if ((state != null) && !state.timeoutExtended()) {
1588                        final InstallArgs args = state.getInstallArgs();
1589                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1590
1591                        Slog.i(TAG, "Verification timed out for " + originUri);
1592                        mPendingVerification.remove(verificationId);
1593
1594                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1595
1596                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1597                            Slog.i(TAG, "Continuing with installation of " + originUri);
1598                            state.setVerifierResponse(Binder.getCallingUid(),
1599                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1600                            broadcastPackageVerified(verificationId, originUri,
1601                                    PackageManager.VERIFICATION_ALLOW,
1602                                    state.getInstallArgs().getUser());
1603                            try {
1604                                ret = args.copyApk(mContainerService, true);
1605                            } catch (RemoteException e) {
1606                                Slog.e(TAG, "Could not contact the ContainerService");
1607                            }
1608                        } else {
1609                            broadcastPackageVerified(verificationId, originUri,
1610                                    PackageManager.VERIFICATION_REJECT,
1611                                    state.getInstallArgs().getUser());
1612                        }
1613
1614                        Trace.asyncTraceEnd(
1615                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1616
1617                        processPendingInstall(args, ret);
1618                        mHandler.sendEmptyMessage(MCS_UNBIND);
1619                    }
1620                    break;
1621                }
1622                case PACKAGE_VERIFIED: {
1623                    final int verificationId = msg.arg1;
1624
1625                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1626                    if (state == null) {
1627                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1628                        break;
1629                    }
1630
1631                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1632
1633                    state.setVerifierResponse(response.callerUid, response.code);
1634
1635                    if (state.isVerificationComplete()) {
1636                        mPendingVerification.remove(verificationId);
1637
1638                        final InstallArgs args = state.getInstallArgs();
1639                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1640
1641                        int ret;
1642                        if (state.isInstallAllowed()) {
1643                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1644                            broadcastPackageVerified(verificationId, originUri,
1645                                    response.code, state.getInstallArgs().getUser());
1646                            try {
1647                                ret = args.copyApk(mContainerService, true);
1648                            } catch (RemoteException e) {
1649                                Slog.e(TAG, "Could not contact the ContainerService");
1650                            }
1651                        } else {
1652                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1653                        }
1654
1655                        Trace.asyncTraceEnd(
1656                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1657
1658                        processPendingInstall(args, ret);
1659                        mHandler.sendEmptyMessage(MCS_UNBIND);
1660                    }
1661
1662                    break;
1663                }
1664                case START_INTENT_FILTER_VERIFICATIONS: {
1665                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1666                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1667                            params.replacing, params.pkg);
1668                    break;
1669                }
1670                case INTENT_FILTER_VERIFIED: {
1671                    final int verificationId = msg.arg1;
1672
1673                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1674                            verificationId);
1675                    if (state == null) {
1676                        Slog.w(TAG, "Invalid IntentFilter verification token "
1677                                + verificationId + " received");
1678                        break;
1679                    }
1680
1681                    final int userId = state.getUserId();
1682
1683                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1684                            "Processing IntentFilter verification with token:"
1685                            + verificationId + " and userId:" + userId);
1686
1687                    final IntentFilterVerificationResponse response =
1688                            (IntentFilterVerificationResponse) msg.obj;
1689
1690                    state.setVerifierResponse(response.callerUid, response.code);
1691
1692                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1693                            "IntentFilter verification with token:" + verificationId
1694                            + " and userId:" + userId
1695                            + " is settings verifier response with response code:"
1696                            + response.code);
1697
1698                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1699                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1700                                + response.getFailedDomainsString());
1701                    }
1702
1703                    if (state.isVerificationComplete()) {
1704                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1705                    } else {
1706                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1707                                "IntentFilter verification with token:" + verificationId
1708                                + " was not said to be complete");
1709                    }
1710
1711                    break;
1712                }
1713                case EPHEMERAL_RESOLUTION_PHASE_TWO: {
1714                    EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext,
1715                            mEphemeralResolverConnection,
1716                            (EphemeralRequest) msg.obj,
1717                            mEphemeralInstallerActivity,
1718                            mHandler);
1719                }
1720            }
1721        }
1722    }
1723
1724    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1725            boolean killApp, String[] grantedPermissions,
1726            boolean launchedForRestore, String installerPackage,
1727            IPackageInstallObserver2 installObserver) {
1728        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1729            // Send the removed broadcasts
1730            if (res.removedInfo != null) {
1731                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1732            }
1733
1734            // Now that we successfully installed the package, grant runtime
1735            // permissions if requested before broadcasting the install. Also
1736            // for legacy apps in permission review mode we clear the permission
1737            // review flag which is used to emulate runtime permissions for
1738            // legacy apps.
1739            if (grantPermissions) {
1740                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1741            }
1742
1743            final boolean update = res.removedInfo != null
1744                    && res.removedInfo.removedPackage != null;
1745
1746            // If this is the first time we have child packages for a disabled privileged
1747            // app that had no children, we grant requested runtime permissions to the new
1748            // children if the parent on the system image had them already granted.
1749            if (res.pkg.parentPackage != null) {
1750                synchronized (mPackages) {
1751                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1752                }
1753            }
1754
1755            synchronized (mPackages) {
1756                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1757            }
1758
1759            final String packageName = res.pkg.applicationInfo.packageName;
1760
1761            // Determine the set of users who are adding this package for
1762            // the first time vs. those who are seeing an update.
1763            int[] firstUsers = EMPTY_INT_ARRAY;
1764            int[] updateUsers = EMPTY_INT_ARRAY;
1765            if (res.origUsers == null || res.origUsers.length == 0) {
1766                firstUsers = res.newUsers;
1767            } else {
1768                for (int newUser : res.newUsers) {
1769                    boolean isNew = true;
1770                    for (int origUser : res.origUsers) {
1771                        if (origUser == newUser) {
1772                            isNew = false;
1773                            break;
1774                        }
1775                    }
1776                    if (isNew) {
1777                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1778                    } else {
1779                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1780                    }
1781                }
1782            }
1783
1784            // Send installed broadcasts if the install/update is not ephemeral
1785            // and the package is not a static shared lib.
1786            if (!isEphemeral(res.pkg) && res.pkg.staticSharedLibName == null) {
1787                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1788
1789                // Send added for users that see the package for the first time
1790                // sendPackageAddedForNewUsers also deals with system apps
1791                int appId = UserHandle.getAppId(res.uid);
1792                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1793                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1794
1795                // Send added for users that don't see the package for the first time
1796                Bundle extras = new Bundle(1);
1797                extras.putInt(Intent.EXTRA_UID, res.uid);
1798                if (update) {
1799                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1800                }
1801                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1802                        extras, 0 /*flags*/, null /*targetPackage*/,
1803                        null /*finishedReceiver*/, updateUsers);
1804
1805                // Send replaced for users that don't see the package for the first time
1806                if (update) {
1807                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1808                            packageName, extras, 0 /*flags*/,
1809                            null /*targetPackage*/, null /*finishedReceiver*/,
1810                            updateUsers);
1811                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1812                            null /*package*/, null /*extras*/, 0 /*flags*/,
1813                            packageName /*targetPackage*/,
1814                            null /*finishedReceiver*/, updateUsers);
1815                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1816                    // First-install and we did a restore, so we're responsible for the
1817                    // first-launch broadcast.
1818                    if (DEBUG_BACKUP) {
1819                        Slog.i(TAG, "Post-restore of " + packageName
1820                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1821                    }
1822                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1823                }
1824
1825                // Send broadcast package appeared if forward locked/external for all users
1826                // treat asec-hosted packages like removable media on upgrade
1827                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1828                    if (DEBUG_INSTALL) {
1829                        Slog.i(TAG, "upgrading pkg " + res.pkg
1830                                + " is ASEC-hosted -> AVAILABLE");
1831                    }
1832                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1833                    ArrayList<String> pkgList = new ArrayList<>(1);
1834                    pkgList.add(packageName);
1835                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1836                }
1837            }
1838
1839            // Work that needs to happen on first install within each user
1840            if (firstUsers != null && firstUsers.length > 0) {
1841                synchronized (mPackages) {
1842                    for (int userId : firstUsers) {
1843                        // If this app is a browser and it's newly-installed for some
1844                        // users, clear any default-browser state in those users. The
1845                        // app's nature doesn't depend on the user, so we can just check
1846                        // its browser nature in any user and generalize.
1847                        if (packageIsBrowser(packageName, userId)) {
1848                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1849                        }
1850
1851                        // We may also need to apply pending (restored) runtime
1852                        // permission grants within these users.
1853                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1854                    }
1855                }
1856            }
1857
1858            // Log current value of "unknown sources" setting
1859            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1860                    getUnknownSourcesSettings());
1861
1862            // Force a gc to clear up things
1863            Runtime.getRuntime().gc();
1864
1865            // Remove the replaced package's older resources safely now
1866            // We delete after a gc for applications  on sdcard.
1867            if (res.removedInfo != null && res.removedInfo.args != null) {
1868                synchronized (mInstallLock) {
1869                    res.removedInfo.args.doPostDeleteLI(true);
1870                }
1871            }
1872
1873            if (!isEphemeral(res.pkg)) {
1874                // Notify DexManager that the package was installed for new users.
1875                // The updated users should already be indexed and the package code paths
1876                // should not change.
1877                // Don't notify the manager for ephemeral apps as they are not expected to
1878                // survive long enough to benefit of background optimizations.
1879                for (int userId : firstUsers) {
1880                    PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
1881                    mDexManager.notifyPackageInstalled(info, userId);
1882                }
1883            }
1884        }
1885
1886        // If someone is watching installs - notify them
1887        if (installObserver != null) {
1888            try {
1889                Bundle extras = extrasForInstallResult(res);
1890                installObserver.onPackageInstalled(res.name, res.returnCode,
1891                        res.returnMsg, extras);
1892            } catch (RemoteException e) {
1893                Slog.i(TAG, "Observer no longer exists.");
1894            }
1895        }
1896    }
1897
1898    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1899            PackageParser.Package pkg) {
1900        if (pkg.parentPackage == null) {
1901            return;
1902        }
1903        if (pkg.requestedPermissions == null) {
1904            return;
1905        }
1906        final PackageSetting disabledSysParentPs = mSettings
1907                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1908        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1909                || !disabledSysParentPs.isPrivileged()
1910                || (disabledSysParentPs.childPackageNames != null
1911                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1912            return;
1913        }
1914        final int[] allUserIds = sUserManager.getUserIds();
1915        final int permCount = pkg.requestedPermissions.size();
1916        for (int i = 0; i < permCount; i++) {
1917            String permission = pkg.requestedPermissions.get(i);
1918            BasePermission bp = mSettings.mPermissions.get(permission);
1919            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1920                continue;
1921            }
1922            for (int userId : allUserIds) {
1923                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1924                        permission, userId)) {
1925                    grantRuntimePermission(pkg.packageName, permission, userId);
1926                }
1927            }
1928        }
1929    }
1930
1931    private StorageEventListener mStorageListener = new StorageEventListener() {
1932        @Override
1933        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1934            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1935                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1936                    final String volumeUuid = vol.getFsUuid();
1937
1938                    // Clean up any users or apps that were removed or recreated
1939                    // while this volume was missing
1940                    reconcileUsers(volumeUuid);
1941                    reconcileApps(volumeUuid);
1942
1943                    // Clean up any install sessions that expired or were
1944                    // cancelled while this volume was missing
1945                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1946
1947                    loadPrivatePackages(vol);
1948
1949                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1950                    unloadPrivatePackages(vol);
1951                }
1952            }
1953
1954            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1955                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1956                    updateExternalMediaStatus(true, false);
1957                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1958                    updateExternalMediaStatus(false, false);
1959                }
1960            }
1961        }
1962
1963        @Override
1964        public void onVolumeForgotten(String fsUuid) {
1965            if (TextUtils.isEmpty(fsUuid)) {
1966                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1967                return;
1968            }
1969
1970            // Remove any apps installed on the forgotten volume
1971            synchronized (mPackages) {
1972                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1973                for (PackageSetting ps : packages) {
1974                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1975                    deletePackageVersioned(new VersionedPackage(ps.name,
1976                            PackageManager.VERSION_CODE_HIGHEST),
1977                            new LegacyPackageDeleteObserver(null).getBinder(),
1978                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1979                    // Try very hard to release any references to this package
1980                    // so we don't risk the system server being killed due to
1981                    // open FDs
1982                    AttributeCache.instance().removePackage(ps.name);
1983                }
1984
1985                mSettings.onVolumeForgotten(fsUuid);
1986                mSettings.writeLPr();
1987            }
1988        }
1989    };
1990
1991    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1992            String[] grantedPermissions) {
1993        for (int userId : userIds) {
1994            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1995        }
1996    }
1997
1998    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1999            String[] grantedPermissions) {
2000        SettingBase sb = (SettingBase) pkg.mExtras;
2001        if (sb == null) {
2002            return;
2003        }
2004
2005        PermissionsState permissionsState = sb.getPermissionsState();
2006
2007        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2008                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2009
2010        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2011                >= Build.VERSION_CODES.M;
2012
2013        for (String permission : pkg.requestedPermissions) {
2014            final BasePermission bp;
2015            synchronized (mPackages) {
2016                bp = mSettings.mPermissions.get(permission);
2017            }
2018            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2019                    && (grantedPermissions == null
2020                           || ArrayUtils.contains(grantedPermissions, permission))) {
2021                final int flags = permissionsState.getPermissionFlags(permission, userId);
2022                if (supportsRuntimePermissions) {
2023                    // Installer cannot change immutable permissions.
2024                    if ((flags & immutableFlags) == 0) {
2025                        grantRuntimePermission(pkg.packageName, permission, userId);
2026                    }
2027                } else if (mPermissionReviewRequired) {
2028                    // In permission review mode we clear the review flag when we
2029                    // are asked to install the app with all permissions granted.
2030                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2031                        updatePermissionFlags(permission, pkg.packageName,
2032                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2033                    }
2034                }
2035            }
2036        }
2037    }
2038
2039    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2040        Bundle extras = null;
2041        switch (res.returnCode) {
2042            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2043                extras = new Bundle();
2044                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2045                        res.origPermission);
2046                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2047                        res.origPackage);
2048                break;
2049            }
2050            case PackageManager.INSTALL_SUCCEEDED: {
2051                extras = new Bundle();
2052                extras.putBoolean(Intent.EXTRA_REPLACING,
2053                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2054                break;
2055            }
2056        }
2057        return extras;
2058    }
2059
2060    void scheduleWriteSettingsLocked() {
2061        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2062            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2063        }
2064    }
2065
2066    void scheduleWritePackageListLocked(int userId) {
2067        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2068            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2069            msg.arg1 = userId;
2070            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2071        }
2072    }
2073
2074    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2075        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2076        scheduleWritePackageRestrictionsLocked(userId);
2077    }
2078
2079    void scheduleWritePackageRestrictionsLocked(int userId) {
2080        final int[] userIds = (userId == UserHandle.USER_ALL)
2081                ? sUserManager.getUserIds() : new int[]{userId};
2082        for (int nextUserId : userIds) {
2083            if (!sUserManager.exists(nextUserId)) return;
2084            mDirtyUsers.add(nextUserId);
2085            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2086                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2087            }
2088        }
2089    }
2090
2091    public static PackageManagerService main(Context context, Installer installer,
2092            boolean factoryTest, boolean onlyCore) {
2093        // Self-check for initial settings.
2094        PackageManagerServiceCompilerMapping.checkProperties();
2095
2096        PackageManagerService m = new PackageManagerService(context, installer,
2097                factoryTest, onlyCore);
2098        m.enableSystemUserPackages();
2099        ServiceManager.addService("package", m);
2100        return m;
2101    }
2102
2103    private void enableSystemUserPackages() {
2104        if (!UserManager.isSplitSystemUser()) {
2105            return;
2106        }
2107        // For system user, enable apps based on the following conditions:
2108        // - app is whitelisted or belong to one of these groups:
2109        //   -- system app which has no launcher icons
2110        //   -- system app which has INTERACT_ACROSS_USERS permission
2111        //   -- system IME app
2112        // - app is not in the blacklist
2113        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2114        Set<String> enableApps = new ArraySet<>();
2115        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2116                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2117                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2118        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2119        enableApps.addAll(wlApps);
2120        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2121                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2122        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2123        enableApps.removeAll(blApps);
2124        Log.i(TAG, "Applications installed for system user: " + enableApps);
2125        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2126                UserHandle.SYSTEM);
2127        final int allAppsSize = allAps.size();
2128        synchronized (mPackages) {
2129            for (int i = 0; i < allAppsSize; i++) {
2130                String pName = allAps.get(i);
2131                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2132                // Should not happen, but we shouldn't be failing if it does
2133                if (pkgSetting == null) {
2134                    continue;
2135                }
2136                boolean install = enableApps.contains(pName);
2137                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2138                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2139                            + " for system user");
2140                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2141                }
2142            }
2143        }
2144    }
2145
2146    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2147        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2148                Context.DISPLAY_SERVICE);
2149        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2150    }
2151
2152    /**
2153     * Requests that files preopted on a secondary system partition be copied to the data partition
2154     * if possible.  Note that the actual copying of the files is accomplished by init for security
2155     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2156     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2157     */
2158    private static void requestCopyPreoptedFiles() {
2159        final int WAIT_TIME_MS = 100;
2160        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2161        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2162            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2163            // We will wait for up to 100 seconds.
2164            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2165            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2166                try {
2167                    Thread.sleep(WAIT_TIME_MS);
2168                } catch (InterruptedException e) {
2169                    // Do nothing
2170                }
2171                if (SystemClock.uptimeMillis() > timeEnd) {
2172                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2173                    Slog.wtf(TAG, "cppreopt did not finish!");
2174                    break;
2175                }
2176            }
2177        }
2178    }
2179
2180    public PackageManagerService(Context context, Installer installer,
2181            boolean factoryTest, boolean onlyCore) {
2182        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2183        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2184                SystemClock.uptimeMillis());
2185
2186        if (mSdkVersion <= 0) {
2187            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2188        }
2189
2190        mContext = context;
2191
2192        mPermissionReviewRequired = context.getResources().getBoolean(
2193                R.bool.config_permissionReviewRequired);
2194
2195        mFactoryTest = factoryTest;
2196        mOnlyCore = onlyCore;
2197        mMetrics = new DisplayMetrics();
2198        mSettings = new Settings(mPackages);
2199        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2200                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2201        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2202                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2203        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2204                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2205        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2206                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2207        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2208                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2209        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2210                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2211
2212        String separateProcesses = SystemProperties.get("debug.separate_processes");
2213        if (separateProcesses != null && separateProcesses.length() > 0) {
2214            if ("*".equals(separateProcesses)) {
2215                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2216                mSeparateProcesses = null;
2217                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2218            } else {
2219                mDefParseFlags = 0;
2220                mSeparateProcesses = separateProcesses.split(",");
2221                Slog.w(TAG, "Running with debug.separate_processes: "
2222                        + separateProcesses);
2223            }
2224        } else {
2225            mDefParseFlags = 0;
2226            mSeparateProcesses = null;
2227        }
2228
2229        mInstaller = installer;
2230        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2231                "*dexopt*");
2232        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2233        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2234
2235        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2236                FgThread.get().getLooper());
2237
2238        getDefaultDisplayMetrics(context, mMetrics);
2239
2240        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2241        SystemConfig systemConfig = SystemConfig.getInstance();
2242        mGlobalGids = systemConfig.getGlobalGids();
2243        mSystemPermissions = systemConfig.getSystemPermissions();
2244        mAvailableFeatures = systemConfig.getAvailableFeatures();
2245        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2246
2247        mProtectedPackages = new ProtectedPackages(mContext);
2248
2249        synchronized (mInstallLock) {
2250        // writer
2251        synchronized (mPackages) {
2252            mHandlerThread = new ServiceThread(TAG,
2253                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2254            mHandlerThread.start();
2255            mHandler = new PackageHandler(mHandlerThread.getLooper());
2256            mProcessLoggingHandler = new ProcessLoggingHandler();
2257            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2258
2259            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2260            mInstantAppRegistry = new InstantAppRegistry(this);
2261
2262            File dataDir = Environment.getDataDirectory();
2263            mAppInstallDir = new File(dataDir, "app");
2264            mAppLib32InstallDir = new File(dataDir, "app-lib");
2265            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2266            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2267            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2268            mUserDataPreparer = new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore);
2269            sUserManager = new UserManagerService(context, this, mUserDataPreparer, mPackages);
2270
2271            // Propagate permission configuration in to package manager.
2272            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2273                    = systemConfig.getPermissions();
2274            for (int i=0; i<permConfig.size(); i++) {
2275                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2276                BasePermission bp = mSettings.mPermissions.get(perm.name);
2277                if (bp == null) {
2278                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2279                    mSettings.mPermissions.put(perm.name, bp);
2280                }
2281                if (perm.gids != null) {
2282                    bp.setGids(perm.gids, perm.perUser);
2283                }
2284            }
2285
2286            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2287            final int builtInLibCount = libConfig.size();
2288            for (int i = 0; i < builtInLibCount; i++) {
2289                String name = libConfig.keyAt(i);
2290                String path = libConfig.valueAt(i);
2291                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2292                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2293            }
2294
2295            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2296
2297            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2298            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2299            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2300
2301            // Clean up orphaned packages for which the code path doesn't exist
2302            // and they are an update to a system app - caused by bug/32321269
2303            final int packageSettingCount = mSettings.mPackages.size();
2304            for (int i = packageSettingCount - 1; i >= 0; i--) {
2305                PackageSetting ps = mSettings.mPackages.valueAt(i);
2306                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2307                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2308                    mSettings.mPackages.removeAt(i);
2309                    mSettings.enableSystemPackageLPw(ps.name);
2310                }
2311            }
2312
2313            if (mFirstBoot) {
2314                requestCopyPreoptedFiles();
2315            }
2316
2317            String customResolverActivity = Resources.getSystem().getString(
2318                    R.string.config_customResolverActivity);
2319            if (TextUtils.isEmpty(customResolverActivity)) {
2320                customResolverActivity = null;
2321            } else {
2322                mCustomResolverComponentName = ComponentName.unflattenFromString(
2323                        customResolverActivity);
2324            }
2325
2326            long startTime = SystemClock.uptimeMillis();
2327
2328            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2329                    startTime);
2330
2331            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2332            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2333
2334            if (bootClassPath == null) {
2335                Slog.w(TAG, "No BOOTCLASSPATH found!");
2336            }
2337
2338            if (systemServerClassPath == null) {
2339                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2340            }
2341
2342            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2343            final String[] dexCodeInstructionSets =
2344                    getDexCodeInstructionSets(
2345                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2346
2347            /**
2348             * Ensure all external libraries have had dexopt run on them.
2349             */
2350            if (mSharedLibraries.size() > 0) {
2351                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2352                // NOTE: For now, we're compiling these system "shared libraries"
2353                // (and framework jars) into all available architectures. It's possible
2354                // to compile them only when we come across an app that uses them (there's
2355                // already logic for that in scanPackageLI) but that adds some complexity.
2356                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2357                    final int libCount = mSharedLibraries.size();
2358                    for (int i = 0; i < libCount; i++) {
2359                        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
2360                        final int versionCount = versionedLib.size();
2361                        for (int j = 0; j < versionCount; j++) {
2362                            SharedLibraryEntry libEntry = versionedLib.valueAt(j);
2363                            final String libPath = libEntry.path != null
2364                                    ? libEntry.path : libEntry.apk;
2365                            if (libPath == null) {
2366                                continue;
2367                            }
2368                            try {
2369                                // Shared libraries do not have profiles so we perform a full
2370                                // AOT compilation (if needed).
2371                                int dexoptNeeded = DexFile.getDexOptNeeded(
2372                                        libPath, dexCodeInstructionSet,
2373                                        getCompilerFilterForReason(REASON_SHARED_APK),
2374                                        false /* newProfile */);
2375                                if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2376                                    mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*",
2377                                            dexCodeInstructionSet, dexoptNeeded, null,
2378                                            DEXOPT_PUBLIC,
2379                                            getCompilerFilterForReason(REASON_SHARED_APK),
2380                                            StorageManager.UUID_PRIVATE_INTERNAL,
2381                                            SKIP_SHARED_LIBRARY_CHECK);
2382                                }
2383                            } catch (FileNotFoundException e) {
2384                                Slog.w(TAG, "Library not found: " + libPath);
2385                            } catch (IOException | InstallerException e) {
2386                                Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? "
2387                                        + e.getMessage());
2388                            }
2389                        }
2390                    }
2391                }
2392                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2393            }
2394
2395            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2396
2397            final VersionInfo ver = mSettings.getInternalVersion();
2398            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2399
2400            // when upgrading from pre-M, promote system app permissions from install to runtime
2401            mPromoteSystemApps =
2402                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2403
2404            // When upgrading from pre-N, we need to handle package extraction like first boot,
2405            // as there is no profiling data available.
2406            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2407
2408            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2409
2410            // save off the names of pre-existing system packages prior to scanning; we don't
2411            // want to automatically grant runtime permissions for new system apps
2412            if (mPromoteSystemApps) {
2413                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2414                while (pkgSettingIter.hasNext()) {
2415                    PackageSetting ps = pkgSettingIter.next();
2416                    if (isSystemApp(ps)) {
2417                        mExistingSystemPackages.add(ps.name);
2418                    }
2419                }
2420            }
2421
2422            mCacheDir = preparePackageParserCache(mIsUpgrade);
2423
2424            // Set flag to monitor and not change apk file paths when
2425            // scanning install directories.
2426            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2427
2428            if (mIsUpgrade || mFirstBoot) {
2429                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2430            }
2431
2432            // Collect vendor overlay packages. (Do this before scanning any apps.)
2433            // For security and version matching reason, only consider
2434            // overlay packages if they reside in the right directory.
2435            String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY);
2436            if (overlayThemeDir.isEmpty()) {
2437                overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY);
2438            }
2439            if (!overlayThemeDir.isEmpty()) {
2440                scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags
2441                        | PackageParser.PARSE_IS_SYSTEM
2442                        | PackageParser.PARSE_IS_SYSTEM_DIR
2443                        | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2444            }
2445            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2446                    | PackageParser.PARSE_IS_SYSTEM
2447                    | PackageParser.PARSE_IS_SYSTEM_DIR
2448                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2449
2450            // Find base frameworks (resource packages without code).
2451            scanDirTracedLI(frameworkDir, mDefParseFlags
2452                    | PackageParser.PARSE_IS_SYSTEM
2453                    | PackageParser.PARSE_IS_SYSTEM_DIR
2454                    | PackageParser.PARSE_IS_PRIVILEGED,
2455                    scanFlags | SCAN_NO_DEX, 0);
2456
2457            // Collected privileged system packages.
2458            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2459            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2460                    | PackageParser.PARSE_IS_SYSTEM
2461                    | PackageParser.PARSE_IS_SYSTEM_DIR
2462                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2463
2464            // Collect ordinary system packages.
2465            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2466            scanDirTracedLI(systemAppDir, mDefParseFlags
2467                    | PackageParser.PARSE_IS_SYSTEM
2468                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2469
2470            // Collect all vendor packages.
2471            File vendorAppDir = new File("/vendor/app");
2472            try {
2473                vendorAppDir = vendorAppDir.getCanonicalFile();
2474            } catch (IOException e) {
2475                // failed to look up canonical path, continue with original one
2476            }
2477            scanDirTracedLI(vendorAppDir, mDefParseFlags
2478                    | PackageParser.PARSE_IS_SYSTEM
2479                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2480
2481            // Collect all OEM packages.
2482            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2483            scanDirTracedLI(oemAppDir, mDefParseFlags
2484                    | PackageParser.PARSE_IS_SYSTEM
2485                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2486
2487            // Prune any system packages that no longer exist.
2488            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2489            if (!mOnlyCore) {
2490                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2491                while (psit.hasNext()) {
2492                    PackageSetting ps = psit.next();
2493
2494                    /*
2495                     * If this is not a system app, it can't be a
2496                     * disable system app.
2497                     */
2498                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2499                        continue;
2500                    }
2501
2502                    /*
2503                     * If the package is scanned, it's not erased.
2504                     */
2505                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2506                    if (scannedPkg != null) {
2507                        /*
2508                         * If the system app is both scanned and in the
2509                         * disabled packages list, then it must have been
2510                         * added via OTA. Remove it from the currently
2511                         * scanned package so the previously user-installed
2512                         * application can be scanned.
2513                         */
2514                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2515                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2516                                    + ps.name + "; removing system app.  Last known codePath="
2517                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2518                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2519                                    + scannedPkg.mVersionCode);
2520                            removePackageLI(scannedPkg, true);
2521                            mExpectingBetter.put(ps.name, ps.codePath);
2522                        }
2523
2524                        continue;
2525                    }
2526
2527                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2528                        psit.remove();
2529                        logCriticalInfo(Log.WARN, "System package " + ps.name
2530                                + " no longer exists; it's data will be wiped");
2531                        // Actual deletion of code and data will be handled by later
2532                        // reconciliation step
2533                    } else {
2534                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2535                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2536                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2537                        }
2538                    }
2539                }
2540            }
2541
2542            //look for any incomplete package installations
2543            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2544            for (int i = 0; i < deletePkgsList.size(); i++) {
2545                // Actual deletion of code and data will be handled by later
2546                // reconciliation step
2547                final String packageName = deletePkgsList.get(i).name;
2548                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2549                synchronized (mPackages) {
2550                    mSettings.removePackageLPw(packageName);
2551                }
2552            }
2553
2554            //delete tmp files
2555            deleteTempPackageFiles();
2556
2557            // Remove any shared userIDs that have no associated packages
2558            mSettings.pruneSharedUsersLPw();
2559
2560            if (!mOnlyCore) {
2561                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2562                        SystemClock.uptimeMillis());
2563                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2564
2565                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2566                        | PackageParser.PARSE_FORWARD_LOCK,
2567                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2568
2569                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2570                        | PackageParser.PARSE_IS_EPHEMERAL,
2571                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2572
2573                /**
2574                 * Remove disable package settings for any updated system
2575                 * apps that were removed via an OTA. If they're not a
2576                 * previously-updated app, remove them completely.
2577                 * Otherwise, just revoke their system-level permissions.
2578                 */
2579                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2580                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2581                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2582
2583                    String msg;
2584                    if (deletedPkg == null) {
2585                        msg = "Updated system package " + deletedAppName
2586                                + " no longer exists; it's data will be wiped";
2587                        // Actual deletion of code and data will be handled by later
2588                        // reconciliation step
2589                    } else {
2590                        msg = "Updated system app + " + deletedAppName
2591                                + " no longer present; removing system privileges for "
2592                                + deletedAppName;
2593
2594                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2595
2596                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2597                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2598                    }
2599                    logCriticalInfo(Log.WARN, msg);
2600                }
2601
2602                /**
2603                 * Make sure all system apps that we expected to appear on
2604                 * the userdata partition actually showed up. If they never
2605                 * appeared, crawl back and revive the system version.
2606                 */
2607                for (int i = 0; i < mExpectingBetter.size(); i++) {
2608                    final String packageName = mExpectingBetter.keyAt(i);
2609                    if (!mPackages.containsKey(packageName)) {
2610                        final File scanFile = mExpectingBetter.valueAt(i);
2611
2612                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2613                                + " but never showed up; reverting to system");
2614
2615                        int reparseFlags = mDefParseFlags;
2616                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2617                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2618                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2619                                    | PackageParser.PARSE_IS_PRIVILEGED;
2620                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2621                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2622                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2623                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2624                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2625                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2626                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2627                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2628                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2629                        } else {
2630                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2631                            continue;
2632                        }
2633
2634                        mSettings.enableSystemPackageLPw(packageName);
2635
2636                        try {
2637                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2638                        } catch (PackageManagerException e) {
2639                            Slog.e(TAG, "Failed to parse original system package: "
2640                                    + e.getMessage());
2641                        }
2642                    }
2643                }
2644            }
2645            mExpectingBetter.clear();
2646
2647            // Resolve the storage manager.
2648            mStorageManagerPackage = getStorageManagerPackageName();
2649
2650            // Resolve protected action filters. Only the setup wizard is allowed to
2651            // have a high priority filter for these actions.
2652            mSetupWizardPackage = getSetupWizardPackageName();
2653            if (mProtectedFilters.size() > 0) {
2654                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2655                    Slog.i(TAG, "No setup wizard;"
2656                        + " All protected intents capped to priority 0");
2657                }
2658                for (ActivityIntentInfo filter : mProtectedFilters) {
2659                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2660                        if (DEBUG_FILTERS) {
2661                            Slog.i(TAG, "Found setup wizard;"
2662                                + " allow priority " + filter.getPriority() + ";"
2663                                + " package: " + filter.activity.info.packageName
2664                                + " activity: " + filter.activity.className
2665                                + " priority: " + filter.getPriority());
2666                        }
2667                        // skip setup wizard; allow it to keep the high priority filter
2668                        continue;
2669                    }
2670                    Slog.w(TAG, "Protected action; cap priority to 0;"
2671                            + " package: " + filter.activity.info.packageName
2672                            + " activity: " + filter.activity.className
2673                            + " origPrio: " + filter.getPriority());
2674                    filter.setPriority(0);
2675                }
2676            }
2677            mDeferProtectedFilters = false;
2678            mProtectedFilters.clear();
2679
2680            // Now that we know all of the shared libraries, update all clients to have
2681            // the correct library paths.
2682            updateAllSharedLibrariesLPw(null);
2683
2684            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2685                // NOTE: We ignore potential failures here during a system scan (like
2686                // the rest of the commands above) because there's precious little we
2687                // can do about it. A settings error is reported, though.
2688                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2689            }
2690
2691            // Now that we know all the packages we are keeping,
2692            // read and update their last usage times.
2693            mPackageUsage.read(mPackages);
2694            mCompilerStats.read();
2695
2696            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2697                    SystemClock.uptimeMillis());
2698            Slog.i(TAG, "Time to scan packages: "
2699                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2700                    + " seconds");
2701
2702            // If the platform SDK has changed since the last time we booted,
2703            // we need to re-grant app permission to catch any new ones that
2704            // appear.  This is really a hack, and means that apps can in some
2705            // cases get permissions that the user didn't initially explicitly
2706            // allow...  it would be nice to have some better way to handle
2707            // this situation.
2708            int updateFlags = UPDATE_PERMISSIONS_ALL;
2709            if (ver.sdkVersion != mSdkVersion) {
2710                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2711                        + mSdkVersion + "; regranting permissions for internal storage");
2712                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2713            }
2714            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2715            ver.sdkVersion = mSdkVersion;
2716
2717            // If this is the first boot or an update from pre-M, and it is a normal
2718            // boot, then we need to initialize the default preferred apps across
2719            // all defined users.
2720            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2721                for (UserInfo user : sUserManager.getUsers(true)) {
2722                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2723                    applyFactoryDefaultBrowserLPw(user.id);
2724                    primeDomainVerificationsLPw(user.id);
2725                }
2726            }
2727
2728            // Prepare storage for system user really early during boot,
2729            // since core system apps like SettingsProvider and SystemUI
2730            // can't wait for user to start
2731            final int storageFlags;
2732            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2733                storageFlags = StorageManager.FLAG_STORAGE_DE;
2734            } else {
2735                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2736            }
2737            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2738                    storageFlags, true /* migrateAppData */);
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            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2774            // early on (before the package manager declares itself as early) because other
2775            // components in the system server might ask for package contexts for these apps.
2776            //
2777            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2778            // (i.e, that the data partition is unavailable).
2779            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2780                long start = System.nanoTime();
2781                List<PackageParser.Package> coreApps = new ArrayList<>();
2782                for (PackageParser.Package pkg : mPackages.values()) {
2783                    if (pkg.coreApp) {
2784                        coreApps.add(pkg);
2785                    }
2786                }
2787
2788                int[] stats = performDexOptUpgrade(coreApps, false,
2789                        getCompilerFilterForReason(REASON_CORE_APP));
2790
2791                final int elapsedTimeSeconds =
2792                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2793                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2794
2795                if (DEBUG_DEXOPT) {
2796                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2797                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2798                }
2799
2800
2801                // TODO: Should we log these stats to tron too ?
2802                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2803                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2804                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2805                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2806            }
2807
2808            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2809                    SystemClock.uptimeMillis());
2810
2811            if (!mOnlyCore) {
2812                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2813                mRequiredInstallerPackage = getRequiredInstallerLPr();
2814                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2815                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2816                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2817                        mIntentFilterVerifierComponent);
2818                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2819                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2820                        SharedLibraryInfo.VERSION_UNDEFINED);
2821                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2822                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2823                        SharedLibraryInfo.VERSION_UNDEFINED);
2824            } else {
2825                mRequiredVerifierPackage = null;
2826                mRequiredInstallerPackage = null;
2827                mRequiredUninstallerPackage = null;
2828                mIntentFilterVerifierComponent = null;
2829                mIntentFilterVerifier = null;
2830                mServicesSystemSharedLibraryPackageName = null;
2831                mSharedSystemSharedLibraryPackageName = null;
2832            }
2833
2834            mInstallerService = new PackageInstallerService(context, this);
2835
2836            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2837            if (ephemeralResolverComponent != null) {
2838                if (DEBUG_EPHEMERAL) {
2839                    Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent);
2840                }
2841                mEphemeralResolverConnection =
2842                        new EphemeralResolverConnection(mContext, ephemeralResolverComponent);
2843            } else {
2844                mEphemeralResolverConnection = null;
2845            }
2846            mEphemeralInstallerComponent = getEphemeralInstallerLPr();
2847            if (mEphemeralInstallerComponent != null) {
2848                if (DEBUG_EPHEMERAL) {
2849                    Slog.i(TAG, "Ephemeral installer: " + mEphemeralInstallerComponent);
2850                }
2851                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2852            }
2853
2854            // Read and update the usage of dex files.
2855            // Do this at the end of PM init so that all the packages have their
2856            // data directory reconciled.
2857            // At this point we know the code paths of the packages, so we can validate
2858            // the disk file and build the internal cache.
2859            // The usage file is expected to be small so loading and verifying it
2860            // should take a fairly small time compare to the other activities (e.g. package
2861            // scanning).
2862            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2863            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2864            for (int userId : currentUserIds) {
2865                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2866            }
2867            mDexManager.load(userPackages);
2868        } // synchronized (mPackages)
2869        } // synchronized (mInstallLock)
2870
2871        // Now after opening every single application zip, make sure they
2872        // are all flushed.  Not really needed, but keeps things nice and
2873        // tidy.
2874        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2875        Runtime.getRuntime().gc();
2876        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2877
2878        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2879        FallbackCategoryProvider.loadFallbacks();
2880        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2881
2882        // The initial scanning above does many calls into installd while
2883        // holding the mPackages lock, but we're mostly interested in yelling
2884        // once we have a booted system.
2885        mInstaller.setWarnIfHeld(mPackages);
2886
2887        // Expose private service for system components to use.
2888        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2889        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2890    }
2891
2892    private static File preparePackageParserCache(boolean isUpgrade) {
2893        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2894            return null;
2895        }
2896
2897        // Disable package parsing on eng builds to allow for faster incremental development.
2898        if ("eng".equals(Build.TYPE)) {
2899            return null;
2900        }
2901
2902        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2903            Slog.i(TAG, "Disabling package parser cache due to system property.");
2904            return null;
2905        }
2906
2907        // The base directory for the package parser cache lives under /data/system/.
2908        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2909                "package_cache");
2910        if (cacheBaseDir == null) {
2911            return null;
2912        }
2913
2914        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2915        // This also serves to "GC" unused entries when the package cache version changes (which
2916        // can only happen during upgrades).
2917        if (isUpgrade) {
2918            FileUtils.deleteContents(cacheBaseDir);
2919        }
2920
2921
2922        // Return the versioned package cache directory. This is something like
2923        // "/data/system/package_cache/1"
2924        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2925
2926        // The following is a workaround to aid development on non-numbered userdebug
2927        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2928        // the system partition is newer.
2929        //
2930        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2931        // that starts with "eng." to signify that this is an engineering build and not
2932        // destined for release.
2933        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2934            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2935
2936            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2937            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2938            // in general and should not be used for production changes. In this specific case,
2939            // we know that they will work.
2940            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2941            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
2942                FileUtils.deleteContents(cacheBaseDir);
2943                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2944            }
2945        }
2946
2947        return cacheDir;
2948    }
2949
2950    @Override
2951    public boolean isFirstBoot() {
2952        return mFirstBoot;
2953    }
2954
2955    @Override
2956    public boolean isOnlyCoreApps() {
2957        return mOnlyCore;
2958    }
2959
2960    @Override
2961    public boolean isUpgrade() {
2962        return mIsUpgrade;
2963    }
2964
2965    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2966        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2967
2968        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2969                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2970                UserHandle.USER_SYSTEM);
2971        if (matches.size() == 1) {
2972            return matches.get(0).getComponentInfo().packageName;
2973        } else if (matches.size() == 0) {
2974            Log.e(TAG, "There should probably be a verifier, but, none were found");
2975            return null;
2976        }
2977        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2978    }
2979
2980    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
2981        synchronized (mPackages) {
2982            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
2983            if (libraryEntry == null) {
2984                throw new IllegalStateException("Missing required shared library:" + name);
2985            }
2986            return libraryEntry.apk;
2987        }
2988    }
2989
2990    private @NonNull String getRequiredInstallerLPr() {
2991        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2992        intent.addCategory(Intent.CATEGORY_DEFAULT);
2993        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2994
2995        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2996                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2997                UserHandle.USER_SYSTEM);
2998        if (matches.size() == 1) {
2999            ResolveInfo resolveInfo = matches.get(0);
3000            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3001                throw new RuntimeException("The installer must be a privileged app");
3002            }
3003            return matches.get(0).getComponentInfo().packageName;
3004        } else {
3005            throw new RuntimeException("There must be exactly one installer; found " + matches);
3006        }
3007    }
3008
3009    private @NonNull String getRequiredUninstallerLPr() {
3010        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3011        intent.addCategory(Intent.CATEGORY_DEFAULT);
3012        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3013
3014        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3015                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3016                UserHandle.USER_SYSTEM);
3017        if (resolveInfo == null ||
3018                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3019            throw new RuntimeException("There must be exactly one uninstaller; found "
3020                    + resolveInfo);
3021        }
3022        return resolveInfo.getComponentInfo().packageName;
3023    }
3024
3025    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3026        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3027
3028        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3029                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3030                UserHandle.USER_SYSTEM);
3031        ResolveInfo best = null;
3032        final int N = matches.size();
3033        for (int i = 0; i < N; i++) {
3034            final ResolveInfo cur = matches.get(i);
3035            final String packageName = cur.getComponentInfo().packageName;
3036            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3037                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3038                continue;
3039            }
3040
3041            if (best == null || cur.priority > best.priority) {
3042                best = cur;
3043            }
3044        }
3045
3046        if (best != null) {
3047            return best.getComponentInfo().getComponentName();
3048        } else {
3049            throw new RuntimeException("There must be at least one intent filter verifier");
3050        }
3051    }
3052
3053    private @Nullable ComponentName getEphemeralResolverLPr() {
3054        final String[] packageArray =
3055                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3056        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3057            if (DEBUG_EPHEMERAL) {
3058                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3059            }
3060            return null;
3061        }
3062
3063        final int resolveFlags =
3064                MATCH_DIRECT_BOOT_AWARE
3065                | MATCH_DIRECT_BOOT_UNAWARE
3066                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3067        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
3068        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3069                resolveFlags, UserHandle.USER_SYSTEM);
3070
3071        final int N = resolvers.size();
3072        if (N == 0) {
3073            if (DEBUG_EPHEMERAL) {
3074                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3075            }
3076            return null;
3077        }
3078
3079        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3080        for (int i = 0; i < N; i++) {
3081            final ResolveInfo info = resolvers.get(i);
3082
3083            if (info.serviceInfo == null) {
3084                continue;
3085            }
3086
3087            final String packageName = info.serviceInfo.packageName;
3088            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3089                if (DEBUG_EPHEMERAL) {
3090                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3091                            + " pkg: " + packageName + ", info:" + info);
3092                }
3093                continue;
3094            }
3095
3096            if (DEBUG_EPHEMERAL) {
3097                Slog.v(TAG, "Ephemeral resolver found;"
3098                        + " pkg: " + packageName + ", info:" + info);
3099            }
3100            return new ComponentName(packageName, info.serviceInfo.name);
3101        }
3102        if (DEBUG_EPHEMERAL) {
3103            Slog.v(TAG, "Ephemeral resolver NOT found");
3104        }
3105        return null;
3106    }
3107
3108    private @Nullable ComponentName getEphemeralInstallerLPr() {
3109        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3110        intent.addCategory(Intent.CATEGORY_DEFAULT);
3111        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3112
3113        final int resolveFlags =
3114                MATCH_DIRECT_BOOT_AWARE
3115                | MATCH_DIRECT_BOOT_UNAWARE
3116                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3117        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3118                resolveFlags, UserHandle.USER_SYSTEM);
3119        Iterator<ResolveInfo> iter = matches.iterator();
3120        while (iter.hasNext()) {
3121            final ResolveInfo rInfo = iter.next();
3122            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3123            if (ps != null) {
3124                final PermissionsState permissionsState = ps.getPermissionsState();
3125                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3126                    continue;
3127                }
3128            }
3129            iter.remove();
3130        }
3131        if (matches.size() == 0) {
3132            return null;
3133        } else if (matches.size() == 1) {
3134            return matches.get(0).getComponentInfo().getComponentName();
3135        } else {
3136            throw new RuntimeException(
3137                    "There must be at most one ephemeral installer; found " + matches);
3138        }
3139    }
3140
3141    private void primeDomainVerificationsLPw(int userId) {
3142        if (DEBUG_DOMAIN_VERIFICATION) {
3143            Slog.d(TAG, "Priming domain verifications in user " + userId);
3144        }
3145
3146        SystemConfig systemConfig = SystemConfig.getInstance();
3147        ArraySet<String> packages = systemConfig.getLinkedApps();
3148
3149        for (String packageName : packages) {
3150            PackageParser.Package pkg = mPackages.get(packageName);
3151            if (pkg != null) {
3152                if (!pkg.isSystemApp()) {
3153                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3154                    continue;
3155                }
3156
3157                ArraySet<String> domains = null;
3158                for (PackageParser.Activity a : pkg.activities) {
3159                    for (ActivityIntentInfo filter : a.intents) {
3160                        if (hasValidDomains(filter)) {
3161                            if (domains == null) {
3162                                domains = new ArraySet<String>();
3163                            }
3164                            domains.addAll(filter.getHostsList());
3165                        }
3166                    }
3167                }
3168
3169                if (domains != null && domains.size() > 0) {
3170                    if (DEBUG_DOMAIN_VERIFICATION) {
3171                        Slog.v(TAG, "      + " + packageName);
3172                    }
3173                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3174                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3175                    // and then 'always' in the per-user state actually used for intent resolution.
3176                    final IntentFilterVerificationInfo ivi;
3177                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3178                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3179                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3180                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3181                } else {
3182                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3183                            + "' does not handle web links");
3184                }
3185            } else {
3186                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3187            }
3188        }
3189
3190        scheduleWritePackageRestrictionsLocked(userId);
3191        scheduleWriteSettingsLocked();
3192    }
3193
3194    private void applyFactoryDefaultBrowserLPw(int userId) {
3195        // The default browser app's package name is stored in a string resource,
3196        // with a product-specific overlay used for vendor customization.
3197        String browserPkg = mContext.getResources().getString(
3198                com.android.internal.R.string.default_browser);
3199        if (!TextUtils.isEmpty(browserPkg)) {
3200            // non-empty string => required to be a known package
3201            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3202            if (ps == null) {
3203                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3204                browserPkg = null;
3205            } else {
3206                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3207            }
3208        }
3209
3210        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3211        // default.  If there's more than one, just leave everything alone.
3212        if (browserPkg == null) {
3213            calculateDefaultBrowserLPw(userId);
3214        }
3215    }
3216
3217    private void calculateDefaultBrowserLPw(int userId) {
3218        List<String> allBrowsers = resolveAllBrowserApps(userId);
3219        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3220        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3221    }
3222
3223    private List<String> resolveAllBrowserApps(int userId) {
3224        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3225        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3226                PackageManager.MATCH_ALL, userId);
3227
3228        final int count = list.size();
3229        List<String> result = new ArrayList<String>(count);
3230        for (int i=0; i<count; i++) {
3231            ResolveInfo info = list.get(i);
3232            if (info.activityInfo == null
3233                    || !info.handleAllWebDataURI
3234                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3235                    || result.contains(info.activityInfo.packageName)) {
3236                continue;
3237            }
3238            result.add(info.activityInfo.packageName);
3239        }
3240
3241        return result;
3242    }
3243
3244    private boolean packageIsBrowser(String packageName, int userId) {
3245        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3246                PackageManager.MATCH_ALL, userId);
3247        final int N = list.size();
3248        for (int i = 0; i < N; i++) {
3249            ResolveInfo info = list.get(i);
3250            if (packageName.equals(info.activityInfo.packageName)) {
3251                return true;
3252            }
3253        }
3254        return false;
3255    }
3256
3257    private void checkDefaultBrowser() {
3258        final int myUserId = UserHandle.myUserId();
3259        final String packageName = getDefaultBrowserPackageName(myUserId);
3260        if (packageName != null) {
3261            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3262            if (info == null) {
3263                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3264                synchronized (mPackages) {
3265                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3266                }
3267            }
3268        }
3269    }
3270
3271    @Override
3272    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3273            throws RemoteException {
3274        try {
3275            return super.onTransact(code, data, reply, flags);
3276        } catch (RuntimeException e) {
3277            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3278                Slog.wtf(TAG, "Package Manager Crash", e);
3279            }
3280            throw e;
3281        }
3282    }
3283
3284    static int[] appendInts(int[] cur, int[] add) {
3285        if (add == null) return cur;
3286        if (cur == null) return add;
3287        final int N = add.length;
3288        for (int i=0; i<N; i++) {
3289            cur = appendInt(cur, add[i]);
3290        }
3291        return cur;
3292    }
3293
3294    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3295        if (!sUserManager.exists(userId)) return null;
3296        if (ps == null) {
3297            return null;
3298        }
3299        final PackageParser.Package p = ps.pkg;
3300        if (p == null) {
3301            return null;
3302        }
3303        // Filter out ephemeral app metadata:
3304        //   * The system/shell/root can see metadata for any app
3305        //   * An installed app can see metadata for 1) other installed apps
3306        //     and 2) ephemeral apps that have explicitly interacted with it
3307        //   * Ephemeral apps can only see their own metadata
3308        //   * Holding a signature permission allows seeing instant apps
3309        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3310        if (callingAppId != Process.SYSTEM_UID
3311                && callingAppId != Process.SHELL_UID
3312                && callingAppId != Process.ROOT_UID
3313                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3314                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3315            final String ephemeralPackageName = getEphemeralPackageName(Binder.getCallingUid());
3316            if (ephemeralPackageName != null) {
3317                // ephemeral apps can only get information on themselves
3318                if (!ephemeralPackageName.equals(p.packageName)) {
3319                    return null;
3320                }
3321            } else {
3322                if (p.applicationInfo.isInstantApp()) {
3323                    // only get access to the ephemeral app if we've been granted access
3324                    if (!mInstantAppRegistry.isInstantAccessGranted(
3325                            userId, callingAppId, ps.appId)) {
3326                        return null;
3327                    }
3328                }
3329            }
3330        }
3331
3332        final PermissionsState permissionsState = ps.getPermissionsState();
3333
3334        // Compute GIDs only if requested
3335        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3336                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3337        // Compute granted permissions only if package has requested permissions
3338        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3339                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3340        final PackageUserState state = ps.readUserState(userId);
3341
3342        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3343                && ps.isSystem()) {
3344            flags |= MATCH_ANY_USER;
3345        }
3346
3347        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3348                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3349
3350        if (packageInfo == null) {
3351            return null;
3352        }
3353
3354        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3355                resolveExternalPackageNameLPr(p);
3356
3357        return packageInfo;
3358    }
3359
3360    @Override
3361    public void checkPackageStartable(String packageName, int userId) {
3362        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3363
3364        synchronized (mPackages) {
3365            final PackageSetting ps = mSettings.mPackages.get(packageName);
3366            if (ps == null) {
3367                throw new SecurityException("Package " + packageName + " was not found!");
3368            }
3369
3370            if (!ps.getInstalled(userId)) {
3371                throw new SecurityException(
3372                        "Package " + packageName + " was not installed for user " + userId + "!");
3373            }
3374
3375            if (mSafeMode && !ps.isSystem()) {
3376                throw new SecurityException("Package " + packageName + " not a system app!");
3377            }
3378
3379            if (mFrozenPackages.contains(packageName)) {
3380                throw new SecurityException("Package " + packageName + " is currently frozen!");
3381            }
3382
3383            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3384                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3385                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3386            }
3387        }
3388    }
3389
3390    @Override
3391    public boolean isPackageAvailable(String packageName, int userId) {
3392        if (!sUserManager.exists(userId)) return false;
3393        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3394                false /* requireFullPermission */, false /* checkShell */, "is package available");
3395        synchronized (mPackages) {
3396            PackageParser.Package p = mPackages.get(packageName);
3397            if (p != null) {
3398                final PackageSetting ps = (PackageSetting) p.mExtras;
3399                if (ps != null) {
3400                    final PackageUserState state = ps.readUserState(userId);
3401                    if (state != null) {
3402                        return PackageParser.isAvailable(state);
3403                    }
3404                }
3405            }
3406        }
3407        return false;
3408    }
3409
3410    @Override
3411    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3412        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3413                flags, userId);
3414    }
3415
3416    @Override
3417    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3418            int flags, int userId) {
3419        return getPackageInfoInternal(versionedPackage.getPackageName(),
3420                // TODO: We will change version code to long, so in the new API it is long
3421                (int) versionedPackage.getVersionCode(), flags, userId);
3422    }
3423
3424    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3425            int flags, int userId) {
3426        if (!sUserManager.exists(userId)) return null;
3427        flags = updateFlagsForPackage(flags, userId, packageName);
3428        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3429                false /* requireFullPermission */, false /* checkShell */, "get package info");
3430
3431        // reader
3432        synchronized (mPackages) {
3433            // Normalize package name to handle renamed packages and static libs
3434            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3435
3436            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3437            if (matchFactoryOnly) {
3438                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3439                if (ps != null) {
3440                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3441                        return null;
3442                    }
3443                    return generatePackageInfo(ps, flags, userId);
3444                }
3445            }
3446
3447            PackageParser.Package p = mPackages.get(packageName);
3448            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3449                return null;
3450            }
3451            if (DEBUG_PACKAGE_INFO)
3452                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3453            if (p != null) {
3454                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3455                        Binder.getCallingUid(), userId)) {
3456                    return null;
3457                }
3458                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3459            }
3460            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3461                final PackageSetting ps = mSettings.mPackages.get(packageName);
3462                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3463                    return null;
3464                }
3465                return generatePackageInfo(ps, flags, userId);
3466            }
3467        }
3468        return null;
3469    }
3470
3471
3472    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) {
3473        // System/shell/root get to see all static libs
3474        final int appId = UserHandle.getAppId(uid);
3475        if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3476                || appId == Process.ROOT_UID) {
3477            return false;
3478        }
3479
3480        // No package means no static lib as it is always on internal storage
3481        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3482            return false;
3483        }
3484
3485        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3486                ps.pkg.staticSharedLibVersion);
3487        if (libEntry == null) {
3488            return false;
3489        }
3490
3491        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3492        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3493        if (uidPackageNames == null) {
3494            return true;
3495        }
3496
3497        for (String uidPackageName : uidPackageNames) {
3498            if (ps.name.equals(uidPackageName)) {
3499                return false;
3500            }
3501            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3502            if (uidPs != null) {
3503                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3504                        libEntry.info.getName());
3505                if (index < 0) {
3506                    continue;
3507                }
3508                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3509                    return false;
3510                }
3511            }
3512        }
3513        return true;
3514    }
3515
3516    @Override
3517    public String[] currentToCanonicalPackageNames(String[] names) {
3518        String[] out = new String[names.length];
3519        // reader
3520        synchronized (mPackages) {
3521            for (int i=names.length-1; i>=0; i--) {
3522                PackageSetting ps = mSettings.mPackages.get(names[i]);
3523                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3524            }
3525        }
3526        return out;
3527    }
3528
3529    @Override
3530    public String[] canonicalToCurrentPackageNames(String[] names) {
3531        String[] out = new String[names.length];
3532        // reader
3533        synchronized (mPackages) {
3534            for (int i=names.length-1; i>=0; i--) {
3535                String cur = mSettings.getRenamedPackageLPr(names[i]);
3536                out[i] = cur != null ? cur : names[i];
3537            }
3538        }
3539        return out;
3540    }
3541
3542    @Override
3543    public int getPackageUid(String packageName, int flags, int userId) {
3544        if (!sUserManager.exists(userId)) return -1;
3545        flags = updateFlagsForPackage(flags, userId, packageName);
3546        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3547                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3548
3549        // reader
3550        synchronized (mPackages) {
3551            final PackageParser.Package p = mPackages.get(packageName);
3552            if (p != null && p.isMatch(flags)) {
3553                return UserHandle.getUid(userId, p.applicationInfo.uid);
3554            }
3555            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3556                final PackageSetting ps = mSettings.mPackages.get(packageName);
3557                if (ps != null && ps.isMatch(flags)) {
3558                    return UserHandle.getUid(userId, ps.appId);
3559                }
3560            }
3561        }
3562
3563        return -1;
3564    }
3565
3566    @Override
3567    public int[] getPackageGids(String packageName, int flags, int userId) {
3568        if (!sUserManager.exists(userId)) return null;
3569        flags = updateFlagsForPackage(flags, userId, packageName);
3570        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3571                false /* requireFullPermission */, false /* checkShell */,
3572                "getPackageGids");
3573
3574        // reader
3575        synchronized (mPackages) {
3576            final PackageParser.Package p = mPackages.get(packageName);
3577            if (p != null && p.isMatch(flags)) {
3578                PackageSetting ps = (PackageSetting) p.mExtras;
3579                // TODO: Shouldn't this be checking for package installed state for userId and
3580                // return null?
3581                return ps.getPermissionsState().computeGids(userId);
3582            }
3583            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3584                final PackageSetting ps = mSettings.mPackages.get(packageName);
3585                if (ps != null && ps.isMatch(flags)) {
3586                    return ps.getPermissionsState().computeGids(userId);
3587                }
3588            }
3589        }
3590
3591        return null;
3592    }
3593
3594    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3595        if (bp.perm != null) {
3596            return PackageParser.generatePermissionInfo(bp.perm, flags);
3597        }
3598        PermissionInfo pi = new PermissionInfo();
3599        pi.name = bp.name;
3600        pi.packageName = bp.sourcePackage;
3601        pi.nonLocalizedLabel = bp.name;
3602        pi.protectionLevel = bp.protectionLevel;
3603        return pi;
3604    }
3605
3606    @Override
3607    public PermissionInfo getPermissionInfo(String name, int flags) {
3608        // reader
3609        synchronized (mPackages) {
3610            final BasePermission p = mSettings.mPermissions.get(name);
3611            if (p != null) {
3612                return generatePermissionInfo(p, flags);
3613            }
3614            return null;
3615        }
3616    }
3617
3618    @Override
3619    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3620            int flags) {
3621        // reader
3622        synchronized (mPackages) {
3623            if (group != null && !mPermissionGroups.containsKey(group)) {
3624                // This is thrown as NameNotFoundException
3625                return null;
3626            }
3627
3628            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3629            for (BasePermission p : mSettings.mPermissions.values()) {
3630                if (group == null) {
3631                    if (p.perm == null || p.perm.info.group == null) {
3632                        out.add(generatePermissionInfo(p, flags));
3633                    }
3634                } else {
3635                    if (p.perm != null && group.equals(p.perm.info.group)) {
3636                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3637                    }
3638                }
3639            }
3640            return new ParceledListSlice<>(out);
3641        }
3642    }
3643
3644    @Override
3645    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3646        // reader
3647        synchronized (mPackages) {
3648            return PackageParser.generatePermissionGroupInfo(
3649                    mPermissionGroups.get(name), flags);
3650        }
3651    }
3652
3653    @Override
3654    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3655        // reader
3656        synchronized (mPackages) {
3657            final int N = mPermissionGroups.size();
3658            ArrayList<PermissionGroupInfo> out
3659                    = new ArrayList<PermissionGroupInfo>(N);
3660            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3661                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3662            }
3663            return new ParceledListSlice<>(out);
3664        }
3665    }
3666
3667    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3668            int uid, int userId) {
3669        if (!sUserManager.exists(userId)) return null;
3670        PackageSetting ps = mSettings.mPackages.get(packageName);
3671        if (ps != null) {
3672            if (filterSharedLibPackageLPr(ps, uid, userId)) {
3673                return null;
3674            }
3675            if (ps.pkg == null) {
3676                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3677                if (pInfo != null) {
3678                    return pInfo.applicationInfo;
3679                }
3680                return null;
3681            }
3682            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3683                    ps.readUserState(userId), userId);
3684            if (ai != null) {
3685                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3686            }
3687            return ai;
3688        }
3689        return null;
3690    }
3691
3692    @Override
3693    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3694        if (!sUserManager.exists(userId)) return null;
3695        flags = updateFlagsForApplication(flags, userId, packageName);
3696        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3697                false /* requireFullPermission */, false /* checkShell */, "get application info");
3698
3699        // writer
3700        synchronized (mPackages) {
3701            // Normalize package name to handle renamed packages and static libs
3702            packageName = resolveInternalPackageNameLPr(packageName,
3703                    PackageManager.VERSION_CODE_HIGHEST);
3704
3705            PackageParser.Package p = mPackages.get(packageName);
3706            if (DEBUG_PACKAGE_INFO) Log.v(
3707                    TAG, "getApplicationInfo " + packageName
3708                    + ": " + p);
3709            if (p != null) {
3710                PackageSetting ps = mSettings.mPackages.get(packageName);
3711                if (ps == null) return null;
3712                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3713                    return null;
3714                }
3715                // Note: isEnabledLP() does not apply here - always return info
3716                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3717                        p, flags, ps.readUserState(userId), userId);
3718                if (ai != null) {
3719                    ai.packageName = resolveExternalPackageNameLPr(p);
3720                }
3721                return ai;
3722            }
3723            if ("android".equals(packageName)||"system".equals(packageName)) {
3724                return mAndroidApplication;
3725            }
3726            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3727                // Already generates the external package name
3728                return generateApplicationInfoFromSettingsLPw(packageName,
3729                        Binder.getCallingUid(), flags, userId);
3730            }
3731        }
3732        return null;
3733    }
3734
3735    private String normalizePackageNameLPr(String packageName) {
3736        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3737        return normalizedPackageName != null ? normalizedPackageName : packageName;
3738    }
3739
3740    @Override
3741    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3742            final IPackageDataObserver observer) {
3743        mContext.enforceCallingOrSelfPermission(
3744                android.Manifest.permission.CLEAR_APP_CACHE, null);
3745        // Queue up an async operation since clearing cache may take a little while.
3746        mHandler.post(new Runnable() {
3747            public void run() {
3748                mHandler.removeCallbacks(this);
3749                boolean success = true;
3750                synchronized (mInstallLock) {
3751                    try {
3752                        mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3753                    } catch (InstallerException e) {
3754                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3755                        success = false;
3756                    }
3757                }
3758                if (observer != null) {
3759                    try {
3760                        observer.onRemoveCompleted(null, success);
3761                    } catch (RemoteException e) {
3762                        Slog.w(TAG, "RemoveException when invoking call back");
3763                    }
3764                }
3765            }
3766        });
3767    }
3768
3769    @Override
3770    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3771            final IntentSender pi) {
3772        mContext.enforceCallingOrSelfPermission(
3773                android.Manifest.permission.CLEAR_APP_CACHE, null);
3774        // Queue up an async operation since clearing cache may take a little while.
3775        mHandler.post(new Runnable() {
3776            public void run() {
3777                mHandler.removeCallbacks(this);
3778                boolean success = true;
3779                synchronized (mInstallLock) {
3780                    try {
3781                        mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3782                    } catch (InstallerException e) {
3783                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3784                        success = false;
3785                    }
3786                }
3787                if(pi != null) {
3788                    try {
3789                        // Callback via pending intent
3790                        int code = success ? 1 : 0;
3791                        pi.sendIntent(null, code, null,
3792                                null, null);
3793                    } catch (SendIntentException e1) {
3794                        Slog.i(TAG, "Failed to send pending intent");
3795                    }
3796                }
3797            }
3798        });
3799    }
3800
3801    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3802        synchronized (mInstallLock) {
3803            try {
3804                mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3805            } catch (InstallerException e) {
3806                throw new IOException("Failed to free enough space", e);
3807            }
3808        }
3809    }
3810
3811    /**
3812     * Update given flags based on encryption status of current user.
3813     */
3814    private int updateFlags(int flags, int userId) {
3815        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3816                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3817            // Caller expressed an explicit opinion about what encryption
3818            // aware/unaware components they want to see, so fall through and
3819            // give them what they want
3820        } else {
3821            // Caller expressed no opinion, so match based on user state
3822            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3823                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3824            } else {
3825                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3826            }
3827        }
3828        return flags;
3829    }
3830
3831    private UserManagerInternal getUserManagerInternal() {
3832        if (mUserManagerInternal == null) {
3833            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3834        }
3835        return mUserManagerInternal;
3836    }
3837
3838    /**
3839     * Update given flags when being used to request {@link PackageInfo}.
3840     */
3841    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3842        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3843        boolean triaged = true;
3844        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3845                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3846            // Caller is asking for component details, so they'd better be
3847            // asking for specific encryption matching behavior, or be triaged
3848            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3849                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3850                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3851                triaged = false;
3852            }
3853        }
3854        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3855                | PackageManager.MATCH_SYSTEM_ONLY
3856                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3857            triaged = false;
3858        }
3859        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3860            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3861                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3862                    + Debug.getCallers(5));
3863        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3864                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3865            // If the caller wants all packages and has a restricted profile associated with it,
3866            // then match all users. This is to make sure that launchers that need to access work
3867            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3868            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3869            flags |= PackageManager.MATCH_ANY_USER;
3870        }
3871        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3872            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3873                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3874        }
3875        return updateFlags(flags, userId);
3876    }
3877
3878    /**
3879     * Update given flags when being used to request {@link ApplicationInfo}.
3880     */
3881    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3882        return updateFlagsForPackage(flags, userId, cookie);
3883    }
3884
3885    /**
3886     * Update given flags when being used to request {@link ComponentInfo}.
3887     */
3888    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3889        if (cookie instanceof Intent) {
3890            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3891                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3892            }
3893        }
3894
3895        boolean triaged = true;
3896        // Caller is asking for component details, so they'd better be
3897        // asking for specific encryption matching behavior, or be triaged
3898        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3899                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3900                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3901            triaged = false;
3902        }
3903        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3904            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3905                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3906        }
3907
3908        return updateFlags(flags, userId);
3909    }
3910
3911    /**
3912     * Update given intent when being used to request {@link ResolveInfo}.
3913     */
3914    private Intent updateIntentForResolve(Intent intent) {
3915        if (intent.getSelector() != null) {
3916            intent = intent.getSelector();
3917        }
3918        if (DEBUG_PREFERRED) {
3919            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3920        }
3921        return intent;
3922    }
3923
3924    /**
3925     * Update given flags when being used to request {@link ResolveInfo}.
3926     */
3927    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3928        // Safe mode means we shouldn't match any third-party components
3929        if (mSafeMode) {
3930            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3931        }
3932        final int callingUid = Binder.getCallingUid();
3933        if (callingUid == Process.SYSTEM_UID || callingUid == 0) {
3934            // The system sees all components
3935            flags |= PackageManager.MATCH_EPHEMERAL;
3936        } else if (getEphemeralPackageName(callingUid) != null) {
3937            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
3938            flags |= PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY;
3939            flags |= PackageManager.MATCH_EPHEMERAL;
3940        } else {
3941            // Otherwise, prevent leaking ephemeral components
3942            flags &= ~PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY;
3943            flags &= ~PackageManager.MATCH_EPHEMERAL;
3944        }
3945        return updateFlagsForComponent(flags, userId, cookie);
3946    }
3947
3948    @Override
3949    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3950        if (!sUserManager.exists(userId)) return null;
3951        flags = updateFlagsForComponent(flags, userId, component);
3952        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3953                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3954        synchronized (mPackages) {
3955            PackageParser.Activity a = mActivities.mActivities.get(component);
3956
3957            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3958            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3959                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3960                if (ps == null) return null;
3961                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3962                        userId);
3963            }
3964            if (mResolveComponentName.equals(component)) {
3965                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3966                        new PackageUserState(), userId);
3967            }
3968        }
3969        return null;
3970    }
3971
3972    @Override
3973    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3974            String resolvedType) {
3975        synchronized (mPackages) {
3976            if (component.equals(mResolveComponentName)) {
3977                // The resolver supports EVERYTHING!
3978                return true;
3979            }
3980            PackageParser.Activity a = mActivities.mActivities.get(component);
3981            if (a == null) {
3982                return false;
3983            }
3984            for (int i=0; i<a.intents.size(); i++) {
3985                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3986                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3987                    return true;
3988                }
3989            }
3990            return false;
3991        }
3992    }
3993
3994    @Override
3995    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3996        if (!sUserManager.exists(userId)) return null;
3997        flags = updateFlagsForComponent(flags, userId, component);
3998        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3999                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4000        synchronized (mPackages) {
4001            PackageParser.Activity a = mReceivers.mActivities.get(component);
4002            if (DEBUG_PACKAGE_INFO) Log.v(
4003                TAG, "getReceiverInfo " + component + ": " + a);
4004            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4005                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4006                if (ps == null) return null;
4007                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
4008                        userId);
4009            }
4010        }
4011        return null;
4012    }
4013
4014    @Override
4015    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4016        if (!sUserManager.exists(userId)) return null;
4017        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4018
4019        flags = updateFlagsForPackage(flags, userId, null);
4020
4021        final boolean canSeeStaticLibraries =
4022                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4023                        == PERMISSION_GRANTED
4024                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4025                        == PERMISSION_GRANTED
4026                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4027                        == PERMISSION_GRANTED
4028                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4029                        == PERMISSION_GRANTED;
4030
4031        synchronized (mPackages) {
4032            List<SharedLibraryInfo> result = null;
4033
4034            final int libCount = mSharedLibraries.size();
4035            for (int i = 0; i < libCount; i++) {
4036                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4037                if (versionedLib == null) {
4038                    continue;
4039                }
4040
4041                final int versionCount = versionedLib.size();
4042                for (int j = 0; j < versionCount; j++) {
4043                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4044                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4045                        break;
4046                    }
4047                    final long identity = Binder.clearCallingIdentity();
4048                    try {
4049                        // TODO: We will change version code to long, so in the new API it is long
4050                        PackageInfo packageInfo = getPackageInfoVersioned(
4051                                libInfo.getDeclaringPackage(), flags, userId);
4052                        if (packageInfo == null) {
4053                            continue;
4054                        }
4055                    } finally {
4056                        Binder.restoreCallingIdentity(identity);
4057                    }
4058
4059                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4060                            libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(),
4061                            getPackagesUsingSharedLibraryLPr(libInfo, flags, userId));
4062
4063                    if (result == null) {
4064                        result = new ArrayList<>();
4065                    }
4066                    result.add(resLibInfo);
4067                }
4068            }
4069
4070            return result != null ? new ParceledListSlice<>(result) : null;
4071        }
4072    }
4073
4074    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4075            SharedLibraryInfo libInfo, int flags, int userId) {
4076        List<VersionedPackage> versionedPackages = null;
4077        final int packageCount = mSettings.mPackages.size();
4078        for (int i = 0; i < packageCount; i++) {
4079            PackageSetting ps = mSettings.mPackages.valueAt(i);
4080
4081            if (ps == null) {
4082                continue;
4083            }
4084
4085            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4086                continue;
4087            }
4088
4089            final String libName = libInfo.getName();
4090            if (libInfo.isStatic()) {
4091                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4092                if (libIdx < 0) {
4093                    continue;
4094                }
4095                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4096                    continue;
4097                }
4098                if (versionedPackages == null) {
4099                    versionedPackages = new ArrayList<>();
4100                }
4101                // If the dependent is a static shared lib, use the public package name
4102                String dependentPackageName = ps.name;
4103                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4104                    dependentPackageName = ps.pkg.manifestPackageName;
4105                }
4106                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4107            } else if (ps.pkg != null) {
4108                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4109                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4110                    if (versionedPackages == null) {
4111                        versionedPackages = new ArrayList<>();
4112                    }
4113                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4114                }
4115            }
4116        }
4117
4118        return versionedPackages;
4119    }
4120
4121    @Override
4122    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4123        if (!sUserManager.exists(userId)) return null;
4124        flags = updateFlagsForComponent(flags, userId, component);
4125        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4126                false /* requireFullPermission */, false /* checkShell */, "get service info");
4127        synchronized (mPackages) {
4128            PackageParser.Service s = mServices.mServices.get(component);
4129            if (DEBUG_PACKAGE_INFO) Log.v(
4130                TAG, "getServiceInfo " + component + ": " + s);
4131            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4132                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4133                if (ps == null) return null;
4134                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
4135                        userId);
4136            }
4137        }
4138        return null;
4139    }
4140
4141    @Override
4142    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4143        if (!sUserManager.exists(userId)) return null;
4144        flags = updateFlagsForComponent(flags, userId, component);
4145        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4146                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4147        synchronized (mPackages) {
4148            PackageParser.Provider p = mProviders.mProviders.get(component);
4149            if (DEBUG_PACKAGE_INFO) Log.v(
4150                TAG, "getProviderInfo " + component + ": " + p);
4151            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4152                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4153                if (ps == null) return null;
4154                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
4155                        userId);
4156            }
4157        }
4158        return null;
4159    }
4160
4161    @Override
4162    public String[] getSystemSharedLibraryNames() {
4163        synchronized (mPackages) {
4164            Set<String> libs = null;
4165            final int libCount = mSharedLibraries.size();
4166            for (int i = 0; i < libCount; i++) {
4167                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4168                if (versionedLib == null) {
4169                    continue;
4170                }
4171                final int versionCount = versionedLib.size();
4172                for (int j = 0; j < versionCount; j++) {
4173                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4174                    if (!libEntry.info.isStatic()) {
4175                        if (libs == null) {
4176                            libs = new ArraySet<>();
4177                        }
4178                        libs.add(libEntry.info.getName());
4179                        break;
4180                    }
4181                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4182                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4183                            UserHandle.getUserId(Binder.getCallingUid()))) {
4184                        if (libs == null) {
4185                            libs = new ArraySet<>();
4186                        }
4187                        libs.add(libEntry.info.getName());
4188                        break;
4189                    }
4190                }
4191            }
4192
4193            if (libs != null) {
4194                String[] libsArray = new String[libs.size()];
4195                libs.toArray(libsArray);
4196                return libsArray;
4197            }
4198
4199            return null;
4200        }
4201    }
4202
4203    @Override
4204    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4205        synchronized (mPackages) {
4206            return mServicesSystemSharedLibraryPackageName;
4207        }
4208    }
4209
4210    @Override
4211    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4212        synchronized (mPackages) {
4213            return mSharedSystemSharedLibraryPackageName;
4214        }
4215    }
4216
4217    @Override
4218    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4219        ArrayList<FeatureInfo> res;
4220        synchronized (mAvailableFeatures) {
4221            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4222            res.addAll(mAvailableFeatures.values());
4223        }
4224        final FeatureInfo fi = new FeatureInfo();
4225        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4226                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4227        res.add(fi);
4228
4229        return new ParceledListSlice<>(res);
4230    }
4231
4232    @Override
4233    public boolean hasSystemFeature(String name, int version) {
4234        synchronized (mAvailableFeatures) {
4235            final FeatureInfo feat = mAvailableFeatures.get(name);
4236            if (feat == null) {
4237                return false;
4238            } else {
4239                return feat.version >= version;
4240            }
4241        }
4242    }
4243
4244    @Override
4245    public int checkPermission(String permName, String pkgName, int userId) {
4246        if (!sUserManager.exists(userId)) {
4247            return PackageManager.PERMISSION_DENIED;
4248        }
4249
4250        synchronized (mPackages) {
4251            final PackageParser.Package p = mPackages.get(pkgName);
4252            if (p != null && p.mExtras != null) {
4253                final PackageSetting ps = (PackageSetting) p.mExtras;
4254                final PermissionsState permissionsState = ps.getPermissionsState();
4255                if (permissionsState.hasPermission(permName, userId)) {
4256                    return PackageManager.PERMISSION_GRANTED;
4257                }
4258                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4259                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4260                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4261                    return PackageManager.PERMISSION_GRANTED;
4262                }
4263            }
4264        }
4265
4266        return PackageManager.PERMISSION_DENIED;
4267    }
4268
4269    @Override
4270    public int checkUidPermission(String permName, int uid) {
4271        final int userId = UserHandle.getUserId(uid);
4272
4273        if (!sUserManager.exists(userId)) {
4274            return PackageManager.PERMISSION_DENIED;
4275        }
4276
4277        synchronized (mPackages) {
4278            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4279            if (obj != null) {
4280                final SettingBase ps = (SettingBase) obj;
4281                final PermissionsState permissionsState = ps.getPermissionsState();
4282                if (permissionsState.hasPermission(permName, userId)) {
4283                    return PackageManager.PERMISSION_GRANTED;
4284                }
4285                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4286                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4287                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4288                    return PackageManager.PERMISSION_GRANTED;
4289                }
4290            } else {
4291                ArraySet<String> perms = mSystemPermissions.get(uid);
4292                if (perms != null) {
4293                    if (perms.contains(permName)) {
4294                        return PackageManager.PERMISSION_GRANTED;
4295                    }
4296                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4297                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4298                        return PackageManager.PERMISSION_GRANTED;
4299                    }
4300                }
4301            }
4302        }
4303
4304        return PackageManager.PERMISSION_DENIED;
4305    }
4306
4307    @Override
4308    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4309        if (UserHandle.getCallingUserId() != userId) {
4310            mContext.enforceCallingPermission(
4311                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4312                    "isPermissionRevokedByPolicy for user " + userId);
4313        }
4314
4315        if (checkPermission(permission, packageName, userId)
4316                == PackageManager.PERMISSION_GRANTED) {
4317            return false;
4318        }
4319
4320        final long identity = Binder.clearCallingIdentity();
4321        try {
4322            final int flags = getPermissionFlags(permission, packageName, userId);
4323            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4324        } finally {
4325            Binder.restoreCallingIdentity(identity);
4326        }
4327    }
4328
4329    @Override
4330    public String getPermissionControllerPackageName() {
4331        synchronized (mPackages) {
4332            return mRequiredInstallerPackage;
4333        }
4334    }
4335
4336    /**
4337     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4338     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4339     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4340     * @param message the message to log on security exception
4341     */
4342    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4343            boolean checkShell, String message) {
4344        if (userId < 0) {
4345            throw new IllegalArgumentException("Invalid userId " + userId);
4346        }
4347        if (checkShell) {
4348            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4349        }
4350        if (userId == UserHandle.getUserId(callingUid)) return;
4351        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4352            if (requireFullPermission) {
4353                mContext.enforceCallingOrSelfPermission(
4354                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4355            } else {
4356                try {
4357                    mContext.enforceCallingOrSelfPermission(
4358                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4359                } catch (SecurityException se) {
4360                    mContext.enforceCallingOrSelfPermission(
4361                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4362                }
4363            }
4364        }
4365    }
4366
4367    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4368        if (callingUid == Process.SHELL_UID) {
4369            if (userHandle >= 0
4370                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4371                throw new SecurityException("Shell does not have permission to access user "
4372                        + userHandle);
4373            } else if (userHandle < 0) {
4374                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4375                        + Debug.getCallers(3));
4376            }
4377        }
4378    }
4379
4380    private BasePermission findPermissionTreeLP(String permName) {
4381        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4382            if (permName.startsWith(bp.name) &&
4383                    permName.length() > bp.name.length() &&
4384                    permName.charAt(bp.name.length()) == '.') {
4385                return bp;
4386            }
4387        }
4388        return null;
4389    }
4390
4391    private BasePermission checkPermissionTreeLP(String permName) {
4392        if (permName != null) {
4393            BasePermission bp = findPermissionTreeLP(permName);
4394            if (bp != null) {
4395                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4396                    return bp;
4397                }
4398                throw new SecurityException("Calling uid "
4399                        + Binder.getCallingUid()
4400                        + " is not allowed to add to permission tree "
4401                        + bp.name + " owned by uid " + bp.uid);
4402            }
4403        }
4404        throw new SecurityException("No permission tree found for " + permName);
4405    }
4406
4407    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4408        if (s1 == null) {
4409            return s2 == null;
4410        }
4411        if (s2 == null) {
4412            return false;
4413        }
4414        if (s1.getClass() != s2.getClass()) {
4415            return false;
4416        }
4417        return s1.equals(s2);
4418    }
4419
4420    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4421        if (pi1.icon != pi2.icon) return false;
4422        if (pi1.logo != pi2.logo) return false;
4423        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4424        if (!compareStrings(pi1.name, pi2.name)) return false;
4425        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4426        // We'll take care of setting this one.
4427        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4428        // These are not currently stored in settings.
4429        //if (!compareStrings(pi1.group, pi2.group)) return false;
4430        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4431        //if (pi1.labelRes != pi2.labelRes) return false;
4432        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4433        return true;
4434    }
4435
4436    int permissionInfoFootprint(PermissionInfo info) {
4437        int size = info.name.length();
4438        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4439        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4440        return size;
4441    }
4442
4443    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4444        int size = 0;
4445        for (BasePermission perm : mSettings.mPermissions.values()) {
4446            if (perm.uid == tree.uid) {
4447                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4448            }
4449        }
4450        return size;
4451    }
4452
4453    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4454        // We calculate the max size of permissions defined by this uid and throw
4455        // if that plus the size of 'info' would exceed our stated maximum.
4456        if (tree.uid != Process.SYSTEM_UID) {
4457            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4458            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4459                throw new SecurityException("Permission tree size cap exceeded");
4460            }
4461        }
4462    }
4463
4464    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4465        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4466            throw new SecurityException("Label must be specified in permission");
4467        }
4468        BasePermission tree = checkPermissionTreeLP(info.name);
4469        BasePermission bp = mSettings.mPermissions.get(info.name);
4470        boolean added = bp == null;
4471        boolean changed = true;
4472        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4473        if (added) {
4474            enforcePermissionCapLocked(info, tree);
4475            bp = new BasePermission(info.name, tree.sourcePackage,
4476                    BasePermission.TYPE_DYNAMIC);
4477        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4478            throw new SecurityException(
4479                    "Not allowed to modify non-dynamic permission "
4480                    + info.name);
4481        } else {
4482            if (bp.protectionLevel == fixedLevel
4483                    && bp.perm.owner.equals(tree.perm.owner)
4484                    && bp.uid == tree.uid
4485                    && comparePermissionInfos(bp.perm.info, info)) {
4486                changed = false;
4487            }
4488        }
4489        bp.protectionLevel = fixedLevel;
4490        info = new PermissionInfo(info);
4491        info.protectionLevel = fixedLevel;
4492        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4493        bp.perm.info.packageName = tree.perm.info.packageName;
4494        bp.uid = tree.uid;
4495        if (added) {
4496            mSettings.mPermissions.put(info.name, bp);
4497        }
4498        if (changed) {
4499            if (!async) {
4500                mSettings.writeLPr();
4501            } else {
4502                scheduleWriteSettingsLocked();
4503            }
4504        }
4505        return added;
4506    }
4507
4508    @Override
4509    public boolean addPermission(PermissionInfo info) {
4510        synchronized (mPackages) {
4511            return addPermissionLocked(info, false);
4512        }
4513    }
4514
4515    @Override
4516    public boolean addPermissionAsync(PermissionInfo info) {
4517        synchronized (mPackages) {
4518            return addPermissionLocked(info, true);
4519        }
4520    }
4521
4522    @Override
4523    public void removePermission(String name) {
4524        synchronized (mPackages) {
4525            checkPermissionTreeLP(name);
4526            BasePermission bp = mSettings.mPermissions.get(name);
4527            if (bp != null) {
4528                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4529                    throw new SecurityException(
4530                            "Not allowed to modify non-dynamic permission "
4531                            + name);
4532                }
4533                mSettings.mPermissions.remove(name);
4534                mSettings.writeLPr();
4535            }
4536        }
4537    }
4538
4539    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4540            BasePermission bp) {
4541        int index = pkg.requestedPermissions.indexOf(bp.name);
4542        if (index == -1) {
4543            throw new SecurityException("Package " + pkg.packageName
4544                    + " has not requested permission " + bp.name);
4545        }
4546        if (!bp.isRuntime() && !bp.isDevelopment()) {
4547            throw new SecurityException("Permission " + bp.name
4548                    + " is not a changeable permission type");
4549        }
4550    }
4551
4552    @Override
4553    public void grantRuntimePermission(String packageName, String name, final int userId) {
4554        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4555    }
4556
4557    private void grantRuntimePermission(String packageName, String name, final int userId,
4558            boolean overridePolicy) {
4559        if (!sUserManager.exists(userId)) {
4560            Log.e(TAG, "No such user:" + userId);
4561            return;
4562        }
4563
4564        mContext.enforceCallingOrSelfPermission(
4565                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4566                "grantRuntimePermission");
4567
4568        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4569                true /* requireFullPermission */, true /* checkShell */,
4570                "grantRuntimePermission");
4571
4572        final int uid;
4573        final SettingBase sb;
4574
4575        synchronized (mPackages) {
4576            final PackageParser.Package pkg = mPackages.get(packageName);
4577            if (pkg == null) {
4578                throw new IllegalArgumentException("Unknown package: " + packageName);
4579            }
4580
4581            final BasePermission bp = mSettings.mPermissions.get(name);
4582            if (bp == null) {
4583                throw new IllegalArgumentException("Unknown permission: " + name);
4584            }
4585
4586            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4587
4588            // If a permission review is required for legacy apps we represent
4589            // their permissions as always granted runtime ones since we need
4590            // to keep the review required permission flag per user while an
4591            // install permission's state is shared across all users.
4592            if (mPermissionReviewRequired
4593                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4594                    && bp.isRuntime()) {
4595                return;
4596            }
4597
4598            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4599            sb = (SettingBase) pkg.mExtras;
4600            if (sb == null) {
4601                throw new IllegalArgumentException("Unknown package: " + packageName);
4602            }
4603
4604            final PermissionsState permissionsState = sb.getPermissionsState();
4605
4606            final int flags = permissionsState.getPermissionFlags(name, userId);
4607            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4608                throw new SecurityException("Cannot grant system fixed permission "
4609                        + name + " for package " + packageName);
4610            }
4611            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4612                throw new SecurityException("Cannot grant policy fixed permission "
4613                        + name + " for package " + packageName);
4614            }
4615
4616            if (bp.isDevelopment()) {
4617                // Development permissions must be handled specially, since they are not
4618                // normal runtime permissions.  For now they apply to all users.
4619                if (permissionsState.grantInstallPermission(bp) !=
4620                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4621                    scheduleWriteSettingsLocked();
4622                }
4623                return;
4624            }
4625
4626            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
4627                throw new SecurityException("Cannot grant non-ephemeral permission"
4628                        + name + " for package " + packageName);
4629            }
4630
4631            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4632                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4633                return;
4634            }
4635
4636            final int result = permissionsState.grantRuntimePermission(bp, userId);
4637            switch (result) {
4638                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4639                    return;
4640                }
4641
4642                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4643                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4644                    mHandler.post(new Runnable() {
4645                        @Override
4646                        public void run() {
4647                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4648                        }
4649                    });
4650                }
4651                break;
4652            }
4653
4654            if (bp.isRuntime()) {
4655                logPermissionGranted(mContext, name, packageName);
4656            }
4657
4658            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4659
4660            // Not critical if that is lost - app has to request again.
4661            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4662        }
4663
4664        // Only need to do this if user is initialized. Otherwise it's a new user
4665        // and there are no processes running as the user yet and there's no need
4666        // to make an expensive call to remount processes for the changed permissions.
4667        if (READ_EXTERNAL_STORAGE.equals(name)
4668                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4669            final long token = Binder.clearCallingIdentity();
4670            try {
4671                if (sUserManager.isInitialized(userId)) {
4672                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4673                            StorageManagerInternal.class);
4674                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4675                }
4676            } finally {
4677                Binder.restoreCallingIdentity(token);
4678            }
4679        }
4680    }
4681
4682    @Override
4683    public void revokeRuntimePermission(String packageName, String name, int userId) {
4684        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4685    }
4686
4687    private void revokeRuntimePermission(String packageName, String name, int userId,
4688            boolean overridePolicy) {
4689        if (!sUserManager.exists(userId)) {
4690            Log.e(TAG, "No such user:" + userId);
4691            return;
4692        }
4693
4694        mContext.enforceCallingOrSelfPermission(
4695                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4696                "revokeRuntimePermission");
4697
4698        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4699                true /* requireFullPermission */, true /* checkShell */,
4700                "revokeRuntimePermission");
4701
4702        final int appId;
4703
4704        synchronized (mPackages) {
4705            final PackageParser.Package pkg = mPackages.get(packageName);
4706            if (pkg == null) {
4707                throw new IllegalArgumentException("Unknown package: " + packageName);
4708            }
4709
4710            final BasePermission bp = mSettings.mPermissions.get(name);
4711            if (bp == null) {
4712                throw new IllegalArgumentException("Unknown permission: " + name);
4713            }
4714
4715            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4716
4717            // If a permission review is required for legacy apps we represent
4718            // their permissions as always granted runtime ones since we need
4719            // to keep the review required permission flag per user while an
4720            // install permission's state is shared across all users.
4721            if (mPermissionReviewRequired
4722                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4723                    && bp.isRuntime()) {
4724                return;
4725            }
4726
4727            SettingBase sb = (SettingBase) pkg.mExtras;
4728            if (sb == null) {
4729                throw new IllegalArgumentException("Unknown package: " + packageName);
4730            }
4731
4732            final PermissionsState permissionsState = sb.getPermissionsState();
4733
4734            final int flags = permissionsState.getPermissionFlags(name, userId);
4735            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4736                throw new SecurityException("Cannot revoke system fixed permission "
4737                        + name + " for package " + packageName);
4738            }
4739            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4740                throw new SecurityException("Cannot revoke policy fixed permission "
4741                        + name + " for package " + packageName);
4742            }
4743
4744            if (bp.isDevelopment()) {
4745                // Development permissions must be handled specially, since they are not
4746                // normal runtime permissions.  For now they apply to all users.
4747                if (permissionsState.revokeInstallPermission(bp) !=
4748                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4749                    scheduleWriteSettingsLocked();
4750                }
4751                return;
4752            }
4753
4754            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4755                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4756                return;
4757            }
4758
4759            if (bp.isRuntime()) {
4760                logPermissionRevoked(mContext, name, packageName);
4761            }
4762
4763            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4764
4765            // Critical, after this call app should never have the permission.
4766            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4767
4768            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4769        }
4770
4771        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4772    }
4773
4774    /**
4775     * Get the first event id for the permission.
4776     *
4777     * <p>There are four events for each permission: <ul>
4778     *     <li>Request permission: first id + 0</li>
4779     *     <li>Grant permission: first id + 1</li>
4780     *     <li>Request for permission denied: first id + 2</li>
4781     *     <li>Revoke permission: first id + 3</li>
4782     * </ul></p>
4783     *
4784     * @param name name of the permission
4785     *
4786     * @return The first event id for the permission
4787     */
4788    private static int getBaseEventId(@NonNull String name) {
4789        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
4790
4791        if (eventIdIndex == -1) {
4792            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
4793                    || "user".equals(Build.TYPE)) {
4794                Log.i(TAG, "Unknown permission " + name);
4795
4796                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
4797            } else {
4798                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
4799                //
4800                // Also update
4801                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
4802                // - metrics_constants.proto
4803                throw new IllegalStateException("Unknown permission " + name);
4804            }
4805        }
4806
4807        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
4808    }
4809
4810    /**
4811     * Log that a permission was revoked.
4812     *
4813     * @param context Context of the caller
4814     * @param name name of the permission
4815     * @param packageName package permission if for
4816     */
4817    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
4818            @NonNull String packageName) {
4819        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
4820    }
4821
4822    /**
4823     * Log that a permission request was granted.
4824     *
4825     * @param context Context of the caller
4826     * @param name name of the permission
4827     * @param packageName package permission if for
4828     */
4829    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
4830            @NonNull String packageName) {
4831        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
4832    }
4833
4834    @Override
4835    public void resetRuntimePermissions() {
4836        mContext.enforceCallingOrSelfPermission(
4837                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4838                "revokeRuntimePermission");
4839
4840        int callingUid = Binder.getCallingUid();
4841        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4842            mContext.enforceCallingOrSelfPermission(
4843                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4844                    "resetRuntimePermissions");
4845        }
4846
4847        synchronized (mPackages) {
4848            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4849            for (int userId : UserManagerService.getInstance().getUserIds()) {
4850                final int packageCount = mPackages.size();
4851                for (int i = 0; i < packageCount; i++) {
4852                    PackageParser.Package pkg = mPackages.valueAt(i);
4853                    if (!(pkg.mExtras instanceof PackageSetting)) {
4854                        continue;
4855                    }
4856                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4857                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4858                }
4859            }
4860        }
4861    }
4862
4863    @Override
4864    public int getPermissionFlags(String name, String packageName, int userId) {
4865        if (!sUserManager.exists(userId)) {
4866            return 0;
4867        }
4868
4869        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4870
4871        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4872                true /* requireFullPermission */, false /* checkShell */,
4873                "getPermissionFlags");
4874
4875        synchronized (mPackages) {
4876            final PackageParser.Package pkg = mPackages.get(packageName);
4877            if (pkg == null) {
4878                return 0;
4879            }
4880
4881            final BasePermission bp = mSettings.mPermissions.get(name);
4882            if (bp == null) {
4883                return 0;
4884            }
4885
4886            SettingBase sb = (SettingBase) pkg.mExtras;
4887            if (sb == null) {
4888                return 0;
4889            }
4890
4891            PermissionsState permissionsState = sb.getPermissionsState();
4892            return permissionsState.getPermissionFlags(name, userId);
4893        }
4894    }
4895
4896    @Override
4897    public void updatePermissionFlags(String name, String packageName, int flagMask,
4898            int flagValues, int userId) {
4899        if (!sUserManager.exists(userId)) {
4900            return;
4901        }
4902
4903        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4904
4905        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4906                true /* requireFullPermission */, true /* checkShell */,
4907                "updatePermissionFlags");
4908
4909        // Only the system can change these flags and nothing else.
4910        if (getCallingUid() != Process.SYSTEM_UID) {
4911            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4912            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4913            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4914            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4915            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4916        }
4917
4918        synchronized (mPackages) {
4919            final PackageParser.Package pkg = mPackages.get(packageName);
4920            if (pkg == null) {
4921                throw new IllegalArgumentException("Unknown package: " + packageName);
4922            }
4923
4924            final BasePermission bp = mSettings.mPermissions.get(name);
4925            if (bp == null) {
4926                throw new IllegalArgumentException("Unknown permission: " + name);
4927            }
4928
4929            SettingBase sb = (SettingBase) pkg.mExtras;
4930            if (sb == null) {
4931                throw new IllegalArgumentException("Unknown package: " + packageName);
4932            }
4933
4934            PermissionsState permissionsState = sb.getPermissionsState();
4935
4936            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4937
4938            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4939                // Install and runtime permissions are stored in different places,
4940                // so figure out what permission changed and persist the change.
4941                if (permissionsState.getInstallPermissionState(name) != null) {
4942                    scheduleWriteSettingsLocked();
4943                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4944                        || hadState) {
4945                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4946                }
4947            }
4948        }
4949    }
4950
4951    /**
4952     * Update the permission flags for all packages and runtime permissions of a user in order
4953     * to allow device or profile owner to remove POLICY_FIXED.
4954     */
4955    @Override
4956    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4957        if (!sUserManager.exists(userId)) {
4958            return;
4959        }
4960
4961        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4962
4963        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4964                true /* requireFullPermission */, true /* checkShell */,
4965                "updatePermissionFlagsForAllApps");
4966
4967        // Only the system can change system fixed flags.
4968        if (getCallingUid() != Process.SYSTEM_UID) {
4969            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4970            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4971        }
4972
4973        synchronized (mPackages) {
4974            boolean changed = false;
4975            final int packageCount = mPackages.size();
4976            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4977                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4978                SettingBase sb = (SettingBase) pkg.mExtras;
4979                if (sb == null) {
4980                    continue;
4981                }
4982                PermissionsState permissionsState = sb.getPermissionsState();
4983                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4984                        userId, flagMask, flagValues);
4985            }
4986            if (changed) {
4987                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4988            }
4989        }
4990    }
4991
4992    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4993        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4994                != PackageManager.PERMISSION_GRANTED
4995            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4996                != PackageManager.PERMISSION_GRANTED) {
4997            throw new SecurityException(message + " requires "
4998                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4999                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5000        }
5001    }
5002
5003    @Override
5004    public boolean shouldShowRequestPermissionRationale(String permissionName,
5005            String packageName, int userId) {
5006        if (UserHandle.getCallingUserId() != userId) {
5007            mContext.enforceCallingPermission(
5008                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5009                    "canShowRequestPermissionRationale for user " + userId);
5010        }
5011
5012        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5013        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5014            return false;
5015        }
5016
5017        if (checkPermission(permissionName, packageName, userId)
5018                == PackageManager.PERMISSION_GRANTED) {
5019            return false;
5020        }
5021
5022        final int flags;
5023
5024        final long identity = Binder.clearCallingIdentity();
5025        try {
5026            flags = getPermissionFlags(permissionName,
5027                    packageName, userId);
5028        } finally {
5029            Binder.restoreCallingIdentity(identity);
5030        }
5031
5032        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5033                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5034                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5035
5036        if ((flags & fixedFlags) != 0) {
5037            return false;
5038        }
5039
5040        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5041    }
5042
5043    @Override
5044    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5045        mContext.enforceCallingOrSelfPermission(
5046                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5047                "addOnPermissionsChangeListener");
5048
5049        synchronized (mPackages) {
5050            mOnPermissionChangeListeners.addListenerLocked(listener);
5051        }
5052    }
5053
5054    @Override
5055    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5056        synchronized (mPackages) {
5057            mOnPermissionChangeListeners.removeListenerLocked(listener);
5058        }
5059    }
5060
5061    @Override
5062    public boolean isProtectedBroadcast(String actionName) {
5063        synchronized (mPackages) {
5064            if (mProtectedBroadcasts.contains(actionName)) {
5065                return true;
5066            } else if (actionName != null) {
5067                // TODO: remove these terrible hacks
5068                if (actionName.startsWith("android.net.netmon.lingerExpired")
5069                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5070                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5071                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5072                    return true;
5073                }
5074            }
5075        }
5076        return false;
5077    }
5078
5079    @Override
5080    public int checkSignatures(String pkg1, String pkg2) {
5081        synchronized (mPackages) {
5082            final PackageParser.Package p1 = mPackages.get(pkg1);
5083            final PackageParser.Package p2 = mPackages.get(pkg2);
5084            if (p1 == null || p1.mExtras == null
5085                    || p2 == null || p2.mExtras == null) {
5086                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5087            }
5088            return compareSignatures(p1.mSignatures, p2.mSignatures);
5089        }
5090    }
5091
5092    @Override
5093    public int checkUidSignatures(int uid1, int uid2) {
5094        // Map to base uids.
5095        uid1 = UserHandle.getAppId(uid1);
5096        uid2 = UserHandle.getAppId(uid2);
5097        // reader
5098        synchronized (mPackages) {
5099            Signature[] s1;
5100            Signature[] s2;
5101            Object obj = mSettings.getUserIdLPr(uid1);
5102            if (obj != null) {
5103                if (obj instanceof SharedUserSetting) {
5104                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5105                } else if (obj instanceof PackageSetting) {
5106                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5107                } else {
5108                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5109                }
5110            } else {
5111                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5112            }
5113            obj = mSettings.getUserIdLPr(uid2);
5114            if (obj != null) {
5115                if (obj instanceof SharedUserSetting) {
5116                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5117                } else if (obj instanceof PackageSetting) {
5118                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5119                } else {
5120                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5121                }
5122            } else {
5123                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5124            }
5125            return compareSignatures(s1, s2);
5126        }
5127    }
5128
5129    /**
5130     * This method should typically only be used when granting or revoking
5131     * permissions, since the app may immediately restart after this call.
5132     * <p>
5133     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5134     * guard your work against the app being relaunched.
5135     */
5136    private void killUid(int appId, int userId, String reason) {
5137        final long identity = Binder.clearCallingIdentity();
5138        try {
5139            IActivityManager am = ActivityManager.getService();
5140            if (am != null) {
5141                try {
5142                    am.killUid(appId, userId, reason);
5143                } catch (RemoteException e) {
5144                    /* ignore - same process */
5145                }
5146            }
5147        } finally {
5148            Binder.restoreCallingIdentity(identity);
5149        }
5150    }
5151
5152    /**
5153     * Compares two sets of signatures. Returns:
5154     * <br />
5155     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5156     * <br />
5157     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5158     * <br />
5159     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5160     * <br />
5161     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5162     * <br />
5163     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5164     */
5165    static int compareSignatures(Signature[] s1, Signature[] s2) {
5166        if (s1 == null) {
5167            return s2 == null
5168                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5169                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5170        }
5171
5172        if (s2 == null) {
5173            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5174        }
5175
5176        if (s1.length != s2.length) {
5177            return PackageManager.SIGNATURE_NO_MATCH;
5178        }
5179
5180        // Since both signature sets are of size 1, we can compare without HashSets.
5181        if (s1.length == 1) {
5182            return s1[0].equals(s2[0]) ?
5183                    PackageManager.SIGNATURE_MATCH :
5184                    PackageManager.SIGNATURE_NO_MATCH;
5185        }
5186
5187        ArraySet<Signature> set1 = new ArraySet<Signature>();
5188        for (Signature sig : s1) {
5189            set1.add(sig);
5190        }
5191        ArraySet<Signature> set2 = new ArraySet<Signature>();
5192        for (Signature sig : s2) {
5193            set2.add(sig);
5194        }
5195        // Make sure s2 contains all signatures in s1.
5196        if (set1.equals(set2)) {
5197            return PackageManager.SIGNATURE_MATCH;
5198        }
5199        return PackageManager.SIGNATURE_NO_MATCH;
5200    }
5201
5202    /**
5203     * If the database version for this type of package (internal storage or
5204     * external storage) is less than the version where package signatures
5205     * were updated, return true.
5206     */
5207    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5208        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5209        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5210    }
5211
5212    /**
5213     * Used for backward compatibility to make sure any packages with
5214     * certificate chains get upgraded to the new style. {@code existingSigs}
5215     * will be in the old format (since they were stored on disk from before the
5216     * system upgrade) and {@code scannedSigs} will be in the newer format.
5217     */
5218    private int compareSignaturesCompat(PackageSignatures existingSigs,
5219            PackageParser.Package scannedPkg) {
5220        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5221            return PackageManager.SIGNATURE_NO_MATCH;
5222        }
5223
5224        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5225        for (Signature sig : existingSigs.mSignatures) {
5226            existingSet.add(sig);
5227        }
5228        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5229        for (Signature sig : scannedPkg.mSignatures) {
5230            try {
5231                Signature[] chainSignatures = sig.getChainSignatures();
5232                for (Signature chainSig : chainSignatures) {
5233                    scannedCompatSet.add(chainSig);
5234                }
5235            } catch (CertificateEncodingException e) {
5236                scannedCompatSet.add(sig);
5237            }
5238        }
5239        /*
5240         * Make sure the expanded scanned set contains all signatures in the
5241         * existing one.
5242         */
5243        if (scannedCompatSet.equals(existingSet)) {
5244            // Migrate the old signatures to the new scheme.
5245            existingSigs.assignSignatures(scannedPkg.mSignatures);
5246            // The new KeySets will be re-added later in the scanning process.
5247            synchronized (mPackages) {
5248                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5249            }
5250            return PackageManager.SIGNATURE_MATCH;
5251        }
5252        return PackageManager.SIGNATURE_NO_MATCH;
5253    }
5254
5255    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5256        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5257        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5258    }
5259
5260    private int compareSignaturesRecover(PackageSignatures existingSigs,
5261            PackageParser.Package scannedPkg) {
5262        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5263            return PackageManager.SIGNATURE_NO_MATCH;
5264        }
5265
5266        String msg = null;
5267        try {
5268            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5269                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5270                        + scannedPkg.packageName);
5271                return PackageManager.SIGNATURE_MATCH;
5272            }
5273        } catch (CertificateException e) {
5274            msg = e.getMessage();
5275        }
5276
5277        logCriticalInfo(Log.INFO,
5278                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5279        return PackageManager.SIGNATURE_NO_MATCH;
5280    }
5281
5282    @Override
5283    public List<String> getAllPackages() {
5284        synchronized (mPackages) {
5285            return new ArrayList<String>(mPackages.keySet());
5286        }
5287    }
5288
5289    @Override
5290    public String[] getPackagesForUid(int uid) {
5291        final int userId = UserHandle.getUserId(uid);
5292        uid = UserHandle.getAppId(uid);
5293        // reader
5294        synchronized (mPackages) {
5295            Object obj = mSettings.getUserIdLPr(uid);
5296            if (obj instanceof SharedUserSetting) {
5297                final SharedUserSetting sus = (SharedUserSetting) obj;
5298                final int N = sus.packages.size();
5299                String[] res = new String[N];
5300                final Iterator<PackageSetting> it = sus.packages.iterator();
5301                int i = 0;
5302                while (it.hasNext()) {
5303                    PackageSetting ps = it.next();
5304                    if (ps.getInstalled(userId)) {
5305                        res[i++] = ps.name;
5306                    } else {
5307                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5308                    }
5309                }
5310                return res;
5311            } else if (obj instanceof PackageSetting) {
5312                final PackageSetting ps = (PackageSetting) obj;
5313                if (ps.getInstalled(userId)) {
5314                    return new String[]{ps.name};
5315                }
5316            }
5317        }
5318        return null;
5319    }
5320
5321    @Override
5322    public String getNameForUid(int uid) {
5323        // reader
5324        synchronized (mPackages) {
5325            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5326            if (obj instanceof SharedUserSetting) {
5327                final SharedUserSetting sus = (SharedUserSetting) obj;
5328                return sus.name + ":" + sus.userId;
5329            } else if (obj instanceof PackageSetting) {
5330                final PackageSetting ps = (PackageSetting) obj;
5331                return ps.name;
5332            }
5333        }
5334        return null;
5335    }
5336
5337    @Override
5338    public int getUidForSharedUser(String sharedUserName) {
5339        if(sharedUserName == null) {
5340            return -1;
5341        }
5342        // reader
5343        synchronized (mPackages) {
5344            SharedUserSetting suid;
5345            try {
5346                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5347                if (suid != null) {
5348                    return suid.userId;
5349                }
5350            } catch (PackageManagerException ignore) {
5351                // can't happen, but, still need to catch it
5352            }
5353            return -1;
5354        }
5355    }
5356
5357    @Override
5358    public int getFlagsForUid(int uid) {
5359        synchronized (mPackages) {
5360            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5361            if (obj instanceof SharedUserSetting) {
5362                final SharedUserSetting sus = (SharedUserSetting) obj;
5363                return sus.pkgFlags;
5364            } else if (obj instanceof PackageSetting) {
5365                final PackageSetting ps = (PackageSetting) obj;
5366                return ps.pkgFlags;
5367            }
5368        }
5369        return 0;
5370    }
5371
5372    @Override
5373    public int getPrivateFlagsForUid(int uid) {
5374        synchronized (mPackages) {
5375            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5376            if (obj instanceof SharedUserSetting) {
5377                final SharedUserSetting sus = (SharedUserSetting) obj;
5378                return sus.pkgPrivateFlags;
5379            } else if (obj instanceof PackageSetting) {
5380                final PackageSetting ps = (PackageSetting) obj;
5381                return ps.pkgPrivateFlags;
5382            }
5383        }
5384        return 0;
5385    }
5386
5387    @Override
5388    public boolean isUidPrivileged(int uid) {
5389        uid = UserHandle.getAppId(uid);
5390        // reader
5391        synchronized (mPackages) {
5392            Object obj = mSettings.getUserIdLPr(uid);
5393            if (obj instanceof SharedUserSetting) {
5394                final SharedUserSetting sus = (SharedUserSetting) obj;
5395                final Iterator<PackageSetting> it = sus.packages.iterator();
5396                while (it.hasNext()) {
5397                    if (it.next().isPrivileged()) {
5398                        return true;
5399                    }
5400                }
5401            } else if (obj instanceof PackageSetting) {
5402                final PackageSetting ps = (PackageSetting) obj;
5403                return ps.isPrivileged();
5404            }
5405        }
5406        return false;
5407    }
5408
5409    @Override
5410    public String[] getAppOpPermissionPackages(String permissionName) {
5411        synchronized (mPackages) {
5412            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5413            if (pkgs == null) {
5414                return null;
5415            }
5416            return pkgs.toArray(new String[pkgs.size()]);
5417        }
5418    }
5419
5420    @Override
5421    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5422            int flags, int userId) {
5423        try {
5424            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5425
5426            if (!sUserManager.exists(userId)) return null;
5427            flags = updateFlagsForResolve(flags, userId, intent);
5428            enforceCrossUserPermission(Binder.getCallingUid(), userId,
5429                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5430
5431            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5432            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5433                    flags, userId);
5434            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5435
5436            final ResolveInfo bestChoice =
5437                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5438            return bestChoice;
5439        } finally {
5440            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5441        }
5442    }
5443
5444    @Override
5445    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5446        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5447            throw new SecurityException(
5448                    "findPersistentPreferredActivity can only be run by the system");
5449        }
5450        if (!sUserManager.exists(userId)) {
5451            return null;
5452        }
5453        intent = updateIntentForResolve(intent);
5454        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5455        final int flags = updateFlagsForResolve(0, userId, intent);
5456        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5457                userId);
5458        synchronized (mPackages) {
5459            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5460                    userId);
5461        }
5462    }
5463
5464    @Override
5465    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5466            IntentFilter filter, int match, ComponentName activity) {
5467        final int userId = UserHandle.getCallingUserId();
5468        if (DEBUG_PREFERRED) {
5469            Log.v(TAG, "setLastChosenActivity intent=" + intent
5470                + " resolvedType=" + resolvedType
5471                + " flags=" + flags
5472                + " filter=" + filter
5473                + " match=" + match
5474                + " activity=" + activity);
5475            filter.dump(new PrintStreamPrinter(System.out), "    ");
5476        }
5477        intent.setComponent(null);
5478        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5479                userId);
5480        // Find any earlier preferred or last chosen entries and nuke them
5481        findPreferredActivity(intent, resolvedType,
5482                flags, query, 0, false, true, false, userId);
5483        // Add the new activity as the last chosen for this filter
5484        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5485                "Setting last chosen");
5486    }
5487
5488    @Override
5489    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5490        final int userId = UserHandle.getCallingUserId();
5491        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5492        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5493                userId);
5494        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5495                false, false, false, userId);
5496    }
5497
5498    private boolean isEphemeralDisabled() {
5499        // ephemeral apps have been disabled across the board
5500        if (DISABLE_EPHEMERAL_APPS) {
5501            return true;
5502        }
5503        // system isn't up yet; can't read settings, so, assume no ephemeral apps
5504        if (!mSystemReady) {
5505            return true;
5506        }
5507        // we can't get a content resolver until the system is ready; these checks must happen last
5508        final ContentResolver resolver = mContext.getContentResolver();
5509        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
5510            return true;
5511        }
5512        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
5513    }
5514
5515    private boolean isEphemeralAllowed(
5516            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5517            boolean skipPackageCheck) {
5518        // Short circuit and return early if possible.
5519        if (isEphemeralDisabled()) {
5520            return false;
5521        }
5522        final int callingUser = UserHandle.getCallingUserId();
5523        if (callingUser != UserHandle.USER_SYSTEM) {
5524            return false;
5525        }
5526        if (mEphemeralResolverConnection == null) {
5527            return false;
5528        }
5529        if (mEphemeralInstallerComponent == null) {
5530            return false;
5531        }
5532        if (intent.getComponent() != null) {
5533            return false;
5534        }
5535        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5536            return false;
5537        }
5538        if (!skipPackageCheck && intent.getPackage() != null) {
5539            return false;
5540        }
5541        final boolean isWebUri = hasWebURI(intent);
5542        if (!isWebUri || intent.getData().getHost() == null) {
5543            return false;
5544        }
5545        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5546        synchronized (mPackages) {
5547            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5548            for (int n = 0; n < count; n++) {
5549                ResolveInfo info = resolvedActivities.get(n);
5550                String packageName = info.activityInfo.packageName;
5551                PackageSetting ps = mSettings.mPackages.get(packageName);
5552                if (ps != null) {
5553                    // Try to get the status from User settings first
5554                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5555                    int status = (int) (packedStatus >> 32);
5556                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5557                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5558                        if (DEBUG_EPHEMERAL) {
5559                            Slog.v(TAG, "DENY ephemeral apps;"
5560                                + " pkg: " + packageName + ", status: " + status);
5561                        }
5562                        return false;
5563                    }
5564                }
5565            }
5566        }
5567        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5568        return true;
5569    }
5570
5571    private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
5572            Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage,
5573            int userId) {
5574        final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO,
5575                new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent,
5576                        callingPackage, userId));
5577        mHandler.sendMessage(msg);
5578    }
5579
5580    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5581            int flags, List<ResolveInfo> query, int userId) {
5582        if (query != null) {
5583            final int N = query.size();
5584            if (N == 1) {
5585                return query.get(0);
5586            } else if (N > 1) {
5587                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5588                // If there is more than one activity with the same priority,
5589                // then let the user decide between them.
5590                ResolveInfo r0 = query.get(0);
5591                ResolveInfo r1 = query.get(1);
5592                if (DEBUG_INTENT_MATCHING || debug) {
5593                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5594                            + r1.activityInfo.name + "=" + r1.priority);
5595                }
5596                // If the first activity has a higher priority, or a different
5597                // default, then it is always desirable to pick it.
5598                if (r0.priority != r1.priority
5599                        || r0.preferredOrder != r1.preferredOrder
5600                        || r0.isDefault != r1.isDefault) {
5601                    return query.get(0);
5602                }
5603                // If we have saved a preference for a preferred activity for
5604                // this Intent, use that.
5605                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5606                        flags, query, r0.priority, true, false, debug, userId);
5607                if (ri != null) {
5608                    return ri;
5609                }
5610                ri = new ResolveInfo(mResolveInfo);
5611                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5612                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5613                // If all of the options come from the same package, show the application's
5614                // label and icon instead of the generic resolver's.
5615                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5616                // and then throw away the ResolveInfo itself, meaning that the caller loses
5617                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5618                // a fallback for this case; we only set the target package's resources on
5619                // the ResolveInfo, not the ActivityInfo.
5620                final String intentPackage = intent.getPackage();
5621                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5622                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5623                    ri.resolvePackageName = intentPackage;
5624                    if (userNeedsBadging(userId)) {
5625                        ri.noResourceId = true;
5626                    } else {
5627                        ri.icon = appi.icon;
5628                    }
5629                    ri.iconResourceId = appi.icon;
5630                    ri.labelRes = appi.labelRes;
5631                }
5632                ri.activityInfo.applicationInfo = new ApplicationInfo(
5633                        ri.activityInfo.applicationInfo);
5634                if (userId != 0) {
5635                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5636                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5637                }
5638                // Make sure that the resolver is displayable in car mode
5639                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5640                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5641                return ri;
5642            }
5643        }
5644        return null;
5645    }
5646
5647    /**
5648     * Return true if the given list is not empty and all of its contents have
5649     * an activityInfo with the given package name.
5650     */
5651    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5652        if (ArrayUtils.isEmpty(list)) {
5653            return false;
5654        }
5655        for (int i = 0, N = list.size(); i < N; i++) {
5656            final ResolveInfo ri = list.get(i);
5657            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5658            if (ai == null || !packageName.equals(ai.packageName)) {
5659                return false;
5660            }
5661        }
5662        return true;
5663    }
5664
5665    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5666            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5667        final int N = query.size();
5668        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5669                .get(userId);
5670        // Get the list of persistent preferred activities that handle the intent
5671        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5672        List<PersistentPreferredActivity> pprefs = ppir != null
5673                ? ppir.queryIntent(intent, resolvedType,
5674                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5675                        (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
5676                        (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId)
5677                : null;
5678        if (pprefs != null && pprefs.size() > 0) {
5679            final int M = pprefs.size();
5680            for (int i=0; i<M; i++) {
5681                final PersistentPreferredActivity ppa = pprefs.get(i);
5682                if (DEBUG_PREFERRED || debug) {
5683                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5684                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5685                            + "\n  component=" + ppa.mComponent);
5686                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5687                }
5688                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5689                        flags | MATCH_DISABLED_COMPONENTS, userId);
5690                if (DEBUG_PREFERRED || debug) {
5691                    Slog.v(TAG, "Found persistent preferred activity:");
5692                    if (ai != null) {
5693                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5694                    } else {
5695                        Slog.v(TAG, "  null");
5696                    }
5697                }
5698                if (ai == null) {
5699                    // This previously registered persistent preferred activity
5700                    // component is no longer known. Ignore it and do NOT remove it.
5701                    continue;
5702                }
5703                for (int j=0; j<N; j++) {
5704                    final ResolveInfo ri = query.get(j);
5705                    if (!ri.activityInfo.applicationInfo.packageName
5706                            .equals(ai.applicationInfo.packageName)) {
5707                        continue;
5708                    }
5709                    if (!ri.activityInfo.name.equals(ai.name)) {
5710                        continue;
5711                    }
5712                    //  Found a persistent preference that can handle the intent.
5713                    if (DEBUG_PREFERRED || debug) {
5714                        Slog.v(TAG, "Returning persistent preferred activity: " +
5715                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5716                    }
5717                    return ri;
5718                }
5719            }
5720        }
5721        return null;
5722    }
5723
5724    // TODO: handle preferred activities missing while user has amnesia
5725    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5726            List<ResolveInfo> query, int priority, boolean always,
5727            boolean removeMatches, boolean debug, int userId) {
5728        if (!sUserManager.exists(userId)) return null;
5729        flags = updateFlagsForResolve(flags, userId, intent);
5730        intent = updateIntentForResolve(intent);
5731        // writer
5732        synchronized (mPackages) {
5733            // Try to find a matching persistent preferred activity.
5734            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5735                    debug, userId);
5736
5737            // If a persistent preferred activity matched, use it.
5738            if (pri != null) {
5739                return pri;
5740            }
5741
5742            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5743            // Get the list of preferred activities that handle the intent
5744            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5745            List<PreferredActivity> prefs = pir != null
5746                    ? pir.queryIntent(intent, resolvedType,
5747                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5748                            (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
5749                            (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId)
5750                    : null;
5751            if (prefs != null && prefs.size() > 0) {
5752                boolean changed = false;
5753                try {
5754                    // First figure out how good the original match set is.
5755                    // We will only allow preferred activities that came
5756                    // from the same match quality.
5757                    int match = 0;
5758
5759                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5760
5761                    final int N = query.size();
5762                    for (int j=0; j<N; j++) {
5763                        final ResolveInfo ri = query.get(j);
5764                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5765                                + ": 0x" + Integer.toHexString(match));
5766                        if (ri.match > match) {
5767                            match = ri.match;
5768                        }
5769                    }
5770
5771                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5772                            + Integer.toHexString(match));
5773
5774                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5775                    final int M = prefs.size();
5776                    for (int i=0; i<M; i++) {
5777                        final PreferredActivity pa = prefs.get(i);
5778                        if (DEBUG_PREFERRED || debug) {
5779                            Slog.v(TAG, "Checking PreferredActivity ds="
5780                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5781                                    + "\n  component=" + pa.mPref.mComponent);
5782                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5783                        }
5784                        if (pa.mPref.mMatch != match) {
5785                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5786                                    + Integer.toHexString(pa.mPref.mMatch));
5787                            continue;
5788                        }
5789                        // If it's not an "always" type preferred activity and that's what we're
5790                        // looking for, skip it.
5791                        if (always && !pa.mPref.mAlways) {
5792                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5793                            continue;
5794                        }
5795                        final ActivityInfo ai = getActivityInfo(
5796                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5797                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5798                                userId);
5799                        if (DEBUG_PREFERRED || debug) {
5800                            Slog.v(TAG, "Found preferred activity:");
5801                            if (ai != null) {
5802                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5803                            } else {
5804                                Slog.v(TAG, "  null");
5805                            }
5806                        }
5807                        if (ai == null) {
5808                            // This previously registered preferred activity
5809                            // component is no longer known.  Most likely an update
5810                            // to the app was installed and in the new version this
5811                            // component no longer exists.  Clean it up by removing
5812                            // it from the preferred activities list, and skip it.
5813                            Slog.w(TAG, "Removing dangling preferred activity: "
5814                                    + pa.mPref.mComponent);
5815                            pir.removeFilter(pa);
5816                            changed = true;
5817                            continue;
5818                        }
5819                        for (int j=0; j<N; j++) {
5820                            final ResolveInfo ri = query.get(j);
5821                            if (!ri.activityInfo.applicationInfo.packageName
5822                                    .equals(ai.applicationInfo.packageName)) {
5823                                continue;
5824                            }
5825                            if (!ri.activityInfo.name.equals(ai.name)) {
5826                                continue;
5827                            }
5828
5829                            if (removeMatches) {
5830                                pir.removeFilter(pa);
5831                                changed = true;
5832                                if (DEBUG_PREFERRED) {
5833                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5834                                }
5835                                break;
5836                            }
5837
5838                            // Okay we found a previously set preferred or last chosen app.
5839                            // If the result set is different from when this
5840                            // was created, we need to clear it and re-ask the
5841                            // user their preference, if we're looking for an "always" type entry.
5842                            if (always && !pa.mPref.sameSet(query)) {
5843                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5844                                        + intent + " type " + resolvedType);
5845                                if (DEBUG_PREFERRED) {
5846                                    Slog.v(TAG, "Removing preferred activity since set changed "
5847                                            + pa.mPref.mComponent);
5848                                }
5849                                pir.removeFilter(pa);
5850                                // Re-add the filter as a "last chosen" entry (!always)
5851                                PreferredActivity lastChosen = new PreferredActivity(
5852                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5853                                pir.addFilter(lastChosen);
5854                                changed = true;
5855                                return null;
5856                            }
5857
5858                            // Yay! Either the set matched or we're looking for the last chosen
5859                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5860                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5861                            return ri;
5862                        }
5863                    }
5864                } finally {
5865                    if (changed) {
5866                        if (DEBUG_PREFERRED) {
5867                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5868                        }
5869                        scheduleWritePackageRestrictionsLocked(userId);
5870                    }
5871                }
5872            }
5873        }
5874        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5875        return null;
5876    }
5877
5878    /*
5879     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5880     */
5881    @Override
5882    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5883            int targetUserId) {
5884        mContext.enforceCallingOrSelfPermission(
5885                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5886        List<CrossProfileIntentFilter> matches =
5887                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5888        if (matches != null) {
5889            int size = matches.size();
5890            for (int i = 0; i < size; i++) {
5891                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5892            }
5893        }
5894        if (hasWebURI(intent)) {
5895            // cross-profile app linking works only towards the parent.
5896            final UserInfo parent = getProfileParent(sourceUserId);
5897            synchronized(mPackages) {
5898                int flags = updateFlagsForResolve(0, parent.id, intent);
5899                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5900                        intent, resolvedType, flags, sourceUserId, parent.id);
5901                return xpDomainInfo != null;
5902            }
5903        }
5904        return false;
5905    }
5906
5907    private UserInfo getProfileParent(int userId) {
5908        final long identity = Binder.clearCallingIdentity();
5909        try {
5910            return sUserManager.getProfileParent(userId);
5911        } finally {
5912            Binder.restoreCallingIdentity(identity);
5913        }
5914    }
5915
5916    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5917            String resolvedType, int userId) {
5918        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5919        if (resolver != null) {
5920            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/,
5921                    false /*visibleToEphemeral*/, false /*isInstant*/, userId);
5922        }
5923        return null;
5924    }
5925
5926    @Override
5927    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5928            String resolvedType, int flags, int userId) {
5929        try {
5930            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5931
5932            return new ParceledListSlice<>(
5933                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5934        } finally {
5935            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5936        }
5937    }
5938
5939    /**
5940     * Returns the package name of the calling Uid if it's an ephemeral app. If it isn't
5941     * ephemeral, returns {@code null}.
5942     */
5943    private String getEphemeralPackageName(int callingUid) {
5944        final int appId = UserHandle.getAppId(callingUid);
5945        synchronized (mPackages) {
5946            final Object obj = mSettings.getUserIdLPr(appId);
5947            if (obj instanceof PackageSetting) {
5948                final PackageSetting ps = (PackageSetting) obj;
5949                return ps.pkg.applicationInfo.isInstantApp() ? ps.pkg.packageName : null;
5950            }
5951        }
5952        return null;
5953    }
5954
5955    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5956            String resolvedType, int flags, int userId) {
5957        if (!sUserManager.exists(userId)) return Collections.emptyList();
5958        final String ephemeralPkgName = getEphemeralPackageName(Binder.getCallingUid());
5959        flags = updateFlagsForResolve(flags, userId, intent);
5960        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5961                false /* requireFullPermission */, false /* checkShell */,
5962                "query intent activities");
5963        ComponentName comp = intent.getComponent();
5964        if (comp == null) {
5965            if (intent.getSelector() != null) {
5966                intent = intent.getSelector();
5967                comp = intent.getComponent();
5968            }
5969        }
5970
5971        if (comp != null) {
5972            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5973            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5974            if (ai != null) {
5975                // When specifying an explicit component, we prevent the activity from being
5976                // used when either 1) the calling package is normal and the activity is within
5977                // an ephemeral application or 2) the calling package is ephemeral and the
5978                // activity is not visible to ephemeral applications.
5979                boolean matchEphemeral =
5980                        (flags & PackageManager.MATCH_EPHEMERAL) != 0;
5981                boolean ephemeralVisibleOnly =
5982                        (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
5983                boolean blockResolution =
5984                        (!matchEphemeral && ephemeralPkgName == null
5985                                && (ai.applicationInfo.privateFlags
5986                                        & ApplicationInfo.PRIVATE_FLAG_EPHEMERAL) != 0)
5987                        || (ephemeralVisibleOnly && ephemeralPkgName != null
5988                                && (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0);
5989                if (!blockResolution) {
5990                    final ResolveInfo ri = new ResolveInfo();
5991                    ri.activityInfo = ai;
5992                    list.add(ri);
5993                }
5994            }
5995            return list;
5996        }
5997
5998        // reader
5999        boolean sortResult = false;
6000        boolean addEphemeral = false;
6001        List<ResolveInfo> result;
6002        final String pkgName = intent.getPackage();
6003        synchronized (mPackages) {
6004            if (pkgName == null) {
6005                List<CrossProfileIntentFilter> matchingFilters =
6006                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6007                // Check for results that need to skip the current profile.
6008                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6009                        resolvedType, flags, userId);
6010                if (xpResolveInfo != null) {
6011                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6012                    xpResult.add(xpResolveInfo);
6013                    return filterForEphemeral(
6014                            filterIfNotSystemUser(xpResult, userId), ephemeralPkgName);
6015                }
6016
6017                // Check for results in the current profile.
6018                result = filterIfNotSystemUser(mActivities.queryIntent(
6019                        intent, resolvedType, flags, userId), userId);
6020                addEphemeral =
6021                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
6022
6023                // Check for cross profile results.
6024                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6025                xpResolveInfo = queryCrossProfileIntents(
6026                        matchingFilters, intent, resolvedType, flags, userId,
6027                        hasNonNegativePriorityResult);
6028                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6029                    boolean isVisibleToUser = filterIfNotSystemUser(
6030                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6031                    if (isVisibleToUser) {
6032                        result.add(xpResolveInfo);
6033                        sortResult = true;
6034                    }
6035                }
6036                if (hasWebURI(intent)) {
6037                    CrossProfileDomainInfo xpDomainInfo = null;
6038                    final UserInfo parent = getProfileParent(userId);
6039                    if (parent != null) {
6040                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6041                                flags, userId, parent.id);
6042                    }
6043                    if (xpDomainInfo != null) {
6044                        if (xpResolveInfo != null) {
6045                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6046                            // in the result.
6047                            result.remove(xpResolveInfo);
6048                        }
6049                        if (result.size() == 0 && !addEphemeral) {
6050                            // No result in current profile, but found candidate in parent user.
6051                            // And we are not going to add emphemeral app, so we can return the
6052                            // result straight away.
6053                            result.add(xpDomainInfo.resolveInfo);
6054                            return filterForEphemeral(result, ephemeralPkgName);
6055                        }
6056                    } else if (result.size() <= 1 && !addEphemeral) {
6057                        // No result in parent user and <= 1 result in current profile, and we
6058                        // are not going to add emphemeral app, so we can return the result without
6059                        // further processing.
6060                        return filterForEphemeral(result, ephemeralPkgName);
6061                    }
6062                    // We have more than one candidate (combining results from current and parent
6063                    // profile), so we need filtering and sorting.
6064                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6065                            intent, flags, result, xpDomainInfo, userId);
6066                    sortResult = true;
6067                }
6068            } else {
6069                final PackageParser.Package pkg = mPackages.get(pkgName);
6070                if (pkg != null) {
6071                    result = filterForEphemeral(filterIfNotSystemUser(
6072                            mActivities.queryIntentForPackage(
6073                                    intent, resolvedType, flags, pkg.activities, userId),
6074                            userId), ephemeralPkgName);
6075                } else {
6076                    // the caller wants to resolve for a particular package; however, there
6077                    // were no installed results, so, try to find an ephemeral result
6078                    addEphemeral = isEphemeralAllowed(
6079                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
6080                    result = new ArrayList<ResolveInfo>();
6081                }
6082            }
6083        }
6084        if (addEphemeral) {
6085            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6086            final EphemeralRequest requestObject = new EphemeralRequest(
6087                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
6088                    null /*launchIntent*/, null /*callingPackage*/, userId);
6089            final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne(
6090                    mContext, mEphemeralResolverConnection, requestObject);
6091            if (intentInfo != null) {
6092                if (DEBUG_EPHEMERAL) {
6093                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6094                }
6095                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
6096                ephemeralInstaller.ephemeralResponse = intentInfo;
6097                // make sure this resolver is the default
6098                ephemeralInstaller.isDefault = true;
6099                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6100                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6101                // add a non-generic filter
6102                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6103                ephemeralInstaller.filter.addDataPath(
6104                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6105                result.add(ephemeralInstaller);
6106            }
6107            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6108        }
6109        if (sortResult) {
6110            Collections.sort(result, mResolvePrioritySorter);
6111        }
6112        return filterForEphemeral(result, ephemeralPkgName);
6113    }
6114
6115    private static class CrossProfileDomainInfo {
6116        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6117        ResolveInfo resolveInfo;
6118        /* Best domain verification status of the activities found in the other profile */
6119        int bestDomainVerificationStatus;
6120    }
6121
6122    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6123            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6124        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6125                sourceUserId)) {
6126            return null;
6127        }
6128        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6129                resolvedType, flags, parentUserId);
6130
6131        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6132            return null;
6133        }
6134        CrossProfileDomainInfo result = null;
6135        int size = resultTargetUser.size();
6136        for (int i = 0; i < size; i++) {
6137            ResolveInfo riTargetUser = resultTargetUser.get(i);
6138            // Intent filter verification is only for filters that specify a host. So don't return
6139            // those that handle all web uris.
6140            if (riTargetUser.handleAllWebDataURI) {
6141                continue;
6142            }
6143            String packageName = riTargetUser.activityInfo.packageName;
6144            PackageSetting ps = mSettings.mPackages.get(packageName);
6145            if (ps == null) {
6146                continue;
6147            }
6148            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6149            int status = (int)(verificationState >> 32);
6150            if (result == null) {
6151                result = new CrossProfileDomainInfo();
6152                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6153                        sourceUserId, parentUserId);
6154                result.bestDomainVerificationStatus = status;
6155            } else {
6156                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6157                        result.bestDomainVerificationStatus);
6158            }
6159        }
6160        // Don't consider matches with status NEVER across profiles.
6161        if (result != null && result.bestDomainVerificationStatus
6162                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6163            return null;
6164        }
6165        return result;
6166    }
6167
6168    /**
6169     * Verification statuses are ordered from the worse to the best, except for
6170     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6171     */
6172    private int bestDomainVerificationStatus(int status1, int status2) {
6173        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6174            return status2;
6175        }
6176        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6177            return status1;
6178        }
6179        return (int) MathUtils.max(status1, status2);
6180    }
6181
6182    private boolean isUserEnabled(int userId) {
6183        long callingId = Binder.clearCallingIdentity();
6184        try {
6185            UserInfo userInfo = sUserManager.getUserInfo(userId);
6186            return userInfo != null && userInfo.isEnabled();
6187        } finally {
6188            Binder.restoreCallingIdentity(callingId);
6189        }
6190    }
6191
6192    /**
6193     * Filter out activities with systemUserOnly flag set, when current user is not System.
6194     *
6195     * @return filtered list
6196     */
6197    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6198        if (userId == UserHandle.USER_SYSTEM) {
6199            return resolveInfos;
6200        }
6201        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6202            ResolveInfo info = resolveInfos.get(i);
6203            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6204                resolveInfos.remove(i);
6205            }
6206        }
6207        return resolveInfos;
6208    }
6209
6210    /**
6211     * Filters out ephemeral activities.
6212     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6213     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6214     *
6215     * @param resolveInfos The pre-filtered list of resolved activities
6216     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6217     *          is performed.
6218     * @return A filtered list of resolved activities.
6219     */
6220    private List<ResolveInfo> filterForEphemeral(List<ResolveInfo> resolveInfos,
6221            String ephemeralPkgName) {
6222        if (ephemeralPkgName == null) {
6223            return resolveInfos;
6224        }
6225        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6226            ResolveInfo info = resolveInfos.get(i);
6227            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6228            // allow activities that are defined in the provided package
6229            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6230                continue;
6231            }
6232            // allow activities that have been explicitly exposed to ephemeral apps
6233            if (!isEphemeralApp
6234                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
6235                continue;
6236            }
6237            resolveInfos.remove(i);
6238        }
6239        return resolveInfos;
6240    }
6241
6242    /**
6243     * @param resolveInfos list of resolve infos in descending priority order
6244     * @return if the list contains a resolve info with non-negative priority
6245     */
6246    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6247        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6248    }
6249
6250    private static boolean hasWebURI(Intent intent) {
6251        if (intent.getData() == null) {
6252            return false;
6253        }
6254        final String scheme = intent.getScheme();
6255        if (TextUtils.isEmpty(scheme)) {
6256            return false;
6257        }
6258        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6259    }
6260
6261    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6262            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6263            int userId) {
6264        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6265
6266        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6267            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6268                    candidates.size());
6269        }
6270
6271        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6272        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6273        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6274        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6275        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6276        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6277
6278        synchronized (mPackages) {
6279            final int count = candidates.size();
6280            // First, try to use linked apps. Partition the candidates into four lists:
6281            // one for the final results, one for the "do not use ever", one for "undefined status"
6282            // and finally one for "browser app type".
6283            for (int n=0; n<count; n++) {
6284                ResolveInfo info = candidates.get(n);
6285                String packageName = info.activityInfo.packageName;
6286                PackageSetting ps = mSettings.mPackages.get(packageName);
6287                if (ps != null) {
6288                    // Add to the special match all list (Browser use case)
6289                    if (info.handleAllWebDataURI) {
6290                        matchAllList.add(info);
6291                        continue;
6292                    }
6293                    // Try to get the status from User settings first
6294                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6295                    int status = (int)(packedStatus >> 32);
6296                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6297                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6298                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6299                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6300                                    + " : linkgen=" + linkGeneration);
6301                        }
6302                        // Use link-enabled generation as preferredOrder, i.e.
6303                        // prefer newly-enabled over earlier-enabled.
6304                        info.preferredOrder = linkGeneration;
6305                        alwaysList.add(info);
6306                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6307                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6308                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6309                        }
6310                        neverList.add(info);
6311                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6312                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6313                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6314                        }
6315                        alwaysAskList.add(info);
6316                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6317                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6318                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6319                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6320                        }
6321                        undefinedList.add(info);
6322                    }
6323                }
6324            }
6325
6326            // We'll want to include browser possibilities in a few cases
6327            boolean includeBrowser = false;
6328
6329            // First try to add the "always" resolution(s) for the current user, if any
6330            if (alwaysList.size() > 0) {
6331                result.addAll(alwaysList);
6332            } else {
6333                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6334                result.addAll(undefinedList);
6335                // Maybe add one for the other profile.
6336                if (xpDomainInfo != null && (
6337                        xpDomainInfo.bestDomainVerificationStatus
6338                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6339                    result.add(xpDomainInfo.resolveInfo);
6340                }
6341                includeBrowser = true;
6342            }
6343
6344            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6345            // If there were 'always' entries their preferred order has been set, so we also
6346            // back that off to make the alternatives equivalent
6347            if (alwaysAskList.size() > 0) {
6348                for (ResolveInfo i : result) {
6349                    i.preferredOrder = 0;
6350                }
6351                result.addAll(alwaysAskList);
6352                includeBrowser = true;
6353            }
6354
6355            if (includeBrowser) {
6356                // Also add browsers (all of them or only the default one)
6357                if (DEBUG_DOMAIN_VERIFICATION) {
6358                    Slog.v(TAG, "   ...including browsers in candidate set");
6359                }
6360                if ((matchFlags & MATCH_ALL) != 0) {
6361                    result.addAll(matchAllList);
6362                } else {
6363                    // Browser/generic handling case.  If there's a default browser, go straight
6364                    // to that (but only if there is no other higher-priority match).
6365                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6366                    int maxMatchPrio = 0;
6367                    ResolveInfo defaultBrowserMatch = null;
6368                    final int numCandidates = matchAllList.size();
6369                    for (int n = 0; n < numCandidates; n++) {
6370                        ResolveInfo info = matchAllList.get(n);
6371                        // track the highest overall match priority...
6372                        if (info.priority > maxMatchPrio) {
6373                            maxMatchPrio = info.priority;
6374                        }
6375                        // ...and the highest-priority default browser match
6376                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6377                            if (defaultBrowserMatch == null
6378                                    || (defaultBrowserMatch.priority < info.priority)) {
6379                                if (debug) {
6380                                    Slog.v(TAG, "Considering default browser match " + info);
6381                                }
6382                                defaultBrowserMatch = info;
6383                            }
6384                        }
6385                    }
6386                    if (defaultBrowserMatch != null
6387                            && defaultBrowserMatch.priority >= maxMatchPrio
6388                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6389                    {
6390                        if (debug) {
6391                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6392                        }
6393                        result.add(defaultBrowserMatch);
6394                    } else {
6395                        result.addAll(matchAllList);
6396                    }
6397                }
6398
6399                // If there is nothing selected, add all candidates and remove the ones that the user
6400                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6401                if (result.size() == 0) {
6402                    result.addAll(candidates);
6403                    result.removeAll(neverList);
6404                }
6405            }
6406        }
6407        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6408            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6409                    result.size());
6410            for (ResolveInfo info : result) {
6411                Slog.v(TAG, "  + " + info.activityInfo);
6412            }
6413        }
6414        return result;
6415    }
6416
6417    // Returns a packed value as a long:
6418    //
6419    // high 'int'-sized word: link status: undefined/ask/never/always.
6420    // low 'int'-sized word: relative priority among 'always' results.
6421    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6422        long result = ps.getDomainVerificationStatusForUser(userId);
6423        // if none available, get the master status
6424        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6425            if (ps.getIntentFilterVerificationInfo() != null) {
6426                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6427            }
6428        }
6429        return result;
6430    }
6431
6432    private ResolveInfo querySkipCurrentProfileIntents(
6433            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6434            int flags, int sourceUserId) {
6435        if (matchingFilters != null) {
6436            int size = matchingFilters.size();
6437            for (int i = 0; i < size; i ++) {
6438                CrossProfileIntentFilter filter = matchingFilters.get(i);
6439                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6440                    // Checking if there are activities in the target user that can handle the
6441                    // intent.
6442                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6443                            resolvedType, flags, sourceUserId);
6444                    if (resolveInfo != null) {
6445                        return resolveInfo;
6446                    }
6447                }
6448            }
6449        }
6450        return null;
6451    }
6452
6453    // Return matching ResolveInfo in target user if any.
6454    private ResolveInfo queryCrossProfileIntents(
6455            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6456            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6457        if (matchingFilters != null) {
6458            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6459            // match the same intent. For performance reasons, it is better not to
6460            // run queryIntent twice for the same userId
6461            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6462            int size = matchingFilters.size();
6463            for (int i = 0; i < size; i++) {
6464                CrossProfileIntentFilter filter = matchingFilters.get(i);
6465                int targetUserId = filter.getTargetUserId();
6466                boolean skipCurrentProfile =
6467                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6468                boolean skipCurrentProfileIfNoMatchFound =
6469                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6470                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6471                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6472                    // Checking if there are activities in the target user that can handle the
6473                    // intent.
6474                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6475                            resolvedType, flags, sourceUserId);
6476                    if (resolveInfo != null) return resolveInfo;
6477                    alreadyTriedUserIds.put(targetUserId, true);
6478                }
6479            }
6480        }
6481        return null;
6482    }
6483
6484    /**
6485     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6486     * will forward the intent to the filter's target user.
6487     * Otherwise, returns null.
6488     */
6489    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6490            String resolvedType, int flags, int sourceUserId) {
6491        int targetUserId = filter.getTargetUserId();
6492        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6493                resolvedType, flags, targetUserId);
6494        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6495            // If all the matches in the target profile are suspended, return null.
6496            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6497                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6498                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6499                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6500                            targetUserId);
6501                }
6502            }
6503        }
6504        return null;
6505    }
6506
6507    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6508            int sourceUserId, int targetUserId) {
6509        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6510        long ident = Binder.clearCallingIdentity();
6511        boolean targetIsProfile;
6512        try {
6513            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6514        } finally {
6515            Binder.restoreCallingIdentity(ident);
6516        }
6517        String className;
6518        if (targetIsProfile) {
6519            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6520        } else {
6521            className = FORWARD_INTENT_TO_PARENT;
6522        }
6523        ComponentName forwardingActivityComponentName = new ComponentName(
6524                mAndroidApplication.packageName, className);
6525        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6526                sourceUserId);
6527        if (!targetIsProfile) {
6528            forwardingActivityInfo.showUserIcon = targetUserId;
6529            forwardingResolveInfo.noResourceId = true;
6530        }
6531        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6532        forwardingResolveInfo.priority = 0;
6533        forwardingResolveInfo.preferredOrder = 0;
6534        forwardingResolveInfo.match = 0;
6535        forwardingResolveInfo.isDefault = true;
6536        forwardingResolveInfo.filter = filter;
6537        forwardingResolveInfo.targetUserId = targetUserId;
6538        return forwardingResolveInfo;
6539    }
6540
6541    @Override
6542    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6543            Intent[] specifics, String[] specificTypes, Intent intent,
6544            String resolvedType, int flags, int userId) {
6545        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6546                specificTypes, intent, resolvedType, flags, userId));
6547    }
6548
6549    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6550            Intent[] specifics, String[] specificTypes, Intent intent,
6551            String resolvedType, int flags, int userId) {
6552        if (!sUserManager.exists(userId)) return Collections.emptyList();
6553        flags = updateFlagsForResolve(flags, userId, intent);
6554        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6555                false /* requireFullPermission */, false /* checkShell */,
6556                "query intent activity options");
6557        final String resultsAction = intent.getAction();
6558
6559        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6560                | PackageManager.GET_RESOLVED_FILTER, userId);
6561
6562        if (DEBUG_INTENT_MATCHING) {
6563            Log.v(TAG, "Query " + intent + ": " + results);
6564        }
6565
6566        int specificsPos = 0;
6567        int N;
6568
6569        // todo: note that the algorithm used here is O(N^2).  This
6570        // isn't a problem in our current environment, but if we start running
6571        // into situations where we have more than 5 or 10 matches then this
6572        // should probably be changed to something smarter...
6573
6574        // First we go through and resolve each of the specific items
6575        // that were supplied, taking care of removing any corresponding
6576        // duplicate items in the generic resolve list.
6577        if (specifics != null) {
6578            for (int i=0; i<specifics.length; i++) {
6579                final Intent sintent = specifics[i];
6580                if (sintent == null) {
6581                    continue;
6582                }
6583
6584                if (DEBUG_INTENT_MATCHING) {
6585                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6586                }
6587
6588                String action = sintent.getAction();
6589                if (resultsAction != null && resultsAction.equals(action)) {
6590                    // If this action was explicitly requested, then don't
6591                    // remove things that have it.
6592                    action = null;
6593                }
6594
6595                ResolveInfo ri = null;
6596                ActivityInfo ai = null;
6597
6598                ComponentName comp = sintent.getComponent();
6599                if (comp == null) {
6600                    ri = resolveIntent(
6601                        sintent,
6602                        specificTypes != null ? specificTypes[i] : null,
6603                            flags, userId);
6604                    if (ri == null) {
6605                        continue;
6606                    }
6607                    if (ri == mResolveInfo) {
6608                        // ACK!  Must do something better with this.
6609                    }
6610                    ai = ri.activityInfo;
6611                    comp = new ComponentName(ai.applicationInfo.packageName,
6612                            ai.name);
6613                } else {
6614                    ai = getActivityInfo(comp, flags, userId);
6615                    if (ai == null) {
6616                        continue;
6617                    }
6618                }
6619
6620                // Look for any generic query activities that are duplicates
6621                // of this specific one, and remove them from the results.
6622                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6623                N = results.size();
6624                int j;
6625                for (j=specificsPos; j<N; j++) {
6626                    ResolveInfo sri = results.get(j);
6627                    if ((sri.activityInfo.name.equals(comp.getClassName())
6628                            && sri.activityInfo.applicationInfo.packageName.equals(
6629                                    comp.getPackageName()))
6630                        || (action != null && sri.filter.matchAction(action))) {
6631                        results.remove(j);
6632                        if (DEBUG_INTENT_MATCHING) Log.v(
6633                            TAG, "Removing duplicate item from " + j
6634                            + " due to specific " + specificsPos);
6635                        if (ri == null) {
6636                            ri = sri;
6637                        }
6638                        j--;
6639                        N--;
6640                    }
6641                }
6642
6643                // Add this specific item to its proper place.
6644                if (ri == null) {
6645                    ri = new ResolveInfo();
6646                    ri.activityInfo = ai;
6647                }
6648                results.add(specificsPos, ri);
6649                ri.specificIndex = i;
6650                specificsPos++;
6651            }
6652        }
6653
6654        // Now we go through the remaining generic results and remove any
6655        // duplicate actions that are found here.
6656        N = results.size();
6657        for (int i=specificsPos; i<N-1; i++) {
6658            final ResolveInfo rii = results.get(i);
6659            if (rii.filter == null) {
6660                continue;
6661            }
6662
6663            // Iterate over all of the actions of this result's intent
6664            // filter...  typically this should be just one.
6665            final Iterator<String> it = rii.filter.actionsIterator();
6666            if (it == null) {
6667                continue;
6668            }
6669            while (it.hasNext()) {
6670                final String action = it.next();
6671                if (resultsAction != null && resultsAction.equals(action)) {
6672                    // If this action was explicitly requested, then don't
6673                    // remove things that have it.
6674                    continue;
6675                }
6676                for (int j=i+1; j<N; j++) {
6677                    final ResolveInfo rij = results.get(j);
6678                    if (rij.filter != null && rij.filter.hasAction(action)) {
6679                        results.remove(j);
6680                        if (DEBUG_INTENT_MATCHING) Log.v(
6681                            TAG, "Removing duplicate item from " + j
6682                            + " due to action " + action + " at " + i);
6683                        j--;
6684                        N--;
6685                    }
6686                }
6687            }
6688
6689            // If the caller didn't request filter information, drop it now
6690            // so we don't have to marshall/unmarshall it.
6691            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6692                rii.filter = null;
6693            }
6694        }
6695
6696        // Filter out the caller activity if so requested.
6697        if (caller != null) {
6698            N = results.size();
6699            for (int i=0; i<N; i++) {
6700                ActivityInfo ainfo = results.get(i).activityInfo;
6701                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6702                        && caller.getClassName().equals(ainfo.name)) {
6703                    results.remove(i);
6704                    break;
6705                }
6706            }
6707        }
6708
6709        // If the caller didn't request filter information,
6710        // drop them now so we don't have to
6711        // marshall/unmarshall it.
6712        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6713            N = results.size();
6714            for (int i=0; i<N; i++) {
6715                results.get(i).filter = null;
6716            }
6717        }
6718
6719        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6720        return results;
6721    }
6722
6723    @Override
6724    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6725            String resolvedType, int flags, int userId) {
6726        return new ParceledListSlice<>(
6727                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6728    }
6729
6730    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6731            String resolvedType, int flags, int userId) {
6732        if (!sUserManager.exists(userId)) return Collections.emptyList();
6733        flags = updateFlagsForResolve(flags, userId, intent);
6734        ComponentName comp = intent.getComponent();
6735        if (comp == null) {
6736            if (intent.getSelector() != null) {
6737                intent = intent.getSelector();
6738                comp = intent.getComponent();
6739            }
6740        }
6741        if (comp != null) {
6742            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6743            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6744            if (ai != null) {
6745                ResolveInfo ri = new ResolveInfo();
6746                ri.activityInfo = ai;
6747                list.add(ri);
6748            }
6749            return list;
6750        }
6751
6752        // reader
6753        synchronized (mPackages) {
6754            String pkgName = intent.getPackage();
6755            if (pkgName == null) {
6756                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6757            }
6758            final PackageParser.Package pkg = mPackages.get(pkgName);
6759            if (pkg != null) {
6760                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6761                        userId);
6762            }
6763            return Collections.emptyList();
6764        }
6765    }
6766
6767    @Override
6768    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6769        if (!sUserManager.exists(userId)) return null;
6770        flags = updateFlagsForResolve(flags, userId, intent);
6771        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6772        if (query != null) {
6773            if (query.size() >= 1) {
6774                // If there is more than one service with the same priority,
6775                // just arbitrarily pick the first one.
6776                return query.get(0);
6777            }
6778        }
6779        return null;
6780    }
6781
6782    @Override
6783    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6784            String resolvedType, int flags, int userId) {
6785        return new ParceledListSlice<>(
6786                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6787    }
6788
6789    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6790            String resolvedType, int flags, int userId) {
6791        if (!sUserManager.exists(userId)) return Collections.emptyList();
6792        flags = updateFlagsForResolve(flags, userId, intent);
6793        ComponentName comp = intent.getComponent();
6794        if (comp == null) {
6795            if (intent.getSelector() != null) {
6796                intent = intent.getSelector();
6797                comp = intent.getComponent();
6798            }
6799        }
6800        if (comp != null) {
6801            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6802            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6803            if (si != null) {
6804                final ResolveInfo ri = new ResolveInfo();
6805                ri.serviceInfo = si;
6806                list.add(ri);
6807            }
6808            return list;
6809        }
6810
6811        // reader
6812        synchronized (mPackages) {
6813            String pkgName = intent.getPackage();
6814            if (pkgName == null) {
6815                return mServices.queryIntent(intent, resolvedType, flags, userId);
6816            }
6817            final PackageParser.Package pkg = mPackages.get(pkgName);
6818            if (pkg != null) {
6819                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6820                        userId);
6821            }
6822            return Collections.emptyList();
6823        }
6824    }
6825
6826    @Override
6827    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6828            String resolvedType, int flags, int userId) {
6829        return new ParceledListSlice<>(
6830                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6831    }
6832
6833    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6834            Intent intent, String resolvedType, int flags, int userId) {
6835        if (!sUserManager.exists(userId)) return Collections.emptyList();
6836        flags = updateFlagsForResolve(flags, userId, intent);
6837        ComponentName comp = intent.getComponent();
6838        if (comp == null) {
6839            if (intent.getSelector() != null) {
6840                intent = intent.getSelector();
6841                comp = intent.getComponent();
6842            }
6843        }
6844        if (comp != null) {
6845            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6846            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6847            if (pi != null) {
6848                final ResolveInfo ri = new ResolveInfo();
6849                ri.providerInfo = pi;
6850                list.add(ri);
6851            }
6852            return list;
6853        }
6854
6855        // reader
6856        synchronized (mPackages) {
6857            String pkgName = intent.getPackage();
6858            if (pkgName == null) {
6859                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6860            }
6861            final PackageParser.Package pkg = mPackages.get(pkgName);
6862            if (pkg != null) {
6863                return mProviders.queryIntentForPackage(
6864                        intent, resolvedType, flags, pkg.providers, userId);
6865            }
6866            return Collections.emptyList();
6867        }
6868    }
6869
6870    @Override
6871    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6872        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6873        flags = updateFlagsForPackage(flags, userId, null);
6874        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6875        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6876                true /* requireFullPermission */, false /* checkShell */,
6877                "get installed packages");
6878
6879        // writer
6880        synchronized (mPackages) {
6881            ArrayList<PackageInfo> list;
6882            if (listUninstalled) {
6883                list = new ArrayList<>(mSettings.mPackages.size());
6884                for (PackageSetting ps : mSettings.mPackages.values()) {
6885                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
6886                        continue;
6887                    }
6888                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
6889                    if (pi != null) {
6890                        list.add(pi);
6891                    }
6892                }
6893            } else {
6894                list = new ArrayList<>(mPackages.size());
6895                for (PackageParser.Package p : mPackages.values()) {
6896                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
6897                            Binder.getCallingUid(), userId)) {
6898                        continue;
6899                    }
6900                    final PackageInfo pi = generatePackageInfo((PackageSetting)
6901                            p.mExtras, flags, userId);
6902                    if (pi != null) {
6903                        list.add(pi);
6904                    }
6905                }
6906            }
6907
6908            return new ParceledListSlice<>(list);
6909        }
6910    }
6911
6912    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6913            String[] permissions, boolean[] tmp, int flags, int userId) {
6914        int numMatch = 0;
6915        final PermissionsState permissionsState = ps.getPermissionsState();
6916        for (int i=0; i<permissions.length; i++) {
6917            final String permission = permissions[i];
6918            if (permissionsState.hasPermission(permission, userId)) {
6919                tmp[i] = true;
6920                numMatch++;
6921            } else {
6922                tmp[i] = false;
6923            }
6924        }
6925        if (numMatch == 0) {
6926            return;
6927        }
6928        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
6929
6930        // The above might return null in cases of uninstalled apps or install-state
6931        // skew across users/profiles.
6932        if (pi != null) {
6933            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6934                if (numMatch == permissions.length) {
6935                    pi.requestedPermissions = permissions;
6936                } else {
6937                    pi.requestedPermissions = new String[numMatch];
6938                    numMatch = 0;
6939                    for (int i=0; i<permissions.length; i++) {
6940                        if (tmp[i]) {
6941                            pi.requestedPermissions[numMatch] = permissions[i];
6942                            numMatch++;
6943                        }
6944                    }
6945                }
6946            }
6947            list.add(pi);
6948        }
6949    }
6950
6951    @Override
6952    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6953            String[] permissions, int flags, int userId) {
6954        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6955        flags = updateFlagsForPackage(flags, userId, permissions);
6956        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6957                true /* requireFullPermission */, false /* checkShell */,
6958                "get packages holding permissions");
6959        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6960
6961        // writer
6962        synchronized (mPackages) {
6963            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6964            boolean[] tmpBools = new boolean[permissions.length];
6965            if (listUninstalled) {
6966                for (PackageSetting ps : mSettings.mPackages.values()) {
6967                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6968                            userId);
6969                }
6970            } else {
6971                for (PackageParser.Package pkg : mPackages.values()) {
6972                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6973                    if (ps != null) {
6974                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6975                                userId);
6976                    }
6977                }
6978            }
6979
6980            return new ParceledListSlice<PackageInfo>(list);
6981        }
6982    }
6983
6984    @Override
6985    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6986        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6987        flags = updateFlagsForApplication(flags, userId, null);
6988        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6989
6990        // writer
6991        synchronized (mPackages) {
6992            ArrayList<ApplicationInfo> list;
6993            if (listUninstalled) {
6994                list = new ArrayList<>(mSettings.mPackages.size());
6995                for (PackageSetting ps : mSettings.mPackages.values()) {
6996                    ApplicationInfo ai;
6997                    int effectiveFlags = flags;
6998                    if (ps.isSystem()) {
6999                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7000                    }
7001                    if (ps.pkg != null) {
7002                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7003                            continue;
7004                        }
7005                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7006                                ps.readUserState(userId), userId);
7007                        if (ai != null) {
7008                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7009                        }
7010                    } else {
7011                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7012                        // and already converts to externally visible package name
7013                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7014                                Binder.getCallingUid(), effectiveFlags, userId);
7015                    }
7016                    if (ai != null) {
7017                        list.add(ai);
7018                    }
7019                }
7020            } else {
7021                list = new ArrayList<>(mPackages.size());
7022                for (PackageParser.Package p : mPackages.values()) {
7023                    if (p.mExtras != null) {
7024                        PackageSetting ps = (PackageSetting) p.mExtras;
7025                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7026                            continue;
7027                        }
7028                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7029                                ps.readUserState(userId), userId);
7030                        if (ai != null) {
7031                            ai.packageName = resolveExternalPackageNameLPr(p);
7032                            list.add(ai);
7033                        }
7034                    }
7035                }
7036            }
7037
7038            return new ParceledListSlice<>(list);
7039        }
7040    }
7041
7042    @Override
7043    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7044        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7045            return null;
7046        }
7047
7048        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7049                "getEphemeralApplications");
7050        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7051                true /* requireFullPermission */, false /* checkShell */,
7052                "getEphemeralApplications");
7053        synchronized (mPackages) {
7054            List<InstantAppInfo> instantApps = mInstantAppRegistry
7055                    .getInstantAppsLPr(userId);
7056            if (instantApps != null) {
7057                return new ParceledListSlice<>(instantApps);
7058            }
7059        }
7060        return null;
7061    }
7062
7063    @Override
7064    public boolean isInstantApp(String packageName, int userId) {
7065        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7066                true /* requireFullPermission */, false /* checkShell */,
7067                "isInstantApp");
7068        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7069            return false;
7070        }
7071
7072        if (!isCallerSameApp(packageName)) {
7073            return false;
7074        }
7075        synchronized (mPackages) {
7076            PackageParser.Package pkg = mPackages.get(packageName);
7077            if (pkg != null) {
7078                return pkg.applicationInfo.isInstantApp();
7079            }
7080        }
7081        return false;
7082    }
7083
7084    @Override
7085    public byte[] getInstantAppCookie(String packageName, int userId) {
7086        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7087            return null;
7088        }
7089
7090        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7091                true /* requireFullPermission */, false /* checkShell */,
7092                "getInstantAppCookie");
7093        if (!isCallerSameApp(packageName)) {
7094            return null;
7095        }
7096        synchronized (mPackages) {
7097            return mInstantAppRegistry.getInstantAppCookieLPw(
7098                    packageName, userId);
7099        }
7100    }
7101
7102    @Override
7103    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7104        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7105            return true;
7106        }
7107
7108        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7109                true /* requireFullPermission */, true /* checkShell */,
7110                "setInstantAppCookie");
7111        if (!isCallerSameApp(packageName)) {
7112            return false;
7113        }
7114        synchronized (mPackages) {
7115            return mInstantAppRegistry.setInstantAppCookieLPw(
7116                    packageName, cookie, userId);
7117        }
7118    }
7119
7120    @Override
7121    public Bitmap getInstantAppIcon(String packageName, int userId) {
7122        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7123            return null;
7124        }
7125
7126        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7127                "getInstantAppIcon");
7128
7129        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7130                true /* requireFullPermission */, false /* checkShell */,
7131                "getInstantAppIcon");
7132
7133        synchronized (mPackages) {
7134            return mInstantAppRegistry.getInstantAppIconLPw(
7135                    packageName, userId);
7136        }
7137    }
7138
7139    private boolean isCallerSameApp(String packageName) {
7140        PackageParser.Package pkg = mPackages.get(packageName);
7141        return pkg != null
7142                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
7143    }
7144
7145    @Override
7146    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7147        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7148    }
7149
7150    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7151        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7152
7153        // reader
7154        synchronized (mPackages) {
7155            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7156            final int userId = UserHandle.getCallingUserId();
7157            while (i.hasNext()) {
7158                final PackageParser.Package p = i.next();
7159                if (p.applicationInfo == null) continue;
7160
7161                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7162                        && !p.applicationInfo.isDirectBootAware();
7163                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7164                        && p.applicationInfo.isDirectBootAware();
7165
7166                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7167                        && (!mSafeMode || isSystemApp(p))
7168                        && (matchesUnaware || matchesAware)) {
7169                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7170                    if (ps != null) {
7171                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7172                                ps.readUserState(userId), userId);
7173                        if (ai != null) {
7174                            finalList.add(ai);
7175                        }
7176                    }
7177                }
7178            }
7179        }
7180
7181        return finalList;
7182    }
7183
7184    @Override
7185    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7186        if (!sUserManager.exists(userId)) return null;
7187        flags = updateFlagsForComponent(flags, userId, name);
7188        // reader
7189        synchronized (mPackages) {
7190            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7191            PackageSetting ps = provider != null
7192                    ? mSettings.mPackages.get(provider.owner.packageName)
7193                    : null;
7194            return ps != null
7195                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
7196                    ? PackageParser.generateProviderInfo(provider, flags,
7197                            ps.readUserState(userId), userId)
7198                    : null;
7199        }
7200    }
7201
7202    /**
7203     * @deprecated
7204     */
7205    @Deprecated
7206    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7207        // reader
7208        synchronized (mPackages) {
7209            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7210                    .entrySet().iterator();
7211            final int userId = UserHandle.getCallingUserId();
7212            while (i.hasNext()) {
7213                Map.Entry<String, PackageParser.Provider> entry = i.next();
7214                PackageParser.Provider p = entry.getValue();
7215                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7216
7217                if (ps != null && p.syncable
7218                        && (!mSafeMode || (p.info.applicationInfo.flags
7219                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7220                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7221                            ps.readUserState(userId), userId);
7222                    if (info != null) {
7223                        outNames.add(entry.getKey());
7224                        outInfo.add(info);
7225                    }
7226                }
7227            }
7228        }
7229    }
7230
7231    @Override
7232    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7233            int uid, int flags) {
7234        final int userId = processName != null ? UserHandle.getUserId(uid)
7235                : UserHandle.getCallingUserId();
7236        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7237        flags = updateFlagsForComponent(flags, userId, processName);
7238
7239        ArrayList<ProviderInfo> finalList = null;
7240        // reader
7241        synchronized (mPackages) {
7242            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7243            while (i.hasNext()) {
7244                final PackageParser.Provider p = i.next();
7245                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7246                if (ps != null && p.info.authority != null
7247                        && (processName == null
7248                                || (p.info.processName.equals(processName)
7249                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7250                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7251                    if (finalList == null) {
7252                        finalList = new ArrayList<ProviderInfo>(3);
7253                    }
7254                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7255                            ps.readUserState(userId), userId);
7256                    if (info != null) {
7257                        finalList.add(info);
7258                    }
7259                }
7260            }
7261        }
7262
7263        if (finalList != null) {
7264            Collections.sort(finalList, mProviderInitOrderSorter);
7265            return new ParceledListSlice<ProviderInfo>(finalList);
7266        }
7267
7268        return ParceledListSlice.emptyList();
7269    }
7270
7271    @Override
7272    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7273        // reader
7274        synchronized (mPackages) {
7275            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7276            return PackageParser.generateInstrumentationInfo(i, flags);
7277        }
7278    }
7279
7280    @Override
7281    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7282            String targetPackage, int flags) {
7283        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7284    }
7285
7286    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7287            int flags) {
7288        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7289
7290        // reader
7291        synchronized (mPackages) {
7292            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7293            while (i.hasNext()) {
7294                final PackageParser.Instrumentation p = i.next();
7295                if (targetPackage == null
7296                        || targetPackage.equals(p.info.targetPackage)) {
7297                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7298                            flags);
7299                    if (ii != null) {
7300                        finalList.add(ii);
7301                    }
7302                }
7303            }
7304        }
7305
7306        return finalList;
7307    }
7308
7309    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
7310        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
7311        if (overlays == null) {
7312            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
7313            return;
7314        }
7315        for (PackageParser.Package opkg : overlays.values()) {
7316            // Not much to do if idmap fails: we already logged the error
7317            // and we certainly don't want to abort installation of pkg simply
7318            // because an overlay didn't fit properly. For these reasons,
7319            // ignore the return value of createIdmapForPackagePairLI.
7320            createIdmapForPackagePairLI(pkg, opkg);
7321        }
7322    }
7323
7324    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
7325            PackageParser.Package opkg) {
7326        if (!opkg.mTrustedOverlay) {
7327            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
7328                    opkg.baseCodePath + ": overlay not trusted");
7329            return false;
7330        }
7331        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
7332        if (overlaySet == null) {
7333            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
7334                    opkg.baseCodePath + " but target package has no known overlays");
7335            return false;
7336        }
7337        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7338        // TODO: generate idmap for split APKs
7339        try {
7340            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
7341        } catch (InstallerException e) {
7342            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
7343                    + opkg.baseCodePath);
7344            return false;
7345        }
7346        PackageParser.Package[] overlayArray =
7347            overlaySet.values().toArray(new PackageParser.Package[0]);
7348        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
7349            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
7350                return p1.mOverlayPriority - p2.mOverlayPriority;
7351            }
7352        };
7353        Arrays.sort(overlayArray, cmp);
7354
7355        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
7356        int i = 0;
7357        for (PackageParser.Package p : overlayArray) {
7358            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
7359        }
7360        return true;
7361    }
7362
7363    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7364        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7365        try {
7366            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7367        } finally {
7368            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7369        }
7370    }
7371
7372    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7373        final File[] files = dir.listFiles();
7374        if (ArrayUtils.isEmpty(files)) {
7375            Log.d(TAG, "No files in app dir " + dir);
7376            return;
7377        }
7378
7379        if (DEBUG_PACKAGE_SCANNING) {
7380            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7381                    + " flags=0x" + Integer.toHexString(parseFlags));
7382        }
7383        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7384                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir);
7385
7386        // Submit files for parsing in parallel
7387        int fileCount = 0;
7388        for (File file : files) {
7389            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7390                    && !PackageInstallerService.isStageName(file.getName());
7391            if (!isPackage) {
7392                // Ignore entries which are not packages
7393                continue;
7394            }
7395            parallelPackageParser.submit(file, parseFlags);
7396            fileCount++;
7397        }
7398
7399        // Process results one by one
7400        for (; fileCount > 0; fileCount--) {
7401            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7402            Throwable throwable = parseResult.throwable;
7403            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7404
7405            if (throwable == null) {
7406                // Static shared libraries have synthetic package names
7407                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
7408                    renameStaticSharedLibraryPackage(parseResult.pkg);
7409                }
7410                try {
7411                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
7412                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7413                                currentTime, null);
7414                    }
7415                } catch (PackageManagerException e) {
7416                    errorCode = e.error;
7417                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7418                }
7419            } else if (throwable instanceof PackageParser.PackageParserException) {
7420                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7421                        throwable;
7422                errorCode = e.error;
7423                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7424            } else {
7425                throw new IllegalStateException("Unexpected exception occurred while parsing "
7426                        + parseResult.scanFile, throwable);
7427            }
7428
7429            // Delete invalid userdata apps
7430            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7431                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7432                logCriticalInfo(Log.WARN,
7433                        "Deleting invalid package at " + parseResult.scanFile);
7434                removeCodePathLI(parseResult.scanFile);
7435            }
7436        }
7437        parallelPackageParser.close();
7438    }
7439
7440    private static File getSettingsProblemFile() {
7441        File dataDir = Environment.getDataDirectory();
7442        File systemDir = new File(dataDir, "system");
7443        File fname = new File(systemDir, "uiderrors.txt");
7444        return fname;
7445    }
7446
7447    static void reportSettingsProblem(int priority, String msg) {
7448        logCriticalInfo(priority, msg);
7449    }
7450
7451    static void logCriticalInfo(int priority, String msg) {
7452        Slog.println(priority, TAG, msg);
7453        EventLogTags.writePmCriticalInfo(msg);
7454        try {
7455            File fname = getSettingsProblemFile();
7456            FileOutputStream out = new FileOutputStream(fname, true);
7457            PrintWriter pw = new FastPrintWriter(out);
7458            SimpleDateFormat formatter = new SimpleDateFormat();
7459            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7460            pw.println(dateString + ": " + msg);
7461            pw.close();
7462            FileUtils.setPermissions(
7463                    fname.toString(),
7464                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7465                    -1, -1);
7466        } catch (java.io.IOException e) {
7467        }
7468    }
7469
7470    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7471        if (srcFile.isDirectory()) {
7472            final File baseFile = new File(pkg.baseCodePath);
7473            long maxModifiedTime = baseFile.lastModified();
7474            if (pkg.splitCodePaths != null) {
7475                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7476                    final File splitFile = new File(pkg.splitCodePaths[i]);
7477                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7478                }
7479            }
7480            return maxModifiedTime;
7481        }
7482        return srcFile.lastModified();
7483    }
7484
7485    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7486            final int policyFlags) throws PackageManagerException {
7487        // When upgrading from pre-N MR1, verify the package time stamp using the package
7488        // directory and not the APK file.
7489        final long lastModifiedTime = mIsPreNMR1Upgrade
7490                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7491        if (ps != null
7492                && ps.codePath.equals(srcFile)
7493                && ps.timeStamp == lastModifiedTime
7494                && !isCompatSignatureUpdateNeeded(pkg)
7495                && !isRecoverSignatureUpdateNeeded(pkg)) {
7496            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7497            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7498            ArraySet<PublicKey> signingKs;
7499            synchronized (mPackages) {
7500                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7501            }
7502            if (ps.signatures.mSignatures != null
7503                    && ps.signatures.mSignatures.length != 0
7504                    && signingKs != null) {
7505                // Optimization: reuse the existing cached certificates
7506                // if the package appears to be unchanged.
7507                pkg.mSignatures = ps.signatures.mSignatures;
7508                pkg.mSigningKeys = signingKs;
7509                return;
7510            }
7511
7512            Slog.w(TAG, "PackageSetting for " + ps.name
7513                    + " is missing signatures.  Collecting certs again to recover them.");
7514        } else {
7515            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7516        }
7517
7518        try {
7519            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7520            PackageParser.collectCertificates(pkg, policyFlags);
7521        } catch (PackageParserException e) {
7522            throw PackageManagerException.from(e);
7523        } finally {
7524            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7525        }
7526    }
7527
7528    /**
7529     *  Traces a package scan.
7530     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7531     */
7532    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7533            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7534        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7535        try {
7536            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7537        } finally {
7538            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7539        }
7540    }
7541
7542    /**
7543     *  Scans a package and returns the newly parsed package.
7544     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7545     */
7546    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7547            long currentTime, UserHandle user) throws PackageManagerException {
7548        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7549        PackageParser pp = new PackageParser();
7550        pp.setSeparateProcesses(mSeparateProcesses);
7551        pp.setOnlyCoreApps(mOnlyCore);
7552        pp.setDisplayMetrics(mMetrics);
7553
7554        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7555            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7556        }
7557
7558        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7559        final PackageParser.Package pkg;
7560        try {
7561            pkg = pp.parsePackage(scanFile, parseFlags);
7562        } catch (PackageParserException e) {
7563            throw PackageManagerException.from(e);
7564        } finally {
7565            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7566        }
7567
7568        // Static shared libraries have synthetic package names
7569        if (pkg.applicationInfo.isStaticSharedLibrary()) {
7570            renameStaticSharedLibraryPackage(pkg);
7571        }
7572
7573        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7574    }
7575
7576    /**
7577     *  Scans a package and returns the newly parsed package.
7578     *  @throws PackageManagerException on a parse error.
7579     */
7580    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7581            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7582            throws PackageManagerException {
7583        // If the package has children and this is the first dive in the function
7584        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7585        // packages (parent and children) would be successfully scanned before the
7586        // actual scan since scanning mutates internal state and we want to atomically
7587        // install the package and its children.
7588        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7589            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7590                scanFlags |= SCAN_CHECK_ONLY;
7591            }
7592        } else {
7593            scanFlags &= ~SCAN_CHECK_ONLY;
7594        }
7595
7596        // Scan the parent
7597        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7598                scanFlags, currentTime, user);
7599
7600        // Scan the children
7601        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7602        for (int i = 0; i < childCount; i++) {
7603            PackageParser.Package childPackage = pkg.childPackages.get(i);
7604            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7605                    currentTime, user);
7606        }
7607
7608
7609        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7610            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7611        }
7612
7613        return scannedPkg;
7614    }
7615
7616    /**
7617     *  Scans a package and returns the newly parsed package.
7618     *  @throws PackageManagerException on a parse error.
7619     */
7620    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7621            int policyFlags, int scanFlags, long currentTime, UserHandle user)
7622            throws PackageManagerException {
7623        PackageSetting ps = null;
7624        PackageSetting updatedPkg;
7625        // reader
7626        synchronized (mPackages) {
7627            // Look to see if we already know about this package.
7628            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7629            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7630                // This package has been renamed to its original name.  Let's
7631                // use that.
7632                ps = mSettings.getPackageLPr(oldName);
7633            }
7634            // If there was no original package, see one for the real package name.
7635            if (ps == null) {
7636                ps = mSettings.getPackageLPr(pkg.packageName);
7637            }
7638            // Check to see if this package could be hiding/updating a system
7639            // package.  Must look for it either under the original or real
7640            // package name depending on our state.
7641            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7642            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7643
7644            // If this is a package we don't know about on the system partition, we
7645            // may need to remove disabled child packages on the system partition
7646            // or may need to not add child packages if the parent apk is updated
7647            // on the data partition and no longer defines this child package.
7648            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7649                // If this is a parent package for an updated system app and this system
7650                // app got an OTA update which no longer defines some of the child packages
7651                // we have to prune them from the disabled system packages.
7652                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7653                if (disabledPs != null) {
7654                    final int scannedChildCount = (pkg.childPackages != null)
7655                            ? pkg.childPackages.size() : 0;
7656                    final int disabledChildCount = disabledPs.childPackageNames != null
7657                            ? disabledPs.childPackageNames.size() : 0;
7658                    for (int i = 0; i < disabledChildCount; i++) {
7659                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7660                        boolean disabledPackageAvailable = false;
7661                        for (int j = 0; j < scannedChildCount; j++) {
7662                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7663                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7664                                disabledPackageAvailable = true;
7665                                break;
7666                            }
7667                         }
7668                         if (!disabledPackageAvailable) {
7669                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7670                         }
7671                    }
7672                }
7673            }
7674        }
7675
7676        boolean updatedPkgBetter = false;
7677        // First check if this is a system package that may involve an update
7678        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7679            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7680            // it needs to drop FLAG_PRIVILEGED.
7681            if (locationIsPrivileged(scanFile)) {
7682                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7683            } else {
7684                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7685            }
7686
7687            if (ps != null && !ps.codePath.equals(scanFile)) {
7688                // The path has changed from what was last scanned...  check the
7689                // version of the new path against what we have stored to determine
7690                // what to do.
7691                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7692                if (pkg.mVersionCode <= ps.versionCode) {
7693                    // The system package has been updated and the code path does not match
7694                    // Ignore entry. Skip it.
7695                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7696                            + " ignored: updated version " + ps.versionCode
7697                            + " better than this " + pkg.mVersionCode);
7698                    if (!updatedPkg.codePath.equals(scanFile)) {
7699                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7700                                + ps.name + " changing from " + updatedPkg.codePathString
7701                                + " to " + scanFile);
7702                        updatedPkg.codePath = scanFile;
7703                        updatedPkg.codePathString = scanFile.toString();
7704                        updatedPkg.resourcePath = scanFile;
7705                        updatedPkg.resourcePathString = scanFile.toString();
7706                    }
7707                    updatedPkg.pkg = pkg;
7708                    updatedPkg.versionCode = pkg.mVersionCode;
7709
7710                    // Update the disabled system child packages to point to the package too.
7711                    final int childCount = updatedPkg.childPackageNames != null
7712                            ? updatedPkg.childPackageNames.size() : 0;
7713                    for (int i = 0; i < childCount; i++) {
7714                        String childPackageName = updatedPkg.childPackageNames.get(i);
7715                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7716                                childPackageName);
7717                        if (updatedChildPkg != null) {
7718                            updatedChildPkg.pkg = pkg;
7719                            updatedChildPkg.versionCode = pkg.mVersionCode;
7720                        }
7721                    }
7722
7723                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7724                            + scanFile + " ignored: updated version " + ps.versionCode
7725                            + " better than this " + pkg.mVersionCode);
7726                } else {
7727                    // The current app on the system partition is better than
7728                    // what we have updated to on the data partition; switch
7729                    // back to the system partition version.
7730                    // At this point, its safely assumed that package installation for
7731                    // apps in system partition will go through. If not there won't be a working
7732                    // version of the app
7733                    // writer
7734                    synchronized (mPackages) {
7735                        // Just remove the loaded entries from package lists.
7736                        mPackages.remove(ps.name);
7737                    }
7738
7739                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7740                            + " reverting from " + ps.codePathString
7741                            + ": new version " + pkg.mVersionCode
7742                            + " better than installed " + ps.versionCode);
7743
7744                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7745                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7746                    synchronized (mInstallLock) {
7747                        args.cleanUpResourcesLI();
7748                    }
7749                    synchronized (mPackages) {
7750                        mSettings.enableSystemPackageLPw(ps.name);
7751                    }
7752                    updatedPkgBetter = true;
7753                }
7754            }
7755        }
7756
7757        if (updatedPkg != null) {
7758            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7759            // initially
7760            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7761
7762            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7763            // flag set initially
7764            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7765                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7766            }
7767        }
7768
7769        // Verify certificates against what was last scanned
7770        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7771
7772        /*
7773         * A new system app appeared, but we already had a non-system one of the
7774         * same name installed earlier.
7775         */
7776        boolean shouldHideSystemApp = false;
7777        if (updatedPkg == null && ps != null
7778                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7779            /*
7780             * Check to make sure the signatures match first. If they don't,
7781             * wipe the installed application and its data.
7782             */
7783            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7784                    != PackageManager.SIGNATURE_MATCH) {
7785                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7786                        + " signatures don't match existing userdata copy; removing");
7787                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7788                        "scanPackageInternalLI")) {
7789                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7790                }
7791                ps = null;
7792            } else {
7793                /*
7794                 * If the newly-added system app is an older version than the
7795                 * already installed version, hide it. It will be scanned later
7796                 * and re-added like an update.
7797                 */
7798                if (pkg.mVersionCode <= ps.versionCode) {
7799                    shouldHideSystemApp = true;
7800                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7801                            + " but new version " + pkg.mVersionCode + " better than installed "
7802                            + ps.versionCode + "; hiding system");
7803                } else {
7804                    /*
7805                     * The newly found system app is a newer version that the
7806                     * one previously installed. Simply remove the
7807                     * already-installed application and replace it with our own
7808                     * while keeping the application data.
7809                     */
7810                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7811                            + " reverting from " + ps.codePathString + ": new version "
7812                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7813                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7814                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7815                    synchronized (mInstallLock) {
7816                        args.cleanUpResourcesLI();
7817                    }
7818                }
7819            }
7820        }
7821
7822        // The apk is forward locked (not public) if its code and resources
7823        // are kept in different files. (except for app in either system or
7824        // vendor path).
7825        // TODO grab this value from PackageSettings
7826        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7827            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7828                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7829            }
7830        }
7831
7832        // TODO: extend to support forward-locked splits
7833        String resourcePath = null;
7834        String baseResourcePath = null;
7835        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7836            if (ps != null && ps.resourcePathString != null) {
7837                resourcePath = ps.resourcePathString;
7838                baseResourcePath = ps.resourcePathString;
7839            } else {
7840                // Should not happen at all. Just log an error.
7841                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7842            }
7843        } else {
7844            resourcePath = pkg.codePath;
7845            baseResourcePath = pkg.baseCodePath;
7846        }
7847
7848        // Set application objects path explicitly.
7849        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7850        pkg.setApplicationInfoCodePath(pkg.codePath);
7851        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7852        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7853        pkg.setApplicationInfoResourcePath(resourcePath);
7854        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7855        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7856
7857        // Note that we invoke the following method only if we are about to unpack an application
7858        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7859                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7860
7861        /*
7862         * If the system app should be overridden by a previously installed
7863         * data, hide the system app now and let the /data/app scan pick it up
7864         * again.
7865         */
7866        if (shouldHideSystemApp) {
7867            synchronized (mPackages) {
7868                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7869            }
7870        }
7871
7872        return scannedPkg;
7873    }
7874
7875    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
7876        // Derive the new package synthetic package name
7877        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
7878                + pkg.staticSharedLibVersion);
7879    }
7880
7881    private static String fixProcessName(String defProcessName,
7882            String processName) {
7883        if (processName == null) {
7884            return defProcessName;
7885        }
7886        return processName;
7887    }
7888
7889    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7890            throws PackageManagerException {
7891        if (pkgSetting.signatures.mSignatures != null) {
7892            // Already existing package. Make sure signatures match
7893            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7894                    == PackageManager.SIGNATURE_MATCH;
7895            if (!match) {
7896                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7897                        == PackageManager.SIGNATURE_MATCH;
7898            }
7899            if (!match) {
7900                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7901                        == PackageManager.SIGNATURE_MATCH;
7902            }
7903            if (!match) {
7904                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7905                        + pkg.packageName + " signatures do not match the "
7906                        + "previously installed version; ignoring!");
7907            }
7908        }
7909
7910        // Check for shared user signatures
7911        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7912            // Already existing package. Make sure signatures match
7913            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7914                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7915            if (!match) {
7916                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7917                        == PackageManager.SIGNATURE_MATCH;
7918            }
7919            if (!match) {
7920                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7921                        == PackageManager.SIGNATURE_MATCH;
7922            }
7923            if (!match) {
7924                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7925                        "Package " + pkg.packageName
7926                        + " has no signatures that match those in shared user "
7927                        + pkgSetting.sharedUser.name + "; ignoring!");
7928            }
7929        }
7930    }
7931
7932    /**
7933     * Enforces that only the system UID or root's UID can call a method exposed
7934     * via Binder.
7935     *
7936     * @param message used as message if SecurityException is thrown
7937     * @throws SecurityException if the caller is not system or root
7938     */
7939    private static final void enforceSystemOrRoot(String message) {
7940        final int uid = Binder.getCallingUid();
7941        if (uid != Process.SYSTEM_UID && uid != 0) {
7942            throw new SecurityException(message);
7943        }
7944    }
7945
7946    @Override
7947    public void performFstrimIfNeeded() {
7948        enforceSystemOrRoot("Only the system can request fstrim");
7949
7950        // Before everything else, see whether we need to fstrim.
7951        try {
7952            IStorageManager sm = PackageHelper.getStorageManager();
7953            if (sm != null) {
7954                boolean doTrim = false;
7955                final long interval = android.provider.Settings.Global.getLong(
7956                        mContext.getContentResolver(),
7957                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7958                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7959                if (interval > 0) {
7960                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
7961                    if (timeSinceLast > interval) {
7962                        doTrim = true;
7963                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7964                                + "; running immediately");
7965                    }
7966                }
7967                if (doTrim) {
7968                    final boolean dexOptDialogShown;
7969                    synchronized (mPackages) {
7970                        dexOptDialogShown = mDexOptDialogShown;
7971                    }
7972                    if (!isFirstBoot() && dexOptDialogShown) {
7973                        try {
7974                            ActivityManager.getService().showBootMessage(
7975                                    mContext.getResources().getString(
7976                                            R.string.android_upgrading_fstrim), true);
7977                        } catch (RemoteException e) {
7978                        }
7979                    }
7980                    sm.runMaintenance();
7981                }
7982            } else {
7983                Slog.e(TAG, "storageManager service unavailable!");
7984            }
7985        } catch (RemoteException e) {
7986            // Can't happen; StorageManagerService is local
7987        }
7988    }
7989
7990    @Override
7991    public void updatePackagesIfNeeded() {
7992        enforceSystemOrRoot("Only the system can request package update");
7993
7994        // We need to re-extract after an OTA.
7995        boolean causeUpgrade = isUpgrade();
7996
7997        // First boot or factory reset.
7998        // Note: we also handle devices that are upgrading to N right now as if it is their
7999        //       first boot, as they do not have profile data.
8000        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8001
8002        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8003        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8004
8005        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8006            return;
8007        }
8008
8009        List<PackageParser.Package> pkgs;
8010        synchronized (mPackages) {
8011            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8012        }
8013
8014        final long startTime = System.nanoTime();
8015        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8016                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8017
8018        final int elapsedTimeSeconds =
8019                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8020
8021        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8022        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8023        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8024        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8025        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8026    }
8027
8028    /**
8029     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8030     * containing statistics about the invocation. The array consists of three elements,
8031     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8032     * and {@code numberOfPackagesFailed}.
8033     */
8034    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8035            String compilerFilter) {
8036
8037        int numberOfPackagesVisited = 0;
8038        int numberOfPackagesOptimized = 0;
8039        int numberOfPackagesSkipped = 0;
8040        int numberOfPackagesFailed = 0;
8041        final int numberOfPackagesToDexopt = pkgs.size();
8042
8043        for (PackageParser.Package pkg : pkgs) {
8044            numberOfPackagesVisited++;
8045
8046            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8047                if (DEBUG_DEXOPT) {
8048                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8049                }
8050                numberOfPackagesSkipped++;
8051                continue;
8052            }
8053
8054            if (DEBUG_DEXOPT) {
8055                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8056                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8057            }
8058
8059            if (showDialog) {
8060                try {
8061                    ActivityManager.getService().showBootMessage(
8062                            mContext.getResources().getString(R.string.android_upgrading_apk,
8063                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8064                } catch (RemoteException e) {
8065                }
8066                synchronized (mPackages) {
8067                    mDexOptDialogShown = true;
8068                }
8069            }
8070
8071            // If the OTA updates a system app which was previously preopted to a non-preopted state
8072            // the app might end up being verified at runtime. That's because by default the apps
8073            // are verify-profile but for preopted apps there's no profile.
8074            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8075            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8076            // filter (by default interpret-only).
8077            // Note that at this stage unused apps are already filtered.
8078            if (isSystemApp(pkg) &&
8079                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8080                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8081                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8082            }
8083
8084            // checkProfiles is false to avoid merging profiles during boot which
8085            // might interfere with background compilation (b/28612421).
8086            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8087            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8088            // trade-off worth doing to save boot time work.
8089            int dexOptStatus = performDexOptTraced(pkg.packageName,
8090                    false /* checkProfiles */,
8091                    compilerFilter,
8092                    false /* force */);
8093            switch (dexOptStatus) {
8094                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8095                    numberOfPackagesOptimized++;
8096                    break;
8097                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8098                    numberOfPackagesSkipped++;
8099                    break;
8100                case PackageDexOptimizer.DEX_OPT_FAILED:
8101                    numberOfPackagesFailed++;
8102                    break;
8103                default:
8104                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8105                    break;
8106            }
8107        }
8108
8109        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8110                numberOfPackagesFailed };
8111    }
8112
8113    @Override
8114    public void notifyPackageUse(String packageName, int reason) {
8115        synchronized (mPackages) {
8116            PackageParser.Package p = mPackages.get(packageName);
8117            if (p == null) {
8118                return;
8119            }
8120            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8121        }
8122    }
8123
8124    @Override
8125    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8126        int userId = UserHandle.getCallingUserId();
8127        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8128        if (ai == null) {
8129            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8130                + loadingPackageName + ", user=" + userId);
8131            return;
8132        }
8133        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8134    }
8135
8136    // TODO: this is not used nor needed. Delete it.
8137    @Override
8138    public boolean performDexOptIfNeeded(String packageName) {
8139        int dexOptStatus = performDexOptTraced(packageName,
8140                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
8141        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8142    }
8143
8144    @Override
8145    public boolean performDexOpt(String packageName,
8146            boolean checkProfiles, int compileReason, boolean force) {
8147        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8148                getCompilerFilterForReason(compileReason), force);
8149        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8150    }
8151
8152    @Override
8153    public boolean performDexOptMode(String packageName,
8154            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8155        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8156                targetCompilerFilter, force);
8157        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8158    }
8159
8160    private int performDexOptTraced(String packageName,
8161                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8162        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8163        try {
8164            return performDexOptInternal(packageName, checkProfiles,
8165                    targetCompilerFilter, force);
8166        } finally {
8167            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8168        }
8169    }
8170
8171    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8172    // if the package can now be considered up to date for the given filter.
8173    private int performDexOptInternal(String packageName,
8174                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8175        PackageParser.Package p;
8176        synchronized (mPackages) {
8177            p = mPackages.get(packageName);
8178            if (p == null) {
8179                // Package could not be found. Report failure.
8180                return PackageDexOptimizer.DEX_OPT_FAILED;
8181            }
8182            mPackageUsage.maybeWriteAsync(mPackages);
8183            mCompilerStats.maybeWriteAsync();
8184        }
8185        long callingId = Binder.clearCallingIdentity();
8186        try {
8187            synchronized (mInstallLock) {
8188                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8189                        targetCompilerFilter, force);
8190            }
8191        } finally {
8192            Binder.restoreCallingIdentity(callingId);
8193        }
8194    }
8195
8196    public ArraySet<String> getOptimizablePackages() {
8197        ArraySet<String> pkgs = new ArraySet<String>();
8198        synchronized (mPackages) {
8199            for (PackageParser.Package p : mPackages.values()) {
8200                if (PackageDexOptimizer.canOptimizePackage(p)) {
8201                    pkgs.add(p.packageName);
8202                }
8203            }
8204        }
8205        return pkgs;
8206    }
8207
8208    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8209            boolean checkProfiles, String targetCompilerFilter,
8210            boolean force) {
8211        // Select the dex optimizer based on the force parameter.
8212        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8213        //       allocate an object here.
8214        PackageDexOptimizer pdo = force
8215                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8216                : mPackageDexOptimizer;
8217
8218        // Optimize all dependencies first. Note: we ignore the return value and march on
8219        // on errors.
8220        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8221        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8222        if (!deps.isEmpty()) {
8223            for (PackageParser.Package depPackage : deps) {
8224                // TODO: Analyze and investigate if we (should) profile libraries.
8225                // Currently this will do a full compilation of the library by default.
8226                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8227                        false /* checkProfiles */,
8228                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
8229                        getOrCreateCompilerPackageStats(depPackage));
8230            }
8231        }
8232        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8233                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
8234    }
8235
8236    // Performs dexopt on the used secondary dex files belonging to the given package.
8237    // Returns true if all dex files were process successfully (which could mean either dexopt or
8238    // skip). Returns false if any of the files caused errors.
8239    @Override
8240    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8241            boolean force) {
8242        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8243    }
8244
8245    /**
8246     * Reconcile the information we have about the secondary dex files belonging to
8247     * {@code packagName} and the actual dex files. For all dex files that were
8248     * deleted, update the internal records and delete the generated oat files.
8249     */
8250    @Override
8251    public void reconcileSecondaryDexFiles(String packageName) {
8252        mDexManager.reconcileSecondaryDexFiles(packageName);
8253    }
8254
8255    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8256    // a reference there.
8257    /*package*/ DexManager getDexManager() {
8258        return mDexManager;
8259    }
8260
8261    /**
8262     * Execute the background dexopt job immediately.
8263     */
8264    @Override
8265    public boolean runBackgroundDexoptJob() {
8266        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8267    }
8268
8269    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8270        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8271                || p.usesStaticLibraries != null) {
8272            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8273            Set<String> collectedNames = new HashSet<>();
8274            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8275
8276            retValue.remove(p);
8277
8278            return retValue;
8279        } else {
8280            return Collections.emptyList();
8281        }
8282    }
8283
8284    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8285            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8286        if (!collectedNames.contains(p.packageName)) {
8287            collectedNames.add(p.packageName);
8288            collected.add(p);
8289
8290            if (p.usesLibraries != null) {
8291                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8292                        null, collected, collectedNames);
8293            }
8294            if (p.usesOptionalLibraries != null) {
8295                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8296                        null, collected, collectedNames);
8297            }
8298            if (p.usesStaticLibraries != null) {
8299                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8300                        p.usesStaticLibrariesVersions, collected, collectedNames);
8301            }
8302        }
8303    }
8304
8305    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8306            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8307        final int libNameCount = libs.size();
8308        for (int i = 0; i < libNameCount; i++) {
8309            String libName = libs.get(i);
8310            int version = (versions != null && versions.length == libNameCount)
8311                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8312            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8313            if (libPkg != null) {
8314                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8315            }
8316        }
8317    }
8318
8319    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8320        synchronized (mPackages) {
8321            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8322            if (libEntry != null) {
8323                return mPackages.get(libEntry.apk);
8324            }
8325            return null;
8326        }
8327    }
8328
8329    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8330        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8331        if (versionedLib == null) {
8332            return null;
8333        }
8334        return versionedLib.get(version);
8335    }
8336
8337    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
8338        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
8339                pkg.staticSharedLibName);
8340        if (versionedLib == null) {
8341            return null;
8342        }
8343        int previousLibVersion = -1;
8344        final int versionCount = versionedLib.size();
8345        for (int i = 0; i < versionCount; i++) {
8346            final int libVersion = versionedLib.keyAt(i);
8347            if (libVersion < pkg.staticSharedLibVersion) {
8348                previousLibVersion = Math.max(previousLibVersion, libVersion);
8349            }
8350        }
8351        if (previousLibVersion >= 0) {
8352            return versionedLib.get(previousLibVersion);
8353        }
8354        return null;
8355    }
8356
8357    public void shutdown() {
8358        mPackageUsage.writeNow(mPackages);
8359        mCompilerStats.writeNow();
8360    }
8361
8362    @Override
8363    public void dumpProfiles(String packageName) {
8364        PackageParser.Package pkg;
8365        synchronized (mPackages) {
8366            pkg = mPackages.get(packageName);
8367            if (pkg == null) {
8368                throw new IllegalArgumentException("Unknown package: " + packageName);
8369            }
8370        }
8371        /* Only the shell, root, or the app user should be able to dump profiles. */
8372        int callingUid = Binder.getCallingUid();
8373        if (callingUid != Process.SHELL_UID &&
8374            callingUid != Process.ROOT_UID &&
8375            callingUid != pkg.applicationInfo.uid) {
8376            throw new SecurityException("dumpProfiles");
8377        }
8378
8379        synchronized (mInstallLock) {
8380            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
8381            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
8382            try {
8383                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
8384                String codePaths = TextUtils.join(";", allCodePaths);
8385                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
8386            } catch (InstallerException e) {
8387                Slog.w(TAG, "Failed to dump profiles", e);
8388            }
8389            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8390        }
8391    }
8392
8393    @Override
8394    public void forceDexOpt(String packageName) {
8395        enforceSystemOrRoot("forceDexOpt");
8396
8397        PackageParser.Package pkg;
8398        synchronized (mPackages) {
8399            pkg = mPackages.get(packageName);
8400            if (pkg == null) {
8401                throw new IllegalArgumentException("Unknown package: " + packageName);
8402            }
8403        }
8404
8405        synchronized (mInstallLock) {
8406            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8407
8408            // Whoever is calling forceDexOpt wants a fully compiled package.
8409            // Don't use profiles since that may cause compilation to be skipped.
8410            final int res = performDexOptInternalWithDependenciesLI(pkg,
8411                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
8412                    true /* force */);
8413
8414            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8415            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
8416                throw new IllegalStateException("Failed to dexopt: " + res);
8417            }
8418        }
8419    }
8420
8421    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
8422        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8423            Slog.w(TAG, "Unable to update from " + oldPkg.name
8424                    + " to " + newPkg.packageName
8425                    + ": old package not in system partition");
8426            return false;
8427        } else if (mPackages.get(oldPkg.name) != null) {
8428            Slog.w(TAG, "Unable to update from " + oldPkg.name
8429                    + " to " + newPkg.packageName
8430                    + ": old package still exists");
8431            return false;
8432        }
8433        return true;
8434    }
8435
8436    void removeCodePathLI(File codePath) {
8437        if (codePath.isDirectory()) {
8438            try {
8439                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8440            } catch (InstallerException e) {
8441                Slog.w(TAG, "Failed to remove code path", e);
8442            }
8443        } else {
8444            codePath.delete();
8445        }
8446    }
8447
8448    private int[] resolveUserIds(int userId) {
8449        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8450    }
8451
8452    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8453        if (pkg == null) {
8454            Slog.wtf(TAG, "Package was null!", new Throwable());
8455            return;
8456        }
8457        clearAppDataLeafLIF(pkg, userId, flags);
8458        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8459        for (int i = 0; i < childCount; i++) {
8460            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8461        }
8462    }
8463
8464    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8465        final PackageSetting ps;
8466        synchronized (mPackages) {
8467            ps = mSettings.mPackages.get(pkg.packageName);
8468        }
8469        for (int realUserId : resolveUserIds(userId)) {
8470            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8471            try {
8472                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8473                        ceDataInode);
8474            } catch (InstallerException e) {
8475                Slog.w(TAG, String.valueOf(e));
8476            }
8477        }
8478    }
8479
8480    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8481        if (pkg == null) {
8482            Slog.wtf(TAG, "Package was null!", new Throwable());
8483            return;
8484        }
8485        destroyAppDataLeafLIF(pkg, userId, flags);
8486        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8487        for (int i = 0; i < childCount; i++) {
8488            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8489        }
8490    }
8491
8492    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8493        final PackageSetting ps;
8494        synchronized (mPackages) {
8495            ps = mSettings.mPackages.get(pkg.packageName);
8496        }
8497        for (int realUserId : resolveUserIds(userId)) {
8498            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8499            try {
8500                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8501                        ceDataInode);
8502            } catch (InstallerException e) {
8503                Slog.w(TAG, String.valueOf(e));
8504            }
8505        }
8506    }
8507
8508    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8509        if (pkg == null) {
8510            Slog.wtf(TAG, "Package was null!", new Throwable());
8511            return;
8512        }
8513        destroyAppProfilesLeafLIF(pkg);
8514        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
8515        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8516        for (int i = 0; i < childCount; i++) {
8517            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8518            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
8519                    true /* removeBaseMarker */);
8520        }
8521    }
8522
8523    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
8524            boolean removeBaseMarker) {
8525        if (pkg.isForwardLocked()) {
8526            return;
8527        }
8528
8529        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
8530            try {
8531                path = PackageManagerServiceUtils.realpath(new File(path));
8532            } catch (IOException e) {
8533                // TODO: Should we return early here ?
8534                Slog.w(TAG, "Failed to get canonical path", e);
8535                continue;
8536            }
8537
8538            final String useMarker = path.replace('/', '@');
8539            for (int realUserId : resolveUserIds(userId)) {
8540                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
8541                if (removeBaseMarker) {
8542                    File foreignUseMark = new File(profileDir, useMarker);
8543                    if (foreignUseMark.exists()) {
8544                        if (!foreignUseMark.delete()) {
8545                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
8546                                    + pkg.packageName);
8547                        }
8548                    }
8549                }
8550
8551                File[] markers = profileDir.listFiles();
8552                if (markers != null) {
8553                    final String searchString = "@" + pkg.packageName + "@";
8554                    // We also delete all markers that contain the package name we're
8555                    // uninstalling. These are associated with secondary dex-files belonging
8556                    // to the package. Reconstructing the path of these dex files is messy
8557                    // in general.
8558                    for (File marker : markers) {
8559                        if (marker.getName().indexOf(searchString) > 0) {
8560                            if (!marker.delete()) {
8561                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
8562                                    + pkg.packageName);
8563                            }
8564                        }
8565                    }
8566                }
8567            }
8568        }
8569    }
8570
8571    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8572        try {
8573            mInstaller.destroyAppProfiles(pkg.packageName);
8574        } catch (InstallerException e) {
8575            Slog.w(TAG, String.valueOf(e));
8576        }
8577    }
8578
8579    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8580        if (pkg == null) {
8581            Slog.wtf(TAG, "Package was null!", new Throwable());
8582            return;
8583        }
8584        clearAppProfilesLeafLIF(pkg);
8585        // We don't remove the base foreign use marker when clearing profiles because
8586        // we will rename it when the app is updated. Unlike the actual profile contents,
8587        // the foreign use marker is good across installs.
8588        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
8589        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8590        for (int i = 0; i < childCount; i++) {
8591            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8592        }
8593    }
8594
8595    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8596        try {
8597            mInstaller.clearAppProfiles(pkg.packageName);
8598        } catch (InstallerException e) {
8599            Slog.w(TAG, String.valueOf(e));
8600        }
8601    }
8602
8603    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8604            long lastUpdateTime) {
8605        // Set parent install/update time
8606        PackageSetting ps = (PackageSetting) pkg.mExtras;
8607        if (ps != null) {
8608            ps.firstInstallTime = firstInstallTime;
8609            ps.lastUpdateTime = lastUpdateTime;
8610        }
8611        // Set children install/update time
8612        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8613        for (int i = 0; i < childCount; i++) {
8614            PackageParser.Package childPkg = pkg.childPackages.get(i);
8615            ps = (PackageSetting) childPkg.mExtras;
8616            if (ps != null) {
8617                ps.firstInstallTime = firstInstallTime;
8618                ps.lastUpdateTime = lastUpdateTime;
8619            }
8620        }
8621    }
8622
8623    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8624            PackageParser.Package changingLib) {
8625        if (file.path != null) {
8626            usesLibraryFiles.add(file.path);
8627            return;
8628        }
8629        PackageParser.Package p = mPackages.get(file.apk);
8630        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8631            // If we are doing this while in the middle of updating a library apk,
8632            // then we need to make sure to use that new apk for determining the
8633            // dependencies here.  (We haven't yet finished committing the new apk
8634            // to the package manager state.)
8635            if (p == null || p.packageName.equals(changingLib.packageName)) {
8636                p = changingLib;
8637            }
8638        }
8639        if (p != null) {
8640            usesLibraryFiles.addAll(p.getAllCodePaths());
8641        }
8642    }
8643
8644    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8645            PackageParser.Package changingLib) throws PackageManagerException {
8646        if (pkg == null) {
8647            return;
8648        }
8649        ArraySet<String> usesLibraryFiles = null;
8650        if (pkg.usesLibraries != null) {
8651            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
8652                    null, null, pkg.packageName, changingLib, true, null);
8653        }
8654        if (pkg.usesStaticLibraries != null) {
8655            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
8656                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
8657                    pkg.packageName, changingLib, true, usesLibraryFiles);
8658        }
8659        if (pkg.usesOptionalLibraries != null) {
8660            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
8661                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
8662        }
8663        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
8664            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
8665        } else {
8666            pkg.usesLibraryFiles = null;
8667        }
8668    }
8669
8670    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
8671            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
8672            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
8673            boolean required, @Nullable ArraySet<String> outUsedLibraries)
8674            throws PackageManagerException {
8675        final int libCount = requestedLibraries.size();
8676        for (int i = 0; i < libCount; i++) {
8677            final String libName = requestedLibraries.get(i);
8678            final int libVersion = requiredVersions != null ? requiredVersions[i]
8679                    : SharedLibraryInfo.VERSION_UNDEFINED;
8680            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
8681            if (libEntry == null) {
8682                if (required) {
8683                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8684                            "Package " + packageName + " requires unavailable shared library "
8685                                    + libName + "; failing!");
8686                } else {
8687                    Slog.w(TAG, "Package " + packageName
8688                            + " desires unavailable shared library "
8689                            + libName + "; ignoring!");
8690                }
8691            } else {
8692                if (requiredVersions != null && requiredCertDigests != null) {
8693                    if (libEntry.info.getVersion() != requiredVersions[i]) {
8694                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8695                            "Package " + packageName + " requires unavailable static shared"
8696                                    + " library " + libName + " version "
8697                                    + libEntry.info.getVersion() + "; failing!");
8698                    }
8699
8700                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
8701                    if (libPkg == null) {
8702                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8703                                "Package " + packageName + " requires unavailable static shared"
8704                                        + " library; failing!");
8705                    }
8706
8707                    String expectedCertDigest = requiredCertDigests[i];
8708                    String libCertDigest = PackageUtils.computeCertSha256Digest(
8709                                libPkg.mSignatures[0]);
8710                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
8711                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8712                                "Package " + packageName + " requires differently signed" +
8713                                        " static shared library; failing!");
8714                    }
8715                }
8716
8717                if (outUsedLibraries == null) {
8718                    outUsedLibraries = new ArraySet<>();
8719                }
8720                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
8721            }
8722        }
8723        return outUsedLibraries;
8724    }
8725
8726    private static boolean hasString(List<String> list, List<String> which) {
8727        if (list == null) {
8728            return false;
8729        }
8730        for (int i=list.size()-1; i>=0; i--) {
8731            for (int j=which.size()-1; j>=0; j--) {
8732                if (which.get(j).equals(list.get(i))) {
8733                    return true;
8734                }
8735            }
8736        }
8737        return false;
8738    }
8739
8740    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
8741            PackageParser.Package changingPkg) {
8742        ArrayList<PackageParser.Package> res = null;
8743        for (PackageParser.Package pkg : mPackages.values()) {
8744            if (changingPkg != null
8745                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
8746                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
8747                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
8748                            changingPkg.staticSharedLibName)) {
8749                return null;
8750            }
8751            if (res == null) {
8752                res = new ArrayList<>();
8753            }
8754            res.add(pkg);
8755            try {
8756                updateSharedLibrariesLPr(pkg, changingPkg);
8757            } catch (PackageManagerException e) {
8758                // If a system app update or an app and a required lib missing we
8759                // delete the package and for updated system apps keep the data as
8760                // it is better for the user to reinstall than to be in an limbo
8761                // state. Also libs disappearing under an app should never happen
8762                // - just in case.
8763                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
8764                    final int flags = pkg.isUpdatedSystemApp()
8765                            ? PackageManager.DELETE_KEEP_DATA : 0;
8766                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
8767                            flags , null, true, null);
8768                }
8769                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8770            }
8771        }
8772        return res;
8773    }
8774
8775    /**
8776     * Derive the value of the {@code cpuAbiOverride} based on the provided
8777     * value and an optional stored value from the package settings.
8778     */
8779    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
8780        String cpuAbiOverride = null;
8781
8782        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
8783            cpuAbiOverride = null;
8784        } else if (abiOverride != null) {
8785            cpuAbiOverride = abiOverride;
8786        } else if (settings != null) {
8787            cpuAbiOverride = settings.cpuAbiOverrideString;
8788        }
8789
8790        return cpuAbiOverride;
8791    }
8792
8793    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8794            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
8795                    throws PackageManagerException {
8796        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8797        // If the package has children and this is the first dive in the function
8798        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
8799        // whether all packages (parent and children) would be successfully scanned
8800        // before the actual scan since scanning mutates internal state and we want
8801        // to atomically install the package and its children.
8802        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8803            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8804                scanFlags |= SCAN_CHECK_ONLY;
8805            }
8806        } else {
8807            scanFlags &= ~SCAN_CHECK_ONLY;
8808        }
8809
8810        final PackageParser.Package scannedPkg;
8811        try {
8812            // Scan the parent
8813            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
8814            // Scan the children
8815            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8816            for (int i = 0; i < childCount; i++) {
8817                PackageParser.Package childPkg = pkg.childPackages.get(i);
8818                scanPackageLI(childPkg, policyFlags,
8819                        scanFlags, currentTime, user);
8820            }
8821        } finally {
8822            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8823        }
8824
8825        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8826            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
8827        }
8828
8829        return scannedPkg;
8830    }
8831
8832    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8833            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8834        boolean success = false;
8835        try {
8836            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
8837                    currentTime, user);
8838            success = true;
8839            return res;
8840        } finally {
8841            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
8842                // DELETE_DATA_ON_FAILURES is only used by frozen paths
8843                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
8844                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
8845                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
8846            }
8847        }
8848    }
8849
8850    /**
8851     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
8852     */
8853    private static boolean apkHasCode(String fileName) {
8854        StrictJarFile jarFile = null;
8855        try {
8856            jarFile = new StrictJarFile(fileName,
8857                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
8858            return jarFile.findEntry("classes.dex") != null;
8859        } catch (IOException ignore) {
8860        } finally {
8861            try {
8862                if (jarFile != null) {
8863                    jarFile.close();
8864                }
8865            } catch (IOException ignore) {}
8866        }
8867        return false;
8868    }
8869
8870    /**
8871     * Enforces code policy for the package. This ensures that if an APK has
8872     * declared hasCode="true" in its manifest that the APK actually contains
8873     * code.
8874     *
8875     * @throws PackageManagerException If bytecode could not be found when it should exist
8876     */
8877    private static void assertCodePolicy(PackageParser.Package pkg)
8878            throws PackageManagerException {
8879        final boolean shouldHaveCode =
8880                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8881        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8882            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8883                    "Package " + pkg.baseCodePath + " code is missing");
8884        }
8885
8886        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8887            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8888                final boolean splitShouldHaveCode =
8889                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8890                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8891                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8892                            "Package " + pkg.splitCodePaths[i] + " code is missing");
8893                }
8894            }
8895        }
8896    }
8897
8898    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8899            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8900                    throws PackageManagerException {
8901        if (DEBUG_PACKAGE_SCANNING) {
8902            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8903                Log.d(TAG, "Scanning package " + pkg.packageName);
8904        }
8905
8906        applyPolicy(pkg, policyFlags);
8907
8908        assertPackageIsValid(pkg, policyFlags, scanFlags);
8909
8910        // Initialize package source and resource directories
8911        final File scanFile = new File(pkg.codePath);
8912        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8913        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8914
8915        SharedUserSetting suid = null;
8916        PackageSetting pkgSetting = null;
8917
8918        // Getting the package setting may have a side-effect, so if we
8919        // are only checking if scan would succeed, stash a copy of the
8920        // old setting to restore at the end.
8921        PackageSetting nonMutatedPs = null;
8922
8923        // We keep references to the derived CPU Abis from settings in oder to reuse
8924        // them in the case where we're not upgrading or booting for the first time.
8925        String primaryCpuAbiFromSettings = null;
8926        String secondaryCpuAbiFromSettings = null;
8927
8928        // writer
8929        synchronized (mPackages) {
8930            if (pkg.mSharedUserId != null) {
8931                // SIDE EFFECTS; may potentially allocate a new shared user
8932                suid = mSettings.getSharedUserLPw(
8933                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
8934                if (DEBUG_PACKAGE_SCANNING) {
8935                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8936                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8937                                + "): packages=" + suid.packages);
8938                }
8939            }
8940
8941            // Check if we are renaming from an original package name.
8942            PackageSetting origPackage = null;
8943            String realName = null;
8944            if (pkg.mOriginalPackages != null) {
8945                // This package may need to be renamed to a previously
8946                // installed name.  Let's check on that...
8947                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8948                if (pkg.mOriginalPackages.contains(renamed)) {
8949                    // This package had originally been installed as the
8950                    // original name, and we have already taken care of
8951                    // transitioning to the new one.  Just update the new
8952                    // one to continue using the old name.
8953                    realName = pkg.mRealPackage;
8954                    if (!pkg.packageName.equals(renamed)) {
8955                        // Callers into this function may have already taken
8956                        // care of renaming the package; only do it here if
8957                        // it is not already done.
8958                        pkg.setPackageName(renamed);
8959                    }
8960                } else {
8961                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8962                        if ((origPackage = mSettings.getPackageLPr(
8963                                pkg.mOriginalPackages.get(i))) != null) {
8964                            // We do have the package already installed under its
8965                            // original name...  should we use it?
8966                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8967                                // New package is not compatible with original.
8968                                origPackage = null;
8969                                continue;
8970                            } else if (origPackage.sharedUser != null) {
8971                                // Make sure uid is compatible between packages.
8972                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8973                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8974                                            + " to " + pkg.packageName + ": old uid "
8975                                            + origPackage.sharedUser.name
8976                                            + " differs from " + pkg.mSharedUserId);
8977                                    origPackage = null;
8978                                    continue;
8979                                }
8980                                // TODO: Add case when shared user id is added [b/28144775]
8981                            } else {
8982                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8983                                        + pkg.packageName + " to old name " + origPackage.name);
8984                            }
8985                            break;
8986                        }
8987                    }
8988                }
8989            }
8990
8991            if (mTransferedPackages.contains(pkg.packageName)) {
8992                Slog.w(TAG, "Package " + pkg.packageName
8993                        + " was transferred to another, but its .apk remains");
8994            }
8995
8996            // See comments in nonMutatedPs declaration
8997            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8998                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
8999                if (foundPs != null) {
9000                    nonMutatedPs = new PackageSetting(foundPs);
9001                }
9002            }
9003
9004            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9005                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9006                if (foundPs != null) {
9007                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9008                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9009                }
9010            }
9011
9012            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9013            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9014                PackageManagerService.reportSettingsProblem(Log.WARN,
9015                        "Package " + pkg.packageName + " shared user changed from "
9016                                + (pkgSetting.sharedUser != null
9017                                        ? pkgSetting.sharedUser.name : "<nothing>")
9018                                + " to "
9019                                + (suid != null ? suid.name : "<nothing>")
9020                                + "; replacing with new");
9021                pkgSetting = null;
9022            }
9023            final PackageSetting oldPkgSetting =
9024                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9025            final PackageSetting disabledPkgSetting =
9026                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9027
9028            String[] usesStaticLibraries = null;
9029            if (pkg.usesStaticLibraries != null) {
9030                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9031                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9032            }
9033
9034            if (pkgSetting == null) {
9035                final String parentPackageName = (pkg.parentPackage != null)
9036                        ? pkg.parentPackage.packageName : null;
9037
9038                // REMOVE SharedUserSetting from method; update in a separate call
9039                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9040                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9041                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9042                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9043                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9044                        true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(),
9045                        UserManagerService.getInstance(), usesStaticLibraries,
9046                        pkg.usesStaticLibrariesVersions);
9047                // SIDE EFFECTS; updates system state; move elsewhere
9048                if (origPackage != null) {
9049                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9050                }
9051                mSettings.addUserToSettingLPw(pkgSetting);
9052            } else {
9053                // REMOVE SharedUserSetting from method; update in a separate call.
9054                //
9055                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9056                // secondaryCpuAbi are not known at this point so we always update them
9057                // to null here, only to reset them at a later point.
9058                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9059                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9060                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9061                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9062                        UserManagerService.getInstance(), usesStaticLibraries,
9063                        pkg.usesStaticLibrariesVersions);
9064            }
9065            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9066            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9067
9068            // SIDE EFFECTS; modifies system state; move elsewhere
9069            if (pkgSetting.origPackage != null) {
9070                // If we are first transitioning from an original package,
9071                // fix up the new package's name now.  We need to do this after
9072                // looking up the package under its new name, so getPackageLP
9073                // can take care of fiddling things correctly.
9074                pkg.setPackageName(origPackage.name);
9075
9076                // File a report about this.
9077                String msg = "New package " + pkgSetting.realName
9078                        + " renamed to replace old package " + pkgSetting.name;
9079                reportSettingsProblem(Log.WARN, msg);
9080
9081                // Make a note of it.
9082                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9083                    mTransferedPackages.add(origPackage.name);
9084                }
9085
9086                // No longer need to retain this.
9087                pkgSetting.origPackage = null;
9088            }
9089
9090            // SIDE EFFECTS; modifies system state; move elsewhere
9091            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9092                // Make a note of it.
9093                mTransferedPackages.add(pkg.packageName);
9094            }
9095
9096            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9097                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9098            }
9099
9100            if ((scanFlags & SCAN_BOOTING) == 0
9101                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9102                // Check all shared libraries and map to their actual file path.
9103                // We only do this here for apps not on a system dir, because those
9104                // are the only ones that can fail an install due to this.  We
9105                // will take care of the system apps by updating all of their
9106                // library paths after the scan is done. Also during the initial
9107                // scan don't update any libs as we do this wholesale after all
9108                // apps are scanned to avoid dependency based scanning.
9109                updateSharedLibrariesLPr(pkg, null);
9110            }
9111
9112            if (mFoundPolicyFile) {
9113                SELinuxMMAC.assignSeinfoValue(pkg);
9114            }
9115
9116            pkg.applicationInfo.uid = pkgSetting.appId;
9117            pkg.mExtras = pkgSetting;
9118
9119
9120            // Static shared libs have same package with different versions where
9121            // we internally use a synthetic package name to allow multiple versions
9122            // of the same package, therefore we need to compare signatures against
9123            // the package setting for the latest library version.
9124            PackageSetting signatureCheckPs = pkgSetting;
9125            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9126                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9127                if (libraryEntry != null) {
9128                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9129                }
9130            }
9131
9132            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9133                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9134                    // We just determined the app is signed correctly, so bring
9135                    // over the latest parsed certs.
9136                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9137                } else {
9138                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9139                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9140                                "Package " + pkg.packageName + " upgrade keys do not match the "
9141                                + "previously installed version");
9142                    } else {
9143                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9144                        String msg = "System package " + pkg.packageName
9145                                + " signature changed; retaining data.";
9146                        reportSettingsProblem(Log.WARN, msg);
9147                    }
9148                }
9149            } else {
9150                try {
9151                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9152                    verifySignaturesLP(signatureCheckPs, pkg);
9153                    // We just determined the app is signed correctly, so bring
9154                    // over the latest parsed certs.
9155                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9156                } catch (PackageManagerException e) {
9157                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9158                        throw e;
9159                    }
9160                    // The signature has changed, but this package is in the system
9161                    // image...  let's recover!
9162                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9163                    // However...  if this package is part of a shared user, but it
9164                    // doesn't match the signature of the shared user, let's fail.
9165                    // What this means is that you can't change the signatures
9166                    // associated with an overall shared user, which doesn't seem all
9167                    // that unreasonable.
9168                    if (signatureCheckPs.sharedUser != null) {
9169                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9170                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9171                            throw new PackageManagerException(
9172                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9173                                    "Signature mismatch for shared user: "
9174                                            + pkgSetting.sharedUser);
9175                        }
9176                    }
9177                    // File a report about this.
9178                    String msg = "System package " + pkg.packageName
9179                            + " signature changed; retaining data.";
9180                    reportSettingsProblem(Log.WARN, msg);
9181                }
9182            }
9183
9184            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9185                // This package wants to adopt ownership of permissions from
9186                // another package.
9187                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9188                    final String origName = pkg.mAdoptPermissions.get(i);
9189                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9190                    if (orig != null) {
9191                        if (verifyPackageUpdateLPr(orig, pkg)) {
9192                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9193                                    + pkg.packageName);
9194                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9195                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9196                        }
9197                    }
9198                }
9199            }
9200        }
9201
9202        pkg.applicationInfo.processName = fixProcessName(
9203                pkg.applicationInfo.packageName,
9204                pkg.applicationInfo.processName);
9205
9206        if (pkg != mPlatformPackage) {
9207            // Get all of our default paths setup
9208            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9209        }
9210
9211        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9212
9213        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9214            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9215                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9216                derivePackageAbi(
9217                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9218                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9219
9220                // Some system apps still use directory structure for native libraries
9221                // in which case we might end up not detecting abi solely based on apk
9222                // structure. Try to detect abi based on directory structure.
9223                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9224                        pkg.applicationInfo.primaryCpuAbi == null) {
9225                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9226                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9227                }
9228            } else {
9229                // This is not a first boot or an upgrade, don't bother deriving the
9230                // ABI during the scan. Instead, trust the value that was stored in the
9231                // package setting.
9232                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9233                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9234
9235                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9236
9237                if (DEBUG_ABI_SELECTION) {
9238                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9239                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9240                        pkg.applicationInfo.secondaryCpuAbi);
9241                }
9242            }
9243        } else {
9244            if ((scanFlags & SCAN_MOVE) != 0) {
9245                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9246                // but we already have this packages package info in the PackageSetting. We just
9247                // use that and derive the native library path based on the new codepath.
9248                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9249                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9250            }
9251
9252            // Set native library paths again. For moves, the path will be updated based on the
9253            // ABIs we've determined above. For non-moves, the path will be updated based on the
9254            // ABIs we determined during compilation, but the path will depend on the final
9255            // package path (after the rename away from the stage path).
9256            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9257        }
9258
9259        // This is a special case for the "system" package, where the ABI is
9260        // dictated by the zygote configuration (and init.rc). We should keep track
9261        // of this ABI so that we can deal with "normal" applications that run under
9262        // the same UID correctly.
9263        if (mPlatformPackage == pkg) {
9264            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9265                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9266        }
9267
9268        // If there's a mismatch between the abi-override in the package setting
9269        // and the abiOverride specified for the install. Warn about this because we
9270        // would've already compiled the app without taking the package setting into
9271        // account.
9272        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9273            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9274                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9275                        " for package " + pkg.packageName);
9276            }
9277        }
9278
9279        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9280        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9281        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9282
9283        // Copy the derived override back to the parsed package, so that we can
9284        // update the package settings accordingly.
9285        pkg.cpuAbiOverride = cpuAbiOverride;
9286
9287        if (DEBUG_ABI_SELECTION) {
9288            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9289                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9290                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9291        }
9292
9293        // Push the derived path down into PackageSettings so we know what to
9294        // clean up at uninstall time.
9295        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9296
9297        if (DEBUG_ABI_SELECTION) {
9298            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9299                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9300                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9301        }
9302
9303        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9304        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9305            // We don't do this here during boot because we can do it all
9306            // at once after scanning all existing packages.
9307            //
9308            // We also do this *before* we perform dexopt on this package, so that
9309            // we can avoid redundant dexopts, and also to make sure we've got the
9310            // code and package path correct.
9311            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9312        }
9313
9314        if (mFactoryTest && pkg.requestedPermissions.contains(
9315                android.Manifest.permission.FACTORY_TEST)) {
9316            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9317        }
9318
9319        if (isSystemApp(pkg)) {
9320            pkgSetting.isOrphaned = true;
9321        }
9322
9323        // Take care of first install / last update times.
9324        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9325        if (currentTime != 0) {
9326            if (pkgSetting.firstInstallTime == 0) {
9327                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9328            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9329                pkgSetting.lastUpdateTime = currentTime;
9330            }
9331        } else if (pkgSetting.firstInstallTime == 0) {
9332            // We need *something*.  Take time time stamp of the file.
9333            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9334        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9335            if (scanFileTime != pkgSetting.timeStamp) {
9336                // A package on the system image has changed; consider this
9337                // to be an update.
9338                pkgSetting.lastUpdateTime = scanFileTime;
9339            }
9340        }
9341        pkgSetting.setTimeStamp(scanFileTime);
9342
9343        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9344            if (nonMutatedPs != null) {
9345                synchronized (mPackages) {
9346                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9347                }
9348            }
9349        } else {
9350            // Modify state for the given package setting
9351            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9352                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9353            if (isEphemeral(pkg)) {
9354                final int userId = user == null ? 0 : user.getIdentifier();
9355                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9356            }
9357        }
9358        return pkg;
9359    }
9360
9361    /**
9362     * Applies policy to the parsed package based upon the given policy flags.
9363     * Ensures the package is in a good state.
9364     * <p>
9365     * Implementation detail: This method must NOT have any side effect. It would
9366     * ideally be static, but, it requires locks to read system state.
9367     */
9368    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9369        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9370            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9371            if (pkg.applicationInfo.isDirectBootAware()) {
9372                // we're direct boot aware; set for all components
9373                for (PackageParser.Service s : pkg.services) {
9374                    s.info.encryptionAware = s.info.directBootAware = true;
9375                }
9376                for (PackageParser.Provider p : pkg.providers) {
9377                    p.info.encryptionAware = p.info.directBootAware = true;
9378                }
9379                for (PackageParser.Activity a : pkg.activities) {
9380                    a.info.encryptionAware = a.info.directBootAware = true;
9381                }
9382                for (PackageParser.Activity r : pkg.receivers) {
9383                    r.info.encryptionAware = r.info.directBootAware = true;
9384                }
9385            }
9386        } else {
9387            // Only allow system apps to be flagged as core apps.
9388            pkg.coreApp = false;
9389            // clear flags not applicable to regular apps
9390            pkg.applicationInfo.privateFlags &=
9391                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
9392            pkg.applicationInfo.privateFlags &=
9393                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
9394        }
9395        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
9396
9397        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
9398            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9399        }
9400
9401        if (!isSystemApp(pkg)) {
9402            // Only system apps can use these features.
9403            pkg.mOriginalPackages = null;
9404            pkg.mRealPackage = null;
9405            pkg.mAdoptPermissions = null;
9406        }
9407    }
9408
9409    /**
9410     * Asserts the parsed package is valid according to the given policy. If the
9411     * package is invalid, for whatever reason, throws {@link PackgeManagerException}.
9412     * <p>
9413     * Implementation detail: This method must NOT have any side effects. It would
9414     * ideally be static, but, it requires locks to read system state.
9415     *
9416     * @throws PackageManagerException If the package fails any of the validation checks
9417     */
9418    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
9419            throws PackageManagerException {
9420        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
9421            assertCodePolicy(pkg);
9422        }
9423
9424        if (pkg.applicationInfo.getCodePath() == null ||
9425                pkg.applicationInfo.getResourcePath() == null) {
9426            // Bail out. The resource and code paths haven't been set.
9427            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9428                    "Code and resource paths haven't been set correctly");
9429        }
9430
9431        // Make sure we're not adding any bogus keyset info
9432        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9433        ksms.assertScannedPackageValid(pkg);
9434
9435        synchronized (mPackages) {
9436            // The special "android" package can only be defined once
9437            if (pkg.packageName.equals("android")) {
9438                if (mAndroidApplication != null) {
9439                    Slog.w(TAG, "*************************************************");
9440                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
9441                    Slog.w(TAG, " codePath=" + pkg.codePath);
9442                    Slog.w(TAG, "*************************************************");
9443                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9444                            "Core android package being redefined.  Skipping.");
9445                }
9446            }
9447
9448            // A package name must be unique; don't allow duplicates
9449            if (mPackages.containsKey(pkg.packageName)) {
9450                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9451                        "Application package " + pkg.packageName
9452                        + " already installed.  Skipping duplicate.");
9453            }
9454
9455            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9456                // Static libs have a synthetic package name containing the version
9457                // but we still want the base name to be unique.
9458                if (mPackages.containsKey(pkg.manifestPackageName)) {
9459                    throw new PackageManagerException(
9460                            "Duplicate static shared lib provider package");
9461                }
9462
9463                // Static shared libraries should have at least O target SDK
9464                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
9465                    throw new PackageManagerException(
9466                            "Packages declaring static-shared libs must target O SDK or higher");
9467                }
9468
9469                // Package declaring static a shared lib cannot be ephemeral
9470                if (pkg.applicationInfo.isInstantApp()) {
9471                    throw new PackageManagerException(
9472                            "Packages declaring static-shared libs cannot be ephemeral");
9473                }
9474
9475                // Package declaring static a shared lib cannot be renamed since the package
9476                // name is synthetic and apps can't code around package manager internals.
9477                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
9478                    throw new PackageManagerException(
9479                            "Packages declaring static-shared libs cannot be renamed");
9480                }
9481
9482                // Package declaring static a shared lib cannot declare child packages
9483                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
9484                    throw new PackageManagerException(
9485                            "Packages declaring static-shared libs cannot have child packages");
9486                }
9487
9488                // Package declaring static a shared lib cannot declare dynamic libs
9489                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
9490                    throw new PackageManagerException(
9491                            "Packages declaring static-shared libs cannot declare dynamic libs");
9492                }
9493
9494                // Package declaring static a shared lib cannot declare shared users
9495                if (pkg.mSharedUserId != null) {
9496                    throw new PackageManagerException(
9497                            "Packages declaring static-shared libs cannot declare shared users");
9498                }
9499
9500                // Static shared libs cannot declare activities
9501                if (!pkg.activities.isEmpty()) {
9502                    throw new PackageManagerException(
9503                            "Static shared libs cannot declare activities");
9504                }
9505
9506                // Static shared libs cannot declare services
9507                if (!pkg.services.isEmpty()) {
9508                    throw new PackageManagerException(
9509                            "Static shared libs cannot declare services");
9510                }
9511
9512                // Static shared libs cannot declare providers
9513                if (!pkg.providers.isEmpty()) {
9514                    throw new PackageManagerException(
9515                            "Static shared libs cannot declare content providers");
9516                }
9517
9518                // Static shared libs cannot declare receivers
9519                if (!pkg.receivers.isEmpty()) {
9520                    throw new PackageManagerException(
9521                            "Static shared libs cannot declare broadcast receivers");
9522                }
9523
9524                // Static shared libs cannot declare permission groups
9525                if (!pkg.permissionGroups.isEmpty()) {
9526                    throw new PackageManagerException(
9527                            "Static shared libs cannot declare permission groups");
9528                }
9529
9530                // Static shared libs cannot declare permissions
9531                if (!pkg.permissions.isEmpty()) {
9532                    throw new PackageManagerException(
9533                            "Static shared libs cannot declare permissions");
9534                }
9535
9536                // Static shared libs cannot declare protected broadcasts
9537                if (pkg.protectedBroadcasts != null) {
9538                    throw new PackageManagerException(
9539                            "Static shared libs cannot declare protected broadcasts");
9540                }
9541
9542                // Static shared libs cannot be overlay targets
9543                if (pkg.mOverlayTarget != null) {
9544                    throw new PackageManagerException(
9545                            "Static shared libs cannot be overlay targets");
9546                }
9547
9548                // The version codes must be ordered as lib versions
9549                int minVersionCode = Integer.MIN_VALUE;
9550                int maxVersionCode = Integer.MAX_VALUE;
9551
9552                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9553                        pkg.staticSharedLibName);
9554                if (versionedLib != null) {
9555                    final int versionCount = versionedLib.size();
9556                    for (int i = 0; i < versionCount; i++) {
9557                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
9558                        // TODO: We will change version code to long, so in the new API it is long
9559                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
9560                                .getVersionCode();
9561                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
9562                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
9563                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
9564                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
9565                        } else {
9566                            minVersionCode = maxVersionCode = libVersionCode;
9567                            break;
9568                        }
9569                    }
9570                }
9571                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
9572                    throw new PackageManagerException("Static shared"
9573                            + " lib version codes must be ordered as lib versions");
9574                }
9575            }
9576
9577            // Only privileged apps and updated privileged apps can add child packages.
9578            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
9579                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
9580                    throw new PackageManagerException("Only privileged apps can add child "
9581                            + "packages. Ignoring package " + pkg.packageName);
9582                }
9583                final int childCount = pkg.childPackages.size();
9584                for (int i = 0; i < childCount; i++) {
9585                    PackageParser.Package childPkg = pkg.childPackages.get(i);
9586                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
9587                            childPkg.packageName)) {
9588                        throw new PackageManagerException("Can't override child of "
9589                                + "another disabled app. Ignoring package " + pkg.packageName);
9590                    }
9591                }
9592            }
9593
9594            // If we're only installing presumed-existing packages, require that the
9595            // scanned APK is both already known and at the path previously established
9596            // for it.  Previously unknown packages we pick up normally, but if we have an
9597            // a priori expectation about this package's install presence, enforce it.
9598            // With a singular exception for new system packages. When an OTA contains
9599            // a new system package, we allow the codepath to change from a system location
9600            // to the user-installed location. If we don't allow this change, any newer,
9601            // user-installed version of the application will be ignored.
9602            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
9603                if (mExpectingBetter.containsKey(pkg.packageName)) {
9604                    logCriticalInfo(Log.WARN,
9605                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
9606                } else {
9607                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
9608                    if (known != null) {
9609                        if (DEBUG_PACKAGE_SCANNING) {
9610                            Log.d(TAG, "Examining " + pkg.codePath
9611                                    + " and requiring known paths " + known.codePathString
9612                                    + " & " + known.resourcePathString);
9613                        }
9614                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
9615                                || !pkg.applicationInfo.getResourcePath().equals(
9616                                        known.resourcePathString)) {
9617                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
9618                                    "Application package " + pkg.packageName
9619                                    + " found at " + pkg.applicationInfo.getCodePath()
9620                                    + " but expected at " + known.codePathString
9621                                    + "; ignoring.");
9622                        }
9623                    }
9624                }
9625            }
9626
9627            // Verify that this new package doesn't have any content providers
9628            // that conflict with existing packages.  Only do this if the
9629            // package isn't already installed, since we don't want to break
9630            // things that are installed.
9631            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
9632                final int N = pkg.providers.size();
9633                int i;
9634                for (i=0; i<N; i++) {
9635                    PackageParser.Provider p = pkg.providers.get(i);
9636                    if (p.info.authority != null) {
9637                        String names[] = p.info.authority.split(";");
9638                        for (int j = 0; j < names.length; j++) {
9639                            if (mProvidersByAuthority.containsKey(names[j])) {
9640                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9641                                final String otherPackageName =
9642                                        ((other != null && other.getComponentName() != null) ?
9643                                                other.getComponentName().getPackageName() : "?");
9644                                throw new PackageManagerException(
9645                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
9646                                        "Can't install because provider name " + names[j]
9647                                                + " (in package " + pkg.applicationInfo.packageName
9648                                                + ") is already used by " + otherPackageName);
9649                            }
9650                        }
9651                    }
9652                }
9653            }
9654        }
9655    }
9656
9657    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
9658            int type, String declaringPackageName, int declaringVersionCode) {
9659        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9660        if (versionedLib == null) {
9661            versionedLib = new SparseArray<>();
9662            mSharedLibraries.put(name, versionedLib);
9663            if (type == SharedLibraryInfo.TYPE_STATIC) {
9664                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
9665            }
9666        } else if (versionedLib.indexOfKey(version) >= 0) {
9667            return false;
9668        }
9669        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
9670                version, type, declaringPackageName, declaringVersionCode);
9671        versionedLib.put(version, libEntry);
9672        return true;
9673    }
9674
9675    private boolean removeSharedLibraryLPw(String name, int version) {
9676        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9677        if (versionedLib == null) {
9678            return false;
9679        }
9680        final int libIdx = versionedLib.indexOfKey(version);
9681        if (libIdx < 0) {
9682            return false;
9683        }
9684        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
9685        versionedLib.remove(version);
9686        if (versionedLib.size() <= 0) {
9687            mSharedLibraries.remove(name);
9688            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
9689                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
9690                        .getPackageName());
9691            }
9692        }
9693        return true;
9694    }
9695
9696    /**
9697     * Adds a scanned package to the system. When this method is finished, the package will
9698     * be available for query, resolution, etc...
9699     */
9700    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
9701            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
9702        final String pkgName = pkg.packageName;
9703        if (mCustomResolverComponentName != null &&
9704                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
9705            setUpCustomResolverActivity(pkg);
9706        }
9707
9708        if (pkg.packageName.equals("android")) {
9709            synchronized (mPackages) {
9710                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9711                    // Set up information for our fall-back user intent resolution activity.
9712                    mPlatformPackage = pkg;
9713                    pkg.mVersionCode = mSdkVersion;
9714                    mAndroidApplication = pkg.applicationInfo;
9715
9716                    if (!mResolverReplaced) {
9717                        mResolveActivity.applicationInfo = mAndroidApplication;
9718                        mResolveActivity.name = ResolverActivity.class.getName();
9719                        mResolveActivity.packageName = mAndroidApplication.packageName;
9720                        mResolveActivity.processName = "system:ui";
9721                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9722                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
9723                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
9724                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
9725                        mResolveActivity.exported = true;
9726                        mResolveActivity.enabled = true;
9727                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
9728                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
9729                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
9730                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
9731                                | ActivityInfo.CONFIG_ORIENTATION
9732                                | ActivityInfo.CONFIG_KEYBOARD
9733                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
9734                        mResolveInfo.activityInfo = mResolveActivity;
9735                        mResolveInfo.priority = 0;
9736                        mResolveInfo.preferredOrder = 0;
9737                        mResolveInfo.match = 0;
9738                        mResolveComponentName = new ComponentName(
9739                                mAndroidApplication.packageName, mResolveActivity.name);
9740                    }
9741                }
9742            }
9743        }
9744
9745        ArrayList<PackageParser.Package> clientLibPkgs = null;
9746        // writer
9747        synchronized (mPackages) {
9748            boolean hasStaticSharedLibs = false;
9749
9750            // Any app can add new static shared libraries
9751            if (pkg.staticSharedLibName != null) {
9752                // Static shared libs don't allow renaming as they have synthetic package
9753                // names to allow install of multiple versions, so use name from manifest.
9754                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
9755                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
9756                        pkg.manifestPackageName, pkg.mVersionCode)) {
9757                    hasStaticSharedLibs = true;
9758                } else {
9759                    Slog.w(TAG, "Package " + pkg.packageName + " library "
9760                                + pkg.staticSharedLibName + " already exists; skipping");
9761                }
9762                // Static shared libs cannot be updated once installed since they
9763                // use synthetic package name which includes the version code, so
9764                // not need to update other packages's shared lib dependencies.
9765            }
9766
9767            if (!hasStaticSharedLibs
9768                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9769                // Only system apps can add new dynamic shared libraries.
9770                if (pkg.libraryNames != null) {
9771                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
9772                        String name = pkg.libraryNames.get(i);
9773                        boolean allowed = false;
9774                        if (pkg.isUpdatedSystemApp()) {
9775                            // New library entries can only be added through the
9776                            // system image.  This is important to get rid of a lot
9777                            // of nasty edge cases: for example if we allowed a non-
9778                            // system update of the app to add a library, then uninstalling
9779                            // the update would make the library go away, and assumptions
9780                            // we made such as through app install filtering would now
9781                            // have allowed apps on the device which aren't compatible
9782                            // with it.  Better to just have the restriction here, be
9783                            // conservative, and create many fewer cases that can negatively
9784                            // impact the user experience.
9785                            final PackageSetting sysPs = mSettings
9786                                    .getDisabledSystemPkgLPr(pkg.packageName);
9787                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
9788                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
9789                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
9790                                        allowed = true;
9791                                        break;
9792                                    }
9793                                }
9794                            }
9795                        } else {
9796                            allowed = true;
9797                        }
9798                        if (allowed) {
9799                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
9800                                    SharedLibraryInfo.VERSION_UNDEFINED,
9801                                    SharedLibraryInfo.TYPE_DYNAMIC,
9802                                    pkg.packageName, pkg.mVersionCode)) {
9803                                Slog.w(TAG, "Package " + pkg.packageName + " library "
9804                                        + name + " already exists; skipping");
9805                            }
9806                        } else {
9807                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
9808                                    + name + " that is not declared on system image; skipping");
9809                        }
9810                    }
9811
9812                    if ((scanFlags & SCAN_BOOTING) == 0) {
9813                        // If we are not booting, we need to update any applications
9814                        // that are clients of our shared library.  If we are booting,
9815                        // this will all be done once the scan is complete.
9816                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
9817                    }
9818                }
9819            }
9820        }
9821
9822        if ((scanFlags & SCAN_BOOTING) != 0) {
9823            // No apps can run during boot scan, so they don't need to be frozen
9824        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
9825            // Caller asked to not kill app, so it's probably not frozen
9826        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
9827            // Caller asked us to ignore frozen check for some reason; they
9828            // probably didn't know the package name
9829        } else {
9830            // We're doing major surgery on this package, so it better be frozen
9831            // right now to keep it from launching
9832            checkPackageFrozen(pkgName);
9833        }
9834
9835        // Also need to kill any apps that are dependent on the library.
9836        if (clientLibPkgs != null) {
9837            for (int i=0; i<clientLibPkgs.size(); i++) {
9838                PackageParser.Package clientPkg = clientLibPkgs.get(i);
9839                killApplication(clientPkg.applicationInfo.packageName,
9840                        clientPkg.applicationInfo.uid, "update lib");
9841            }
9842        }
9843
9844        // writer
9845        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
9846
9847        boolean createIdmapFailed = false;
9848        synchronized (mPackages) {
9849            // We don't expect installation to fail beyond this point
9850
9851            if (pkgSetting.pkg != null) {
9852                // Note that |user| might be null during the initial boot scan. If a codePath
9853                // for an app has changed during a boot scan, it's due to an app update that's
9854                // part of the system partition and marker changes must be applied to all users.
9855                final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier();
9856                final int[] userIds = resolveUserIds(userId);
9857                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds);
9858            }
9859
9860            // Add the new setting to mSettings
9861            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
9862            // Add the new setting to mPackages
9863            mPackages.put(pkg.applicationInfo.packageName, pkg);
9864            // Make sure we don't accidentally delete its data.
9865            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
9866            while (iter.hasNext()) {
9867                PackageCleanItem item = iter.next();
9868                if (pkgName.equals(item.packageName)) {
9869                    iter.remove();
9870                }
9871            }
9872
9873            // Add the package's KeySets to the global KeySetManagerService
9874            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9875            ksms.addScannedPackageLPw(pkg);
9876
9877            int N = pkg.providers.size();
9878            StringBuilder r = null;
9879            int i;
9880            for (i=0; i<N; i++) {
9881                PackageParser.Provider p = pkg.providers.get(i);
9882                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
9883                        p.info.processName);
9884                mProviders.addProvider(p);
9885                p.syncable = p.info.isSyncable;
9886                if (p.info.authority != null) {
9887                    String names[] = p.info.authority.split(";");
9888                    p.info.authority = null;
9889                    for (int j = 0; j < names.length; j++) {
9890                        if (j == 1 && p.syncable) {
9891                            // We only want the first authority for a provider to possibly be
9892                            // syncable, so if we already added this provider using a different
9893                            // authority clear the syncable flag. We copy the provider before
9894                            // changing it because the mProviders object contains a reference
9895                            // to a provider that we don't want to change.
9896                            // Only do this for the second authority since the resulting provider
9897                            // object can be the same for all future authorities for this provider.
9898                            p = new PackageParser.Provider(p);
9899                            p.syncable = false;
9900                        }
9901                        if (!mProvidersByAuthority.containsKey(names[j])) {
9902                            mProvidersByAuthority.put(names[j], p);
9903                            if (p.info.authority == null) {
9904                                p.info.authority = names[j];
9905                            } else {
9906                                p.info.authority = p.info.authority + ";" + names[j];
9907                            }
9908                            if (DEBUG_PACKAGE_SCANNING) {
9909                                if (chatty)
9910                                    Log.d(TAG, "Registered content provider: " + names[j]
9911                                            + ", className = " + p.info.name + ", isSyncable = "
9912                                            + p.info.isSyncable);
9913                            }
9914                        } else {
9915                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9916                            Slog.w(TAG, "Skipping provider name " + names[j] +
9917                                    " (in package " + pkg.applicationInfo.packageName +
9918                                    "): name already used by "
9919                                    + ((other != null && other.getComponentName() != null)
9920                                            ? other.getComponentName().getPackageName() : "?"));
9921                        }
9922                    }
9923                }
9924                if (chatty) {
9925                    if (r == null) {
9926                        r = new StringBuilder(256);
9927                    } else {
9928                        r.append(' ');
9929                    }
9930                    r.append(p.info.name);
9931                }
9932            }
9933            if (r != null) {
9934                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
9935            }
9936
9937            N = pkg.services.size();
9938            r = null;
9939            for (i=0; i<N; i++) {
9940                PackageParser.Service s = pkg.services.get(i);
9941                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
9942                        s.info.processName);
9943                mServices.addService(s);
9944                if (chatty) {
9945                    if (r == null) {
9946                        r = new StringBuilder(256);
9947                    } else {
9948                        r.append(' ');
9949                    }
9950                    r.append(s.info.name);
9951                }
9952            }
9953            if (r != null) {
9954                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
9955            }
9956
9957            N = pkg.receivers.size();
9958            r = null;
9959            for (i=0; i<N; i++) {
9960                PackageParser.Activity a = pkg.receivers.get(i);
9961                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
9962                        a.info.processName);
9963                mReceivers.addActivity(a, "receiver");
9964                if (chatty) {
9965                    if (r == null) {
9966                        r = new StringBuilder(256);
9967                    } else {
9968                        r.append(' ');
9969                    }
9970                    r.append(a.info.name);
9971                }
9972            }
9973            if (r != null) {
9974                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
9975            }
9976
9977            N = pkg.activities.size();
9978            r = null;
9979            for (i=0; i<N; i++) {
9980                PackageParser.Activity a = pkg.activities.get(i);
9981                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
9982                        a.info.processName);
9983                mActivities.addActivity(a, "activity");
9984                if (chatty) {
9985                    if (r == null) {
9986                        r = new StringBuilder(256);
9987                    } else {
9988                        r.append(' ');
9989                    }
9990                    r.append(a.info.name);
9991                }
9992            }
9993            if (r != null) {
9994                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
9995            }
9996
9997            N = pkg.permissionGroups.size();
9998            r = null;
9999            for (i=0; i<N; i++) {
10000                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
10001                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10002                final String curPackageName = cur == null ? null : cur.info.packageName;
10003                // Dont allow ephemeral apps to define new permission groups.
10004                if (pkg.applicationInfo.isInstantApp()) {
10005                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10006                            + pg.info.packageName
10007                            + " ignored: ephemeral apps cannot define new permission groups.");
10008                    continue;
10009                }
10010                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10011                if (cur == null || isPackageUpdate) {
10012                    mPermissionGroups.put(pg.info.name, pg);
10013                    if (chatty) {
10014                        if (r == null) {
10015                            r = new StringBuilder(256);
10016                        } else {
10017                            r.append(' ');
10018                        }
10019                        if (isPackageUpdate) {
10020                            r.append("UPD:");
10021                        }
10022                        r.append(pg.info.name);
10023                    }
10024                } else {
10025                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10026                            + pg.info.packageName + " ignored: original from "
10027                            + cur.info.packageName);
10028                    if (chatty) {
10029                        if (r == null) {
10030                            r = new StringBuilder(256);
10031                        } else {
10032                            r.append(' ');
10033                        }
10034                        r.append("DUP:");
10035                        r.append(pg.info.name);
10036                    }
10037                }
10038            }
10039            if (r != null) {
10040                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10041            }
10042
10043            N = pkg.permissions.size();
10044            r = null;
10045            for (i=0; i<N; i++) {
10046                PackageParser.Permission p = pkg.permissions.get(i);
10047
10048                // Dont allow ephemeral apps to define new permissions.
10049                if (pkg.applicationInfo.isInstantApp()) {
10050                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10051                            + p.info.packageName
10052                            + " ignored: ephemeral apps cannot define new permissions.");
10053                    continue;
10054                }
10055
10056                // Assume by default that we did not install this permission into the system.
10057                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10058
10059                // Now that permission groups have a special meaning, we ignore permission
10060                // groups for legacy apps to prevent unexpected behavior. In particular,
10061                // permissions for one app being granted to someone just becase they happen
10062                // to be in a group defined by another app (before this had no implications).
10063                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10064                    p.group = mPermissionGroups.get(p.info.group);
10065                    // Warn for a permission in an unknown group.
10066                    if (p.info.group != null && p.group == null) {
10067                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10068                                + p.info.packageName + " in an unknown group " + p.info.group);
10069                    }
10070                }
10071
10072                ArrayMap<String, BasePermission> permissionMap =
10073                        p.tree ? mSettings.mPermissionTrees
10074                                : mSettings.mPermissions;
10075                BasePermission bp = permissionMap.get(p.info.name);
10076
10077                // Allow system apps to redefine non-system permissions
10078                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10079                    final boolean currentOwnerIsSystem = (bp.perm != null
10080                            && isSystemApp(bp.perm.owner));
10081                    if (isSystemApp(p.owner)) {
10082                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10083                            // It's a built-in permission and no owner, take ownership now
10084                            bp.packageSetting = pkgSetting;
10085                            bp.perm = p;
10086                            bp.uid = pkg.applicationInfo.uid;
10087                            bp.sourcePackage = p.info.packageName;
10088                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10089                        } else if (!currentOwnerIsSystem) {
10090                            String msg = "New decl " + p.owner + " of permission  "
10091                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10092                            reportSettingsProblem(Log.WARN, msg);
10093                            bp = null;
10094                        }
10095                    }
10096                }
10097
10098                if (bp == null) {
10099                    bp = new BasePermission(p.info.name, p.info.packageName,
10100                            BasePermission.TYPE_NORMAL);
10101                    permissionMap.put(p.info.name, bp);
10102                }
10103
10104                if (bp.perm == null) {
10105                    if (bp.sourcePackage == null
10106                            || bp.sourcePackage.equals(p.info.packageName)) {
10107                        BasePermission tree = findPermissionTreeLP(p.info.name);
10108                        if (tree == null
10109                                || tree.sourcePackage.equals(p.info.packageName)) {
10110                            bp.packageSetting = pkgSetting;
10111                            bp.perm = p;
10112                            bp.uid = pkg.applicationInfo.uid;
10113                            bp.sourcePackage = p.info.packageName;
10114                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10115                            if (chatty) {
10116                                if (r == null) {
10117                                    r = new StringBuilder(256);
10118                                } else {
10119                                    r.append(' ');
10120                                }
10121                                r.append(p.info.name);
10122                            }
10123                        } else {
10124                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10125                                    + p.info.packageName + " ignored: base tree "
10126                                    + tree.name + " is from package "
10127                                    + tree.sourcePackage);
10128                        }
10129                    } else {
10130                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10131                                + p.info.packageName + " ignored: original from "
10132                                + bp.sourcePackage);
10133                    }
10134                } else if (chatty) {
10135                    if (r == null) {
10136                        r = new StringBuilder(256);
10137                    } else {
10138                        r.append(' ');
10139                    }
10140                    r.append("DUP:");
10141                    r.append(p.info.name);
10142                }
10143                if (bp.perm == p) {
10144                    bp.protectionLevel = p.info.protectionLevel;
10145                }
10146            }
10147
10148            if (r != null) {
10149                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10150            }
10151
10152            N = pkg.instrumentation.size();
10153            r = null;
10154            for (i=0; i<N; i++) {
10155                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10156                a.info.packageName = pkg.applicationInfo.packageName;
10157                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10158                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10159                a.info.splitNames = pkg.splitNames;
10160                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10161                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10162                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10163                a.info.dataDir = pkg.applicationInfo.dataDir;
10164                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10165                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10166                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10167                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10168                mInstrumentation.put(a.getComponentName(), a);
10169                if (chatty) {
10170                    if (r == null) {
10171                        r = new StringBuilder(256);
10172                    } else {
10173                        r.append(' ');
10174                    }
10175                    r.append(a.info.name);
10176                }
10177            }
10178            if (r != null) {
10179                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10180            }
10181
10182            if (pkg.protectedBroadcasts != null) {
10183                N = pkg.protectedBroadcasts.size();
10184                for (i=0; i<N; i++) {
10185                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10186                }
10187            }
10188
10189            // Create idmap files for pairs of (packages, overlay packages).
10190            // Note: "android", ie framework-res.apk, is handled by native layers.
10191            if (pkg.mOverlayTarget != null) {
10192                // This is an overlay package.
10193                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
10194                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
10195                        mOverlays.put(pkg.mOverlayTarget,
10196                                new ArrayMap<String, PackageParser.Package>());
10197                    }
10198                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
10199                    map.put(pkg.packageName, pkg);
10200                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
10201                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
10202                        createIdmapFailed = true;
10203                    }
10204                }
10205            } else if (mOverlays.containsKey(pkg.packageName) &&
10206                    !pkg.packageName.equals("android")) {
10207                // This is a regular package, with one or more known overlay packages.
10208                createIdmapsForPackageLI(pkg);
10209            }
10210        }
10211
10212        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10213
10214        if (createIdmapFailed) {
10215            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10216                    "scanPackageLI failed to createIdmap");
10217        }
10218    }
10219
10220    private static void maybeRenameForeignDexMarkers(PackageParser.Package existing,
10221            PackageParser.Package update, int[] userIds) {
10222        if (existing.applicationInfo == null || update.applicationInfo == null) {
10223            // This isn't due to an app installation.
10224            return;
10225        }
10226
10227        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
10228        final File newCodePath = new File(update.applicationInfo.getCodePath());
10229
10230        // The codePath hasn't changed, so there's nothing for us to do.
10231        if (Objects.equals(oldCodePath, newCodePath)) {
10232            return;
10233        }
10234
10235        File canonicalNewCodePath;
10236        try {
10237            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
10238        } catch (IOException e) {
10239            Slog.w(TAG, "Failed to get canonical path.", e);
10240            return;
10241        }
10242
10243        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
10244        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
10245        // that the last component of the path (i.e, the name) doesn't need canonicalization
10246        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
10247        // but may change in the future. Hopefully this function won't exist at that point.
10248        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
10249                oldCodePath.getName());
10250
10251        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
10252        // with "@".
10253        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
10254        if (!oldMarkerPrefix.endsWith("@")) {
10255            oldMarkerPrefix += "@";
10256        }
10257        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
10258        if (!newMarkerPrefix.endsWith("@")) {
10259            newMarkerPrefix += "@";
10260        }
10261
10262        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
10263        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
10264        for (String updatedPath : updatedPaths) {
10265            String updatedPathName = new File(updatedPath).getName();
10266            markerSuffixes.add(updatedPathName.replace('/', '@'));
10267        }
10268
10269        for (int userId : userIds) {
10270            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
10271
10272            for (String markerSuffix : markerSuffixes) {
10273                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
10274                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
10275                if (oldForeignUseMark.exists()) {
10276                    try {
10277                        Os.rename(oldForeignUseMark.getAbsolutePath(),
10278                                newForeignUseMark.getAbsolutePath());
10279                    } catch (ErrnoException e) {
10280                        Slog.w(TAG, "Failed to rename foreign use marker", e);
10281                        oldForeignUseMark.delete();
10282                    }
10283                }
10284            }
10285        }
10286    }
10287
10288    /**
10289     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10290     * is derived purely on the basis of the contents of {@code scanFile} and
10291     * {@code cpuAbiOverride}.
10292     *
10293     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10294     */
10295    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10296                                 String cpuAbiOverride, boolean extractLibs,
10297                                 File appLib32InstallDir)
10298            throws PackageManagerException {
10299        // Give ourselves some initial paths; we'll come back for another
10300        // pass once we've determined ABI below.
10301        setNativeLibraryPaths(pkg, appLib32InstallDir);
10302
10303        // We would never need to extract libs for forward-locked and external packages,
10304        // since the container service will do it for us. We shouldn't attempt to
10305        // extract libs from system app when it was not updated.
10306        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10307                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10308            extractLibs = false;
10309        }
10310
10311        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10312        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10313
10314        NativeLibraryHelper.Handle handle = null;
10315        try {
10316            handle = NativeLibraryHelper.Handle.create(pkg);
10317            // TODO(multiArch): This can be null for apps that didn't go through the
10318            // usual installation process. We can calculate it again, like we
10319            // do during install time.
10320            //
10321            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10322            // unnecessary.
10323            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10324
10325            // Null out the abis so that they can be recalculated.
10326            pkg.applicationInfo.primaryCpuAbi = null;
10327            pkg.applicationInfo.secondaryCpuAbi = null;
10328            if (isMultiArch(pkg.applicationInfo)) {
10329                // Warn if we've set an abiOverride for multi-lib packages..
10330                // By definition, we need to copy both 32 and 64 bit libraries for
10331                // such packages.
10332                if (pkg.cpuAbiOverride != null
10333                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10334                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10335                }
10336
10337                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10338                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10339                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10340                    if (extractLibs) {
10341                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10342                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10343                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10344                                useIsaSpecificSubdirs);
10345                    } else {
10346                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10347                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10348                    }
10349                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10350                }
10351
10352                maybeThrowExceptionForMultiArchCopy(
10353                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10354
10355                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10356                    if (extractLibs) {
10357                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10358                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10359                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10360                                useIsaSpecificSubdirs);
10361                    } else {
10362                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10363                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10364                    }
10365                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10366                }
10367
10368                maybeThrowExceptionForMultiArchCopy(
10369                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10370
10371                if (abi64 >= 0) {
10372                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10373                }
10374
10375                if (abi32 >= 0) {
10376                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10377                    if (abi64 >= 0) {
10378                        if (pkg.use32bitAbi) {
10379                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10380                            pkg.applicationInfo.primaryCpuAbi = abi;
10381                        } else {
10382                            pkg.applicationInfo.secondaryCpuAbi = abi;
10383                        }
10384                    } else {
10385                        pkg.applicationInfo.primaryCpuAbi = abi;
10386                    }
10387                }
10388
10389            } else {
10390                String[] abiList = (cpuAbiOverride != null) ?
10391                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10392
10393                // Enable gross and lame hacks for apps that are built with old
10394                // SDK tools. We must scan their APKs for renderscript bitcode and
10395                // not launch them if it's present. Don't bother checking on devices
10396                // that don't have 64 bit support.
10397                boolean needsRenderScriptOverride = false;
10398                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10399                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10400                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10401                    needsRenderScriptOverride = true;
10402                }
10403
10404                final int copyRet;
10405                if (extractLibs) {
10406                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10407                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10408                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10409                } else {
10410                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10411                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10412                }
10413                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10414
10415                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10416                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10417                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10418                }
10419
10420                if (copyRet >= 0) {
10421                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10422                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10423                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10424                } else if (needsRenderScriptOverride) {
10425                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10426                }
10427            }
10428        } catch (IOException ioe) {
10429            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10430        } finally {
10431            IoUtils.closeQuietly(handle);
10432        }
10433
10434        // Now that we've calculated the ABIs and determined if it's an internal app,
10435        // we will go ahead and populate the nativeLibraryPath.
10436        setNativeLibraryPaths(pkg, appLib32InstallDir);
10437    }
10438
10439    /**
10440     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10441     * i.e, so that all packages can be run inside a single process if required.
10442     *
10443     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10444     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10445     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10446     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10447     * updating a package that belongs to a shared user.
10448     *
10449     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10450     * adds unnecessary complexity.
10451     */
10452    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10453            PackageParser.Package scannedPackage) {
10454        String requiredInstructionSet = null;
10455        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10456            requiredInstructionSet = VMRuntime.getInstructionSet(
10457                     scannedPackage.applicationInfo.primaryCpuAbi);
10458        }
10459
10460        PackageSetting requirer = null;
10461        for (PackageSetting ps : packagesForUser) {
10462            // If packagesForUser contains scannedPackage, we skip it. This will happen
10463            // when scannedPackage is an update of an existing package. Without this check,
10464            // we will never be able to change the ABI of any package belonging to a shared
10465            // user, even if it's compatible with other packages.
10466            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10467                if (ps.primaryCpuAbiString == null) {
10468                    continue;
10469                }
10470
10471                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10472                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10473                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10474                    // this but there's not much we can do.
10475                    String errorMessage = "Instruction set mismatch, "
10476                            + ((requirer == null) ? "[caller]" : requirer)
10477                            + " requires " + requiredInstructionSet + " whereas " + ps
10478                            + " requires " + instructionSet;
10479                    Slog.w(TAG, errorMessage);
10480                }
10481
10482                if (requiredInstructionSet == null) {
10483                    requiredInstructionSet = instructionSet;
10484                    requirer = ps;
10485                }
10486            }
10487        }
10488
10489        if (requiredInstructionSet != null) {
10490            String adjustedAbi;
10491            if (requirer != null) {
10492                // requirer != null implies that either scannedPackage was null or that scannedPackage
10493                // did not require an ABI, in which case we have to adjust scannedPackage to match
10494                // the ABI of the set (which is the same as requirer's ABI)
10495                adjustedAbi = requirer.primaryCpuAbiString;
10496                if (scannedPackage != null) {
10497                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10498                }
10499            } else {
10500                // requirer == null implies that we're updating all ABIs in the set to
10501                // match scannedPackage.
10502                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10503            }
10504
10505            for (PackageSetting ps : packagesForUser) {
10506                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10507                    if (ps.primaryCpuAbiString != null) {
10508                        continue;
10509                    }
10510
10511                    ps.primaryCpuAbiString = adjustedAbi;
10512                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
10513                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
10514                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
10515                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
10516                                + " (requirer="
10517                                + (requirer == null ? "null" : requirer.pkg.packageName)
10518                                + ", scannedPackage="
10519                                + (scannedPackage != null ? scannedPackage.packageName : "null")
10520                                + ")");
10521                        try {
10522                            mInstaller.rmdex(ps.codePathString,
10523                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
10524                        } catch (InstallerException ignored) {
10525                        }
10526                    }
10527                }
10528            }
10529        }
10530    }
10531
10532    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
10533        synchronized (mPackages) {
10534            mResolverReplaced = true;
10535            // Set up information for custom user intent resolution activity.
10536            mResolveActivity.applicationInfo = pkg.applicationInfo;
10537            mResolveActivity.name = mCustomResolverComponentName.getClassName();
10538            mResolveActivity.packageName = pkg.applicationInfo.packageName;
10539            mResolveActivity.processName = pkg.applicationInfo.packageName;
10540            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10541            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
10542                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10543            mResolveActivity.theme = 0;
10544            mResolveActivity.exported = true;
10545            mResolveActivity.enabled = true;
10546            mResolveInfo.activityInfo = mResolveActivity;
10547            mResolveInfo.priority = 0;
10548            mResolveInfo.preferredOrder = 0;
10549            mResolveInfo.match = 0;
10550            mResolveComponentName = mCustomResolverComponentName;
10551            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
10552                    mResolveComponentName);
10553        }
10554    }
10555
10556    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
10557        if (installerComponent == null) {
10558            if (DEBUG_EPHEMERAL) {
10559                Slog.d(TAG, "Clear ephemeral installer activity");
10560            }
10561            mEphemeralInstallerActivity.applicationInfo = null;
10562            return;
10563        }
10564
10565        if (DEBUG_EPHEMERAL) {
10566            Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent);
10567        }
10568        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
10569        // Set up information for ephemeral installer activity
10570        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
10571        mEphemeralInstallerActivity.name = installerComponent.getClassName();
10572        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
10573        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
10574        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10575        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
10576                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10577        mEphemeralInstallerActivity.theme = 0;
10578        mEphemeralInstallerActivity.exported = true;
10579        mEphemeralInstallerActivity.enabled = true;
10580        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
10581        mEphemeralInstallerInfo.priority = 0;
10582        mEphemeralInstallerInfo.preferredOrder = 1;
10583        mEphemeralInstallerInfo.isDefault = true;
10584        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
10585                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
10586    }
10587
10588    private static String calculateBundledApkRoot(final String codePathString) {
10589        final File codePath = new File(codePathString);
10590        final File codeRoot;
10591        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
10592            codeRoot = Environment.getRootDirectory();
10593        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
10594            codeRoot = Environment.getOemDirectory();
10595        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
10596            codeRoot = Environment.getVendorDirectory();
10597        } else {
10598            // Unrecognized code path; take its top real segment as the apk root:
10599            // e.g. /something/app/blah.apk => /something
10600            try {
10601                File f = codePath.getCanonicalFile();
10602                File parent = f.getParentFile();    // non-null because codePath is a file
10603                File tmp;
10604                while ((tmp = parent.getParentFile()) != null) {
10605                    f = parent;
10606                    parent = tmp;
10607                }
10608                codeRoot = f;
10609                Slog.w(TAG, "Unrecognized code path "
10610                        + codePath + " - using " + codeRoot);
10611            } catch (IOException e) {
10612                // Can't canonicalize the code path -- shenanigans?
10613                Slog.w(TAG, "Can't canonicalize code path " + codePath);
10614                return Environment.getRootDirectory().getPath();
10615            }
10616        }
10617        return codeRoot.getPath();
10618    }
10619
10620    /**
10621     * Derive and set the location of native libraries for the given package,
10622     * which varies depending on where and how the package was installed.
10623     */
10624    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
10625        final ApplicationInfo info = pkg.applicationInfo;
10626        final String codePath = pkg.codePath;
10627        final File codeFile = new File(codePath);
10628        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
10629        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
10630
10631        info.nativeLibraryRootDir = null;
10632        info.nativeLibraryRootRequiresIsa = false;
10633        info.nativeLibraryDir = null;
10634        info.secondaryNativeLibraryDir = null;
10635
10636        if (isApkFile(codeFile)) {
10637            // Monolithic install
10638            if (bundledApp) {
10639                // If "/system/lib64/apkname" exists, assume that is the per-package
10640                // native library directory to use; otherwise use "/system/lib/apkname".
10641                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
10642                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
10643                        getPrimaryInstructionSet(info));
10644
10645                // This is a bundled system app so choose the path based on the ABI.
10646                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
10647                // is just the default path.
10648                final String apkName = deriveCodePathName(codePath);
10649                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
10650                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
10651                        apkName).getAbsolutePath();
10652
10653                if (info.secondaryCpuAbi != null) {
10654                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
10655                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
10656                            secondaryLibDir, apkName).getAbsolutePath();
10657                }
10658            } else if (asecApp) {
10659                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
10660                        .getAbsolutePath();
10661            } else {
10662                final String apkName = deriveCodePathName(codePath);
10663                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
10664                        .getAbsolutePath();
10665            }
10666
10667            info.nativeLibraryRootRequiresIsa = false;
10668            info.nativeLibraryDir = info.nativeLibraryRootDir;
10669        } else {
10670            // Cluster install
10671            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10672            info.nativeLibraryRootRequiresIsa = true;
10673
10674            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10675                    getPrimaryInstructionSet(info)).getAbsolutePath();
10676
10677            if (info.secondaryCpuAbi != null) {
10678                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10679                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10680            }
10681        }
10682    }
10683
10684    /**
10685     * Calculate the abis and roots for a bundled app. These can uniquely
10686     * be determined from the contents of the system partition, i.e whether
10687     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10688     * of this information, and instead assume that the system was built
10689     * sensibly.
10690     */
10691    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10692                                           PackageSetting pkgSetting) {
10693        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10694
10695        // If "/system/lib64/apkname" exists, assume that is the per-package
10696        // native library directory to use; otherwise use "/system/lib/apkname".
10697        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10698        setBundledAppAbi(pkg, apkRoot, apkName);
10699        // pkgSetting might be null during rescan following uninstall of updates
10700        // to a bundled app, so accommodate that possibility.  The settings in
10701        // that case will be established later from the parsed package.
10702        //
10703        // If the settings aren't null, sync them up with what we've just derived.
10704        // note that apkRoot isn't stored in the package settings.
10705        if (pkgSetting != null) {
10706            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10707            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10708        }
10709    }
10710
10711    /**
10712     * Deduces the ABI of a bundled app and sets the relevant fields on the
10713     * parsed pkg object.
10714     *
10715     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
10716     *        under which system libraries are installed.
10717     * @param apkName the name of the installed package.
10718     */
10719    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
10720        final File codeFile = new File(pkg.codePath);
10721
10722        final boolean has64BitLibs;
10723        final boolean has32BitLibs;
10724        if (isApkFile(codeFile)) {
10725            // Monolithic install
10726            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
10727            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
10728        } else {
10729            // Cluster install
10730            final File rootDir = new File(codeFile, LIB_DIR_NAME);
10731            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
10732                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
10733                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
10734                has64BitLibs = (new File(rootDir, isa)).exists();
10735            } else {
10736                has64BitLibs = false;
10737            }
10738            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
10739                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
10740                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
10741                has32BitLibs = (new File(rootDir, isa)).exists();
10742            } else {
10743                has32BitLibs = false;
10744            }
10745        }
10746
10747        if (has64BitLibs && !has32BitLibs) {
10748            // The package has 64 bit libs, but not 32 bit libs. Its primary
10749            // ABI should be 64 bit. We can safely assume here that the bundled
10750            // native libraries correspond to the most preferred ABI in the list.
10751
10752            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10753            pkg.applicationInfo.secondaryCpuAbi = null;
10754        } else if (has32BitLibs && !has64BitLibs) {
10755            // The package has 32 bit libs but not 64 bit libs. Its primary
10756            // ABI should be 32 bit.
10757
10758            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10759            pkg.applicationInfo.secondaryCpuAbi = null;
10760        } else if (has32BitLibs && has64BitLibs) {
10761            // The application has both 64 and 32 bit bundled libraries. We check
10762            // here that the app declares multiArch support, and warn if it doesn't.
10763            //
10764            // We will be lenient here and record both ABIs. The primary will be the
10765            // ABI that's higher on the list, i.e, a device that's configured to prefer
10766            // 64 bit apps will see a 64 bit primary ABI,
10767
10768            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
10769                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
10770            }
10771
10772            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
10773                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10774                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10775            } else {
10776                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10777                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10778            }
10779        } else {
10780            pkg.applicationInfo.primaryCpuAbi = null;
10781            pkg.applicationInfo.secondaryCpuAbi = null;
10782        }
10783    }
10784
10785    private void killApplication(String pkgName, int appId, String reason) {
10786        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
10787    }
10788
10789    private void killApplication(String pkgName, int appId, int userId, String reason) {
10790        // Request the ActivityManager to kill the process(only for existing packages)
10791        // so that we do not end up in a confused state while the user is still using the older
10792        // version of the application while the new one gets installed.
10793        final long token = Binder.clearCallingIdentity();
10794        try {
10795            IActivityManager am = ActivityManager.getService();
10796            if (am != null) {
10797                try {
10798                    am.killApplication(pkgName, appId, userId, reason);
10799                } catch (RemoteException e) {
10800                }
10801            }
10802        } finally {
10803            Binder.restoreCallingIdentity(token);
10804        }
10805    }
10806
10807    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10808        // Remove the parent package setting
10809        PackageSetting ps = (PackageSetting) pkg.mExtras;
10810        if (ps != null) {
10811            removePackageLI(ps, chatty);
10812        }
10813        // Remove the child package setting
10814        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10815        for (int i = 0; i < childCount; i++) {
10816            PackageParser.Package childPkg = pkg.childPackages.get(i);
10817            ps = (PackageSetting) childPkg.mExtras;
10818            if (ps != null) {
10819                removePackageLI(ps, chatty);
10820            }
10821        }
10822    }
10823
10824    void removePackageLI(PackageSetting ps, boolean chatty) {
10825        if (DEBUG_INSTALL) {
10826            if (chatty)
10827                Log.d(TAG, "Removing package " + ps.name);
10828        }
10829
10830        // writer
10831        synchronized (mPackages) {
10832            mPackages.remove(ps.name);
10833            final PackageParser.Package pkg = ps.pkg;
10834            if (pkg != null) {
10835                cleanPackageDataStructuresLILPw(pkg, chatty);
10836            }
10837        }
10838    }
10839
10840    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
10841        if (DEBUG_INSTALL) {
10842            if (chatty)
10843                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
10844        }
10845
10846        // writer
10847        synchronized (mPackages) {
10848            // Remove the parent package
10849            mPackages.remove(pkg.applicationInfo.packageName);
10850            cleanPackageDataStructuresLILPw(pkg, chatty);
10851
10852            // Remove the child packages
10853            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10854            for (int i = 0; i < childCount; i++) {
10855                PackageParser.Package childPkg = pkg.childPackages.get(i);
10856                mPackages.remove(childPkg.applicationInfo.packageName);
10857                cleanPackageDataStructuresLILPw(childPkg, chatty);
10858            }
10859        }
10860    }
10861
10862    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
10863        int N = pkg.providers.size();
10864        StringBuilder r = null;
10865        int i;
10866        for (i=0; i<N; i++) {
10867            PackageParser.Provider p = pkg.providers.get(i);
10868            mProviders.removeProvider(p);
10869            if (p.info.authority == null) {
10870
10871                /* There was another ContentProvider with this authority when
10872                 * this app was installed so this authority is null,
10873                 * Ignore it as we don't have to unregister the provider.
10874                 */
10875                continue;
10876            }
10877            String names[] = p.info.authority.split(";");
10878            for (int j = 0; j < names.length; j++) {
10879                if (mProvidersByAuthority.get(names[j]) == p) {
10880                    mProvidersByAuthority.remove(names[j]);
10881                    if (DEBUG_REMOVE) {
10882                        if (chatty)
10883                            Log.d(TAG, "Unregistered content provider: " + names[j]
10884                                    + ", className = " + p.info.name + ", isSyncable = "
10885                                    + p.info.isSyncable);
10886                    }
10887                }
10888            }
10889            if (DEBUG_REMOVE && chatty) {
10890                if (r == null) {
10891                    r = new StringBuilder(256);
10892                } else {
10893                    r.append(' ');
10894                }
10895                r.append(p.info.name);
10896            }
10897        }
10898        if (r != null) {
10899            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
10900        }
10901
10902        N = pkg.services.size();
10903        r = null;
10904        for (i=0; i<N; i++) {
10905            PackageParser.Service s = pkg.services.get(i);
10906            mServices.removeService(s);
10907            if (chatty) {
10908                if (r == null) {
10909                    r = new StringBuilder(256);
10910                } else {
10911                    r.append(' ');
10912                }
10913                r.append(s.info.name);
10914            }
10915        }
10916        if (r != null) {
10917            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
10918        }
10919
10920        N = pkg.receivers.size();
10921        r = null;
10922        for (i=0; i<N; i++) {
10923            PackageParser.Activity a = pkg.receivers.get(i);
10924            mReceivers.removeActivity(a, "receiver");
10925            if (DEBUG_REMOVE && chatty) {
10926                if (r == null) {
10927                    r = new StringBuilder(256);
10928                } else {
10929                    r.append(' ');
10930                }
10931                r.append(a.info.name);
10932            }
10933        }
10934        if (r != null) {
10935            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
10936        }
10937
10938        N = pkg.activities.size();
10939        r = null;
10940        for (i=0; i<N; i++) {
10941            PackageParser.Activity a = pkg.activities.get(i);
10942            mActivities.removeActivity(a, "activity");
10943            if (DEBUG_REMOVE && chatty) {
10944                if (r == null) {
10945                    r = new StringBuilder(256);
10946                } else {
10947                    r.append(' ');
10948                }
10949                r.append(a.info.name);
10950            }
10951        }
10952        if (r != null) {
10953            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
10954        }
10955
10956        N = pkg.permissions.size();
10957        r = null;
10958        for (i=0; i<N; i++) {
10959            PackageParser.Permission p = pkg.permissions.get(i);
10960            BasePermission bp = mSettings.mPermissions.get(p.info.name);
10961            if (bp == null) {
10962                bp = mSettings.mPermissionTrees.get(p.info.name);
10963            }
10964            if (bp != null && bp.perm == p) {
10965                bp.perm = null;
10966                if (DEBUG_REMOVE && chatty) {
10967                    if (r == null) {
10968                        r = new StringBuilder(256);
10969                    } else {
10970                        r.append(' ');
10971                    }
10972                    r.append(p.info.name);
10973                }
10974            }
10975            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10976                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
10977                if (appOpPkgs != null) {
10978                    appOpPkgs.remove(pkg.packageName);
10979                }
10980            }
10981        }
10982        if (r != null) {
10983            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
10984        }
10985
10986        N = pkg.requestedPermissions.size();
10987        r = null;
10988        for (i=0; i<N; i++) {
10989            String perm = pkg.requestedPermissions.get(i);
10990            BasePermission bp = mSettings.mPermissions.get(perm);
10991            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10992                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
10993                if (appOpPkgs != null) {
10994                    appOpPkgs.remove(pkg.packageName);
10995                    if (appOpPkgs.isEmpty()) {
10996                        mAppOpPermissionPackages.remove(perm);
10997                    }
10998                }
10999            }
11000        }
11001        if (r != null) {
11002            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11003        }
11004
11005        N = pkg.instrumentation.size();
11006        r = null;
11007        for (i=0; i<N; i++) {
11008            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11009            mInstrumentation.remove(a.getComponentName());
11010            if (DEBUG_REMOVE && chatty) {
11011                if (r == null) {
11012                    r = new StringBuilder(256);
11013                } else {
11014                    r.append(' ');
11015                }
11016                r.append(a.info.name);
11017            }
11018        }
11019        if (r != null) {
11020            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11021        }
11022
11023        r = null;
11024        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11025            // Only system apps can hold shared libraries.
11026            if (pkg.libraryNames != null) {
11027                for (i = 0; i < pkg.libraryNames.size(); i++) {
11028                    String name = pkg.libraryNames.get(i);
11029                    if (removeSharedLibraryLPw(name, 0)) {
11030                        if (DEBUG_REMOVE && chatty) {
11031                            if (r == null) {
11032                                r = new StringBuilder(256);
11033                            } else {
11034                                r.append(' ');
11035                            }
11036                            r.append(name);
11037                        }
11038                    }
11039                }
11040            }
11041        }
11042
11043        r = null;
11044
11045        // Any package can hold static shared libraries.
11046        if (pkg.staticSharedLibName != null) {
11047            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11048                if (DEBUG_REMOVE && chatty) {
11049                    if (r == null) {
11050                        r = new StringBuilder(256);
11051                    } else {
11052                        r.append(' ');
11053                    }
11054                    r.append(pkg.staticSharedLibName);
11055                }
11056            }
11057        }
11058
11059        if (r != null) {
11060            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11061        }
11062    }
11063
11064    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11065        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11066            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11067                return true;
11068            }
11069        }
11070        return false;
11071    }
11072
11073    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11074    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11075    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11076
11077    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11078        // Update the parent permissions
11079        updatePermissionsLPw(pkg.packageName, pkg, flags);
11080        // Update the child permissions
11081        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11082        for (int i = 0; i < childCount; i++) {
11083            PackageParser.Package childPkg = pkg.childPackages.get(i);
11084            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11085        }
11086    }
11087
11088    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11089            int flags) {
11090        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11091        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11092    }
11093
11094    private void updatePermissionsLPw(String changingPkg,
11095            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11096        // Make sure there are no dangling permission trees.
11097        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11098        while (it.hasNext()) {
11099            final BasePermission bp = it.next();
11100            if (bp.packageSetting == null) {
11101                // We may not yet have parsed the package, so just see if
11102                // we still know about its settings.
11103                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11104            }
11105            if (bp.packageSetting == null) {
11106                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11107                        + " from package " + bp.sourcePackage);
11108                it.remove();
11109            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11110                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11111                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11112                            + " from package " + bp.sourcePackage);
11113                    flags |= UPDATE_PERMISSIONS_ALL;
11114                    it.remove();
11115                }
11116            }
11117        }
11118
11119        // Make sure all dynamic permissions have been assigned to a package,
11120        // and make sure there are no dangling permissions.
11121        it = mSettings.mPermissions.values().iterator();
11122        while (it.hasNext()) {
11123            final BasePermission bp = it.next();
11124            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11125                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11126                        + bp.name + " pkg=" + bp.sourcePackage
11127                        + " info=" + bp.pendingInfo);
11128                if (bp.packageSetting == null && bp.pendingInfo != null) {
11129                    final BasePermission tree = findPermissionTreeLP(bp.name);
11130                    if (tree != null && tree.perm != null) {
11131                        bp.packageSetting = tree.packageSetting;
11132                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11133                                new PermissionInfo(bp.pendingInfo));
11134                        bp.perm.info.packageName = tree.perm.info.packageName;
11135                        bp.perm.info.name = bp.name;
11136                        bp.uid = tree.uid;
11137                    }
11138                }
11139            }
11140            if (bp.packageSetting == null) {
11141                // We may not yet have parsed the package, so just see if
11142                // we still know about its settings.
11143                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11144            }
11145            if (bp.packageSetting == null) {
11146                Slog.w(TAG, "Removing dangling permission: " + bp.name
11147                        + " from package " + bp.sourcePackage);
11148                it.remove();
11149            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11150                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11151                    Slog.i(TAG, "Removing old permission: " + bp.name
11152                            + " from package " + bp.sourcePackage);
11153                    flags |= UPDATE_PERMISSIONS_ALL;
11154                    it.remove();
11155                }
11156            }
11157        }
11158
11159        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11160        // Now update the permissions for all packages, in particular
11161        // replace the granted permissions of the system packages.
11162        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11163            for (PackageParser.Package pkg : mPackages.values()) {
11164                if (pkg != pkgInfo) {
11165                    // Only replace for packages on requested volume
11166                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11167                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11168                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11169                    grantPermissionsLPw(pkg, replace, changingPkg);
11170                }
11171            }
11172        }
11173
11174        if (pkgInfo != null) {
11175            // Only replace for packages on requested volume
11176            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11177            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11178                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11179            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11180        }
11181        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11182    }
11183
11184    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11185            String packageOfInterest) {
11186        // IMPORTANT: There are two types of permissions: install and runtime.
11187        // Install time permissions are granted when the app is installed to
11188        // all device users and users added in the future. Runtime permissions
11189        // are granted at runtime explicitly to specific users. Normal and signature
11190        // protected permissions are install time permissions. Dangerous permissions
11191        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11192        // otherwise they are runtime permissions. This function does not manage
11193        // runtime permissions except for the case an app targeting Lollipop MR1
11194        // being upgraded to target a newer SDK, in which case dangerous permissions
11195        // are transformed from install time to runtime ones.
11196
11197        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11198        if (ps == null) {
11199            return;
11200        }
11201
11202        PermissionsState permissionsState = ps.getPermissionsState();
11203        PermissionsState origPermissions = permissionsState;
11204
11205        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11206
11207        boolean runtimePermissionsRevoked = false;
11208        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11209
11210        boolean changedInstallPermission = false;
11211
11212        if (replace) {
11213            ps.installPermissionsFixed = false;
11214            if (!ps.isSharedUser()) {
11215                origPermissions = new PermissionsState(permissionsState);
11216                permissionsState.reset();
11217            } else {
11218                // We need to know only about runtime permission changes since the
11219                // calling code always writes the install permissions state but
11220                // the runtime ones are written only if changed. The only cases of
11221                // changed runtime permissions here are promotion of an install to
11222                // runtime and revocation of a runtime from a shared user.
11223                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11224                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11225                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11226                    runtimePermissionsRevoked = true;
11227                }
11228            }
11229        }
11230
11231        permissionsState.setGlobalGids(mGlobalGids);
11232
11233        final int N = pkg.requestedPermissions.size();
11234        for (int i=0; i<N; i++) {
11235            final String name = pkg.requestedPermissions.get(i);
11236            final BasePermission bp = mSettings.mPermissions.get(name);
11237
11238            if (DEBUG_INSTALL) {
11239                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11240            }
11241
11242            if (bp == null || bp.packageSetting == null) {
11243                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11244                    Slog.w(TAG, "Unknown permission " + name
11245                            + " in package " + pkg.packageName);
11246                }
11247                continue;
11248            }
11249
11250
11251            // Limit ephemeral apps to ephemeral allowed permissions.
11252            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11253                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11254                        + pkg.packageName);
11255                continue;
11256            }
11257
11258            final String perm = bp.name;
11259            boolean allowedSig = false;
11260            int grant = GRANT_DENIED;
11261
11262            // Keep track of app op permissions.
11263            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11264                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11265                if (pkgs == null) {
11266                    pkgs = new ArraySet<>();
11267                    mAppOpPermissionPackages.put(bp.name, pkgs);
11268                }
11269                pkgs.add(pkg.packageName);
11270            }
11271
11272            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11273            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11274                    >= Build.VERSION_CODES.M;
11275            switch (level) {
11276                case PermissionInfo.PROTECTION_NORMAL: {
11277                    // For all apps normal permissions are install time ones.
11278                    grant = GRANT_INSTALL;
11279                } break;
11280
11281                case PermissionInfo.PROTECTION_DANGEROUS: {
11282                    // If a permission review is required for legacy apps we represent
11283                    // their permissions as always granted runtime ones since we need
11284                    // to keep the review required permission flag per user while an
11285                    // install permission's state is shared across all users.
11286                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11287                        // For legacy apps dangerous permissions are install time ones.
11288                        grant = GRANT_INSTALL;
11289                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11290                        // For legacy apps that became modern, install becomes runtime.
11291                        grant = GRANT_UPGRADE;
11292                    } else if (mPromoteSystemApps
11293                            && isSystemApp(ps)
11294                            && mExistingSystemPackages.contains(ps.name)) {
11295                        // For legacy system apps, install becomes runtime.
11296                        // We cannot check hasInstallPermission() for system apps since those
11297                        // permissions were granted implicitly and not persisted pre-M.
11298                        grant = GRANT_UPGRADE;
11299                    } else {
11300                        // For modern apps keep runtime permissions unchanged.
11301                        grant = GRANT_RUNTIME;
11302                    }
11303                } break;
11304
11305                case PermissionInfo.PROTECTION_SIGNATURE: {
11306                    // For all apps signature permissions are install time ones.
11307                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11308                    if (allowedSig) {
11309                        grant = GRANT_INSTALL;
11310                    }
11311                } break;
11312            }
11313
11314            if (DEBUG_INSTALL) {
11315                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11316            }
11317
11318            if (grant != GRANT_DENIED) {
11319                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11320                    // If this is an existing, non-system package, then
11321                    // we can't add any new permissions to it.
11322                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11323                        // Except...  if this is a permission that was added
11324                        // to the platform (note: need to only do this when
11325                        // updating the platform).
11326                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11327                            grant = GRANT_DENIED;
11328                        }
11329                    }
11330                }
11331
11332                switch (grant) {
11333                    case GRANT_INSTALL: {
11334                        // Revoke this as runtime permission to handle the case of
11335                        // a runtime permission being downgraded to an install one.
11336                        // Also in permission review mode we keep dangerous permissions
11337                        // for legacy apps
11338                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11339                            if (origPermissions.getRuntimePermissionState(
11340                                    bp.name, userId) != null) {
11341                                // Revoke the runtime permission and clear the flags.
11342                                origPermissions.revokeRuntimePermission(bp, userId);
11343                                origPermissions.updatePermissionFlags(bp, userId,
11344                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11345                                // If we revoked a permission permission, we have to write.
11346                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11347                                        changedRuntimePermissionUserIds, userId);
11348                            }
11349                        }
11350                        // Grant an install permission.
11351                        if (permissionsState.grantInstallPermission(bp) !=
11352                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11353                            changedInstallPermission = true;
11354                        }
11355                    } break;
11356
11357                    case GRANT_RUNTIME: {
11358                        // Grant previously granted runtime permissions.
11359                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11360                            PermissionState permissionState = origPermissions
11361                                    .getRuntimePermissionState(bp.name, userId);
11362                            int flags = permissionState != null
11363                                    ? permissionState.getFlags() : 0;
11364                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11365                                // Don't propagate the permission in a permission review mode if
11366                                // the former was revoked, i.e. marked to not propagate on upgrade.
11367                                // Note that in a permission review mode install permissions are
11368                                // represented as constantly granted runtime ones since we need to
11369                                // keep a per user state associated with the permission. Also the
11370                                // revoke on upgrade flag is no longer applicable and is reset.
11371                                final boolean revokeOnUpgrade = (flags & PackageManager
11372                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11373                                if (revokeOnUpgrade) {
11374                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11375                                    // Since we changed the flags, we have to write.
11376                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11377                                            changedRuntimePermissionUserIds, userId);
11378                                }
11379                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11380                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11381                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11382                                        // If we cannot put the permission as it was,
11383                                        // we have to write.
11384                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11385                                                changedRuntimePermissionUserIds, userId);
11386                                    }
11387                                }
11388
11389                                // If the app supports runtime permissions no need for a review.
11390                                if (mPermissionReviewRequired
11391                                        && appSupportsRuntimePermissions
11392                                        && (flags & PackageManager
11393                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11394                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11395                                    // Since we changed the flags, we have to write.
11396                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11397                                            changedRuntimePermissionUserIds, userId);
11398                                }
11399                            } else if (mPermissionReviewRequired
11400                                    && !appSupportsRuntimePermissions) {
11401                                // For legacy apps that need a permission review, every new
11402                                // runtime permission is granted but it is pending a review.
11403                                // We also need to review only platform defined runtime
11404                                // permissions as these are the only ones the platform knows
11405                                // how to disable the API to simulate revocation as legacy
11406                                // apps don't expect to run with revoked permissions.
11407                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11408                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11409                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11410                                        // We changed the flags, hence have to write.
11411                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11412                                                changedRuntimePermissionUserIds, userId);
11413                                    }
11414                                }
11415                                if (permissionsState.grantRuntimePermission(bp, userId)
11416                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11417                                    // We changed the permission, hence have to write.
11418                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11419                                            changedRuntimePermissionUserIds, userId);
11420                                }
11421                            }
11422                            // Propagate the permission flags.
11423                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11424                        }
11425                    } break;
11426
11427                    case GRANT_UPGRADE: {
11428                        // Grant runtime permissions for a previously held install permission.
11429                        PermissionState permissionState = origPermissions
11430                                .getInstallPermissionState(bp.name);
11431                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11432
11433                        if (origPermissions.revokeInstallPermission(bp)
11434                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11435                            // We will be transferring the permission flags, so clear them.
11436                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11437                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11438                            changedInstallPermission = true;
11439                        }
11440
11441                        // If the permission is not to be promoted to runtime we ignore it and
11442                        // also its other flags as they are not applicable to install permissions.
11443                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11444                            for (int userId : currentUserIds) {
11445                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11446                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11447                                    // Transfer the permission flags.
11448                                    permissionsState.updatePermissionFlags(bp, userId,
11449                                            flags, flags);
11450                                    // If we granted the permission, we have to write.
11451                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11452                                            changedRuntimePermissionUserIds, userId);
11453                                }
11454                            }
11455                        }
11456                    } break;
11457
11458                    default: {
11459                        if (packageOfInterest == null
11460                                || packageOfInterest.equals(pkg.packageName)) {
11461                            Slog.w(TAG, "Not granting permission " + perm
11462                                    + " to package " + pkg.packageName
11463                                    + " because it was previously installed without");
11464                        }
11465                    } break;
11466                }
11467            } else {
11468                if (permissionsState.revokeInstallPermission(bp) !=
11469                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11470                    // Also drop the permission flags.
11471                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11472                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11473                    changedInstallPermission = true;
11474                    Slog.i(TAG, "Un-granting permission " + perm
11475                            + " from package " + pkg.packageName
11476                            + " (protectionLevel=" + bp.protectionLevel
11477                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11478                            + ")");
11479                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11480                    // Don't print warning for app op permissions, since it is fine for them
11481                    // not to be granted, there is a UI for the user to decide.
11482                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11483                        Slog.w(TAG, "Not granting permission " + perm
11484                                + " to package " + pkg.packageName
11485                                + " (protectionLevel=" + bp.protectionLevel
11486                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11487                                + ")");
11488                    }
11489                }
11490            }
11491        }
11492
11493        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11494                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11495            // This is the first that we have heard about this package, so the
11496            // permissions we have now selected are fixed until explicitly
11497            // changed.
11498            ps.installPermissionsFixed = true;
11499        }
11500
11501        // Persist the runtime permissions state for users with changes. If permissions
11502        // were revoked because no app in the shared user declares them we have to
11503        // write synchronously to avoid losing runtime permissions state.
11504        for (int userId : changedRuntimePermissionUserIds) {
11505            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11506        }
11507    }
11508
11509    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
11510        boolean allowed = false;
11511        final int NP = PackageParser.NEW_PERMISSIONS.length;
11512        for (int ip=0; ip<NP; ip++) {
11513            final PackageParser.NewPermissionInfo npi
11514                    = PackageParser.NEW_PERMISSIONS[ip];
11515            if (npi.name.equals(perm)
11516                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
11517                allowed = true;
11518                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
11519                        + pkg.packageName);
11520                break;
11521            }
11522        }
11523        return allowed;
11524    }
11525
11526    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
11527            BasePermission bp, PermissionsState origPermissions) {
11528        boolean privilegedPermission = (bp.protectionLevel
11529                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
11530        boolean privappPermissionsDisable =
11531                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
11532        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
11533        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
11534        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
11535                && !platformPackage && platformPermission) {
11536            ArraySet<String> wlPermissions = SystemConfig.getInstance()
11537                    .getPrivAppPermissions(pkg.packageName);
11538            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
11539            if (!whitelisted) {
11540                Slog.w(TAG, "Privileged permission " + perm + " for package "
11541                        + pkg.packageName + " - not in privapp-permissions whitelist");
11542                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
11543                    return false;
11544                }
11545            }
11546        }
11547        boolean allowed = (compareSignatures(
11548                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
11549                        == PackageManager.SIGNATURE_MATCH)
11550                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
11551                        == PackageManager.SIGNATURE_MATCH);
11552        if (!allowed && privilegedPermission) {
11553            if (isSystemApp(pkg)) {
11554                // For updated system applications, a system permission
11555                // is granted only if it had been defined by the original application.
11556                if (pkg.isUpdatedSystemApp()) {
11557                    final PackageSetting sysPs = mSettings
11558                            .getDisabledSystemPkgLPr(pkg.packageName);
11559                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
11560                        // If the original was granted this permission, we take
11561                        // that grant decision as read and propagate it to the
11562                        // update.
11563                        if (sysPs.isPrivileged()) {
11564                            allowed = true;
11565                        }
11566                    } else {
11567                        // The system apk may have been updated with an older
11568                        // version of the one on the data partition, but which
11569                        // granted a new system permission that it didn't have
11570                        // before.  In this case we do want to allow the app to
11571                        // now get the new permission if the ancestral apk is
11572                        // privileged to get it.
11573                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
11574                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
11575                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
11576                                    allowed = true;
11577                                    break;
11578                                }
11579                            }
11580                        }
11581                        // Also if a privileged parent package on the system image or any of
11582                        // its children requested a privileged permission, the updated child
11583                        // packages can also get the permission.
11584                        if (pkg.parentPackage != null) {
11585                            final PackageSetting disabledSysParentPs = mSettings
11586                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
11587                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
11588                                    && disabledSysParentPs.isPrivileged()) {
11589                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
11590                                    allowed = true;
11591                                } else if (disabledSysParentPs.pkg.childPackages != null) {
11592                                    final int count = disabledSysParentPs.pkg.childPackages.size();
11593                                    for (int i = 0; i < count; i++) {
11594                                        PackageParser.Package disabledSysChildPkg =
11595                                                disabledSysParentPs.pkg.childPackages.get(i);
11596                                        if (isPackageRequestingPermission(disabledSysChildPkg,
11597                                                perm)) {
11598                                            allowed = true;
11599                                            break;
11600                                        }
11601                                    }
11602                                }
11603                            }
11604                        }
11605                    }
11606                } else {
11607                    allowed = isPrivilegedApp(pkg);
11608                }
11609            }
11610        }
11611        if (!allowed) {
11612            if (!allowed && (bp.protectionLevel
11613                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
11614                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
11615                // If this was a previously normal/dangerous permission that got moved
11616                // to a system permission as part of the runtime permission redesign, then
11617                // we still want to blindly grant it to old apps.
11618                allowed = true;
11619            }
11620            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
11621                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
11622                // If this permission is to be granted to the system installer and
11623                // this app is an installer, then it gets the permission.
11624                allowed = true;
11625            }
11626            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
11627                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
11628                // If this permission is to be granted to the system verifier and
11629                // this app is a verifier, then it gets the permission.
11630                allowed = true;
11631            }
11632            if (!allowed && (bp.protectionLevel
11633                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
11634                    && isSystemApp(pkg)) {
11635                // Any pre-installed system app is allowed to get this permission.
11636                allowed = true;
11637            }
11638            if (!allowed && (bp.protectionLevel
11639                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
11640                // For development permissions, a development permission
11641                // is granted only if it was already granted.
11642                allowed = origPermissions.hasInstallPermission(perm);
11643            }
11644            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
11645                    && pkg.packageName.equals(mSetupWizardPackage)) {
11646                // If this permission is to be granted to the system setup wizard and
11647                // this app is a setup wizard, then it gets the permission.
11648                allowed = true;
11649            }
11650        }
11651        return allowed;
11652    }
11653
11654    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
11655        final int permCount = pkg.requestedPermissions.size();
11656        for (int j = 0; j < permCount; j++) {
11657            String requestedPermission = pkg.requestedPermissions.get(j);
11658            if (permission.equals(requestedPermission)) {
11659                return true;
11660            }
11661        }
11662        return false;
11663    }
11664
11665    final class ActivityIntentResolver
11666            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11667        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11668                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
11669            if (!sUserManager.exists(userId)) return null;
11670            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0)
11671                    | (visibleToEphemeral ? PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY : 0)
11672                    | (isEphemeral ? PackageManager.MATCH_EPHEMERAL : 0);
11673            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
11674                    isEphemeral, userId);
11675        }
11676
11677        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11678                int userId) {
11679            if (!sUserManager.exists(userId)) return null;
11680            mFlags = flags;
11681            return super.queryIntent(intent, resolvedType,
11682                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11683                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
11684                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
11685        }
11686
11687        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11688                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11689            if (!sUserManager.exists(userId)) return null;
11690            if (packageActivities == null) {
11691                return null;
11692            }
11693            mFlags = flags;
11694            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11695            final boolean vislbleToEphemeral =
11696                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
11697            final boolean isEphemeral = (flags & PackageManager.MATCH_EPHEMERAL) != 0;
11698            final int N = packageActivities.size();
11699            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11700                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11701
11702            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11703            for (int i = 0; i < N; ++i) {
11704                intentFilters = packageActivities.get(i).intents;
11705                if (intentFilters != null && intentFilters.size() > 0) {
11706                    PackageParser.ActivityIntentInfo[] array =
11707                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11708                    intentFilters.toArray(array);
11709                    listCut.add(array);
11710                }
11711            }
11712            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
11713                    vislbleToEphemeral, isEphemeral, listCut, userId);
11714        }
11715
11716        /**
11717         * Finds a privileged activity that matches the specified activity names.
11718         */
11719        private PackageParser.Activity findMatchingActivity(
11720                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11721            for (PackageParser.Activity sysActivity : activityList) {
11722                if (sysActivity.info.name.equals(activityInfo.name)) {
11723                    return sysActivity;
11724                }
11725                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11726                    return sysActivity;
11727                }
11728                if (sysActivity.info.targetActivity != null) {
11729                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11730                        return sysActivity;
11731                    }
11732                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11733                        return sysActivity;
11734                    }
11735                }
11736            }
11737            return null;
11738        }
11739
11740        public class IterGenerator<E> {
11741            public Iterator<E> generate(ActivityIntentInfo info) {
11742                return null;
11743            }
11744        }
11745
11746        public class ActionIterGenerator extends IterGenerator<String> {
11747            @Override
11748            public Iterator<String> generate(ActivityIntentInfo info) {
11749                return info.actionsIterator();
11750            }
11751        }
11752
11753        public class CategoriesIterGenerator extends IterGenerator<String> {
11754            @Override
11755            public Iterator<String> generate(ActivityIntentInfo info) {
11756                return info.categoriesIterator();
11757            }
11758        }
11759
11760        public class SchemesIterGenerator extends IterGenerator<String> {
11761            @Override
11762            public Iterator<String> generate(ActivityIntentInfo info) {
11763                return info.schemesIterator();
11764            }
11765        }
11766
11767        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11768            @Override
11769            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11770                return info.authoritiesIterator();
11771            }
11772        }
11773
11774        /**
11775         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11776         * MODIFIED. Do not pass in a list that should not be changed.
11777         */
11778        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11779                IterGenerator<T> generator, Iterator<T> searchIterator) {
11780            // loop through the set of actions; every one must be found in the intent filter
11781            while (searchIterator.hasNext()) {
11782                // we must have at least one filter in the list to consider a match
11783                if (intentList.size() == 0) {
11784                    break;
11785                }
11786
11787                final T searchAction = searchIterator.next();
11788
11789                // loop through the set of intent filters
11790                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11791                while (intentIter.hasNext()) {
11792                    final ActivityIntentInfo intentInfo = intentIter.next();
11793                    boolean selectionFound = false;
11794
11795                    // loop through the intent filter's selection criteria; at least one
11796                    // of them must match the searched criteria
11797                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11798                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11799                        final T intentSelection = intentSelectionIter.next();
11800                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11801                            selectionFound = true;
11802                            break;
11803                        }
11804                    }
11805
11806                    // the selection criteria wasn't found in this filter's set; this filter
11807                    // is not a potential match
11808                    if (!selectionFound) {
11809                        intentIter.remove();
11810                    }
11811                }
11812            }
11813        }
11814
11815        private boolean isProtectedAction(ActivityIntentInfo filter) {
11816            final Iterator<String> actionsIter = filter.actionsIterator();
11817            while (actionsIter != null && actionsIter.hasNext()) {
11818                final String filterAction = actionsIter.next();
11819                if (PROTECTED_ACTIONS.contains(filterAction)) {
11820                    return true;
11821                }
11822            }
11823            return false;
11824        }
11825
11826        /**
11827         * Adjusts the priority of the given intent filter according to policy.
11828         * <p>
11829         * <ul>
11830         * <li>The priority for non privileged applications is capped to '0'</li>
11831         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11832         * <li>The priority for unbundled updates to privileged applications is capped to the
11833         *      priority defined on the system partition</li>
11834         * </ul>
11835         * <p>
11836         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11837         * allowed to obtain any priority on any action.
11838         */
11839        private void adjustPriority(
11840                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11841            // nothing to do; priority is fine as-is
11842            if (intent.getPriority() <= 0) {
11843                return;
11844            }
11845
11846            final ActivityInfo activityInfo = intent.activity.info;
11847            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11848
11849            final boolean privilegedApp =
11850                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11851            if (!privilegedApp) {
11852                // non-privileged applications can never define a priority >0
11853                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
11854                        + " package: " + applicationInfo.packageName
11855                        + " activity: " + intent.activity.className
11856                        + " origPrio: " + intent.getPriority());
11857                intent.setPriority(0);
11858                return;
11859            }
11860
11861            if (systemActivities == null) {
11862                // the system package is not disabled; we're parsing the system partition
11863                if (isProtectedAction(intent)) {
11864                    if (mDeferProtectedFilters) {
11865                        // We can't deal with these just yet. No component should ever obtain a
11866                        // >0 priority for a protected actions, with ONE exception -- the setup
11867                        // wizard. The setup wizard, however, cannot be known until we're able to
11868                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
11869                        // until all intent filters have been processed. Chicken, meet egg.
11870                        // Let the filter temporarily have a high priority and rectify the
11871                        // priorities after all system packages have been scanned.
11872                        mProtectedFilters.add(intent);
11873                        if (DEBUG_FILTERS) {
11874                            Slog.i(TAG, "Protected action; save for later;"
11875                                    + " package: " + applicationInfo.packageName
11876                                    + " activity: " + intent.activity.className
11877                                    + " origPrio: " + intent.getPriority());
11878                        }
11879                        return;
11880                    } else {
11881                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
11882                            Slog.i(TAG, "No setup wizard;"
11883                                + " All protected intents capped to priority 0");
11884                        }
11885                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
11886                            if (DEBUG_FILTERS) {
11887                                Slog.i(TAG, "Found setup wizard;"
11888                                    + " allow priority " + intent.getPriority() + ";"
11889                                    + " package: " + intent.activity.info.packageName
11890                                    + " activity: " + intent.activity.className
11891                                    + " priority: " + intent.getPriority());
11892                            }
11893                            // setup wizard gets whatever it wants
11894                            return;
11895                        }
11896                        Slog.w(TAG, "Protected action; cap priority to 0;"
11897                                + " package: " + intent.activity.info.packageName
11898                                + " activity: " + intent.activity.className
11899                                + " origPrio: " + intent.getPriority());
11900                        intent.setPriority(0);
11901                        return;
11902                    }
11903                }
11904                // privileged apps on the system image get whatever priority they request
11905                return;
11906            }
11907
11908            // privileged app unbundled update ... try to find the same activity
11909            final PackageParser.Activity foundActivity =
11910                    findMatchingActivity(systemActivities, activityInfo);
11911            if (foundActivity == null) {
11912                // this is a new activity; it cannot obtain >0 priority
11913                if (DEBUG_FILTERS) {
11914                    Slog.i(TAG, "New activity; cap priority to 0;"
11915                            + " package: " + applicationInfo.packageName
11916                            + " activity: " + intent.activity.className
11917                            + " origPrio: " + intent.getPriority());
11918                }
11919                intent.setPriority(0);
11920                return;
11921            }
11922
11923            // found activity, now check for filter equivalence
11924
11925            // a shallow copy is enough; we modify the list, not its contents
11926            final List<ActivityIntentInfo> intentListCopy =
11927                    new ArrayList<>(foundActivity.intents);
11928            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
11929
11930            // find matching action subsets
11931            final Iterator<String> actionsIterator = intent.actionsIterator();
11932            if (actionsIterator != null) {
11933                getIntentListSubset(
11934                        intentListCopy, new ActionIterGenerator(), actionsIterator);
11935                if (intentListCopy.size() == 0) {
11936                    // no more intents to match; we're not equivalent
11937                    if (DEBUG_FILTERS) {
11938                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
11939                                + " package: " + applicationInfo.packageName
11940                                + " activity: " + intent.activity.className
11941                                + " origPrio: " + intent.getPriority());
11942                    }
11943                    intent.setPriority(0);
11944                    return;
11945                }
11946            }
11947
11948            // find matching category subsets
11949            final Iterator<String> categoriesIterator = intent.categoriesIterator();
11950            if (categoriesIterator != null) {
11951                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
11952                        categoriesIterator);
11953                if (intentListCopy.size() == 0) {
11954                    // no more intents to match; we're not equivalent
11955                    if (DEBUG_FILTERS) {
11956                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
11957                                + " package: " + applicationInfo.packageName
11958                                + " activity: " + intent.activity.className
11959                                + " origPrio: " + intent.getPriority());
11960                    }
11961                    intent.setPriority(0);
11962                    return;
11963                }
11964            }
11965
11966            // find matching schemes subsets
11967            final Iterator<String> schemesIterator = intent.schemesIterator();
11968            if (schemesIterator != null) {
11969                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
11970                        schemesIterator);
11971                if (intentListCopy.size() == 0) {
11972                    // no more intents to match; we're not equivalent
11973                    if (DEBUG_FILTERS) {
11974                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
11975                                + " package: " + applicationInfo.packageName
11976                                + " activity: " + intent.activity.className
11977                                + " origPrio: " + intent.getPriority());
11978                    }
11979                    intent.setPriority(0);
11980                    return;
11981                }
11982            }
11983
11984            // find matching authorities subsets
11985            final Iterator<IntentFilter.AuthorityEntry>
11986                    authoritiesIterator = intent.authoritiesIterator();
11987            if (authoritiesIterator != null) {
11988                getIntentListSubset(intentListCopy,
11989                        new AuthoritiesIterGenerator(),
11990                        authoritiesIterator);
11991                if (intentListCopy.size() == 0) {
11992                    // no more intents to match; we're not equivalent
11993                    if (DEBUG_FILTERS) {
11994                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
11995                                + " package: " + applicationInfo.packageName
11996                                + " activity: " + intent.activity.className
11997                                + " origPrio: " + intent.getPriority());
11998                    }
11999                    intent.setPriority(0);
12000                    return;
12001                }
12002            }
12003
12004            // we found matching filter(s); app gets the max priority of all intents
12005            int cappedPriority = 0;
12006            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12007                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12008            }
12009            if (intent.getPriority() > cappedPriority) {
12010                if (DEBUG_FILTERS) {
12011                    Slog.i(TAG, "Found matching filter(s);"
12012                            + " cap priority to " + cappedPriority + ";"
12013                            + " package: " + applicationInfo.packageName
12014                            + " activity: " + intent.activity.className
12015                            + " origPrio: " + intent.getPriority());
12016                }
12017                intent.setPriority(cappedPriority);
12018                return;
12019            }
12020            // all this for nothing; the requested priority was <= what was on the system
12021        }
12022
12023        public final void addActivity(PackageParser.Activity a, String type) {
12024            mActivities.put(a.getComponentName(), a);
12025            if (DEBUG_SHOW_INFO)
12026                Log.v(
12027                TAG, "  " + type + " " +
12028                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12029            if (DEBUG_SHOW_INFO)
12030                Log.v(TAG, "    Class=" + a.info.name);
12031            final int NI = a.intents.size();
12032            for (int j=0; j<NI; j++) {
12033                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12034                if ("activity".equals(type)) {
12035                    final PackageSetting ps =
12036                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12037                    final List<PackageParser.Activity> systemActivities =
12038                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12039                    adjustPriority(systemActivities, intent);
12040                }
12041                if (DEBUG_SHOW_INFO) {
12042                    Log.v(TAG, "    IntentFilter:");
12043                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12044                }
12045                if (!intent.debugCheck()) {
12046                    Log.w(TAG, "==> For Activity " + a.info.name);
12047                }
12048                addFilter(intent);
12049            }
12050        }
12051
12052        public final void removeActivity(PackageParser.Activity a, String type) {
12053            mActivities.remove(a.getComponentName());
12054            if (DEBUG_SHOW_INFO) {
12055                Log.v(TAG, "  " + type + " "
12056                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12057                                : a.info.name) + ":");
12058                Log.v(TAG, "    Class=" + a.info.name);
12059            }
12060            final int NI = a.intents.size();
12061            for (int j=0; j<NI; j++) {
12062                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12063                if (DEBUG_SHOW_INFO) {
12064                    Log.v(TAG, "    IntentFilter:");
12065                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12066                }
12067                removeFilter(intent);
12068            }
12069        }
12070
12071        @Override
12072        protected boolean allowFilterResult(
12073                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12074            ActivityInfo filterAi = filter.activity.info;
12075            for (int i=dest.size()-1; i>=0; i--) {
12076                ActivityInfo destAi = dest.get(i).activityInfo;
12077                if (destAi.name == filterAi.name
12078                        && destAi.packageName == filterAi.packageName) {
12079                    return false;
12080                }
12081            }
12082            return true;
12083        }
12084
12085        @Override
12086        protected ActivityIntentInfo[] newArray(int size) {
12087            return new ActivityIntentInfo[size];
12088        }
12089
12090        @Override
12091        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12092            if (!sUserManager.exists(userId)) return true;
12093            PackageParser.Package p = filter.activity.owner;
12094            if (p != null) {
12095                PackageSetting ps = (PackageSetting)p.mExtras;
12096                if (ps != null) {
12097                    // System apps are never considered stopped for purposes of
12098                    // filtering, because there may be no way for the user to
12099                    // actually re-launch them.
12100                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12101                            && ps.getStopped(userId);
12102                }
12103            }
12104            return false;
12105        }
12106
12107        @Override
12108        protected boolean isPackageForFilter(String packageName,
12109                PackageParser.ActivityIntentInfo info) {
12110            return packageName.equals(info.activity.owner.packageName);
12111        }
12112
12113        @Override
12114        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12115                int match, int userId) {
12116            if (!sUserManager.exists(userId)) return null;
12117            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12118                return null;
12119            }
12120            final PackageParser.Activity activity = info.activity;
12121            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12122            if (ps == null) {
12123                return null;
12124            }
12125            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
12126                    ps.readUserState(userId), userId);
12127            if (ai == null) {
12128                return null;
12129            }
12130            final ResolveInfo res = new ResolveInfo();
12131            res.activityInfo = ai;
12132            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12133                res.filter = info;
12134            }
12135            if (info != null) {
12136                res.handleAllWebDataURI = info.handleAllWebDataURI();
12137            }
12138            res.priority = info.getPriority();
12139            res.preferredOrder = activity.owner.mPreferredOrder;
12140            //System.out.println("Result: " + res.activityInfo.className +
12141            //                   " = " + res.priority);
12142            res.match = match;
12143            res.isDefault = info.hasDefault;
12144            res.labelRes = info.labelRes;
12145            res.nonLocalizedLabel = info.nonLocalizedLabel;
12146            if (userNeedsBadging(userId)) {
12147                res.noResourceId = true;
12148            } else {
12149                res.icon = info.icon;
12150            }
12151            res.iconResourceId = info.icon;
12152            res.system = res.activityInfo.applicationInfo.isSystemApp();
12153            return res;
12154        }
12155
12156        @Override
12157        protected void sortResults(List<ResolveInfo> results) {
12158            Collections.sort(results, mResolvePrioritySorter);
12159        }
12160
12161        @Override
12162        protected void dumpFilter(PrintWriter out, String prefix,
12163                PackageParser.ActivityIntentInfo filter) {
12164            out.print(prefix); out.print(
12165                    Integer.toHexString(System.identityHashCode(filter.activity)));
12166                    out.print(' ');
12167                    filter.activity.printComponentShortName(out);
12168                    out.print(" filter ");
12169                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12170        }
12171
12172        @Override
12173        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12174            return filter.activity;
12175        }
12176
12177        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12178            PackageParser.Activity activity = (PackageParser.Activity)label;
12179            out.print(prefix); out.print(
12180                    Integer.toHexString(System.identityHashCode(activity)));
12181                    out.print(' ');
12182                    activity.printComponentShortName(out);
12183            if (count > 1) {
12184                out.print(" ("); out.print(count); out.print(" filters)");
12185            }
12186            out.println();
12187        }
12188
12189        // Keys are String (activity class name), values are Activity.
12190        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12191                = new ArrayMap<ComponentName, PackageParser.Activity>();
12192        private int mFlags;
12193    }
12194
12195    private final class ServiceIntentResolver
12196            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12197        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12198                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
12199            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12200            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
12201                    isEphemeral, userId);
12202        }
12203
12204        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12205                int userId) {
12206            if (!sUserManager.exists(userId)) return null;
12207            mFlags = flags;
12208            return super.queryIntent(intent, resolvedType,
12209                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12210                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
12211                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
12212        }
12213
12214        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12215                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12216            if (!sUserManager.exists(userId)) return null;
12217            if (packageServices == null) {
12218                return null;
12219            }
12220            mFlags = flags;
12221            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12222            final boolean vislbleToEphemeral =
12223                    (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
12224            final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0;
12225            final int N = packageServices.size();
12226            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12227                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12228
12229            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12230            for (int i = 0; i < N; ++i) {
12231                intentFilters = packageServices.get(i).intents;
12232                if (intentFilters != null && intentFilters.size() > 0) {
12233                    PackageParser.ServiceIntentInfo[] array =
12234                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12235                    intentFilters.toArray(array);
12236                    listCut.add(array);
12237                }
12238            }
12239            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
12240                    vislbleToEphemeral, isEphemeral, listCut, userId);
12241        }
12242
12243        public final void addService(PackageParser.Service s) {
12244            mServices.put(s.getComponentName(), s);
12245            if (DEBUG_SHOW_INFO) {
12246                Log.v(TAG, "  "
12247                        + (s.info.nonLocalizedLabel != null
12248                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12249                Log.v(TAG, "    Class=" + s.info.name);
12250            }
12251            final int NI = s.intents.size();
12252            int j;
12253            for (j=0; j<NI; j++) {
12254                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12255                if (DEBUG_SHOW_INFO) {
12256                    Log.v(TAG, "    IntentFilter:");
12257                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12258                }
12259                if (!intent.debugCheck()) {
12260                    Log.w(TAG, "==> For Service " + s.info.name);
12261                }
12262                addFilter(intent);
12263            }
12264        }
12265
12266        public final void removeService(PackageParser.Service s) {
12267            mServices.remove(s.getComponentName());
12268            if (DEBUG_SHOW_INFO) {
12269                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12270                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12271                Log.v(TAG, "    Class=" + s.info.name);
12272            }
12273            final int NI = s.intents.size();
12274            int j;
12275            for (j=0; j<NI; j++) {
12276                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12277                if (DEBUG_SHOW_INFO) {
12278                    Log.v(TAG, "    IntentFilter:");
12279                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12280                }
12281                removeFilter(intent);
12282            }
12283        }
12284
12285        @Override
12286        protected boolean allowFilterResult(
12287                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12288            ServiceInfo filterSi = filter.service.info;
12289            for (int i=dest.size()-1; i>=0; i--) {
12290                ServiceInfo destAi = dest.get(i).serviceInfo;
12291                if (destAi.name == filterSi.name
12292                        && destAi.packageName == filterSi.packageName) {
12293                    return false;
12294                }
12295            }
12296            return true;
12297        }
12298
12299        @Override
12300        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12301            return new PackageParser.ServiceIntentInfo[size];
12302        }
12303
12304        @Override
12305        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12306            if (!sUserManager.exists(userId)) return true;
12307            PackageParser.Package p = filter.service.owner;
12308            if (p != null) {
12309                PackageSetting ps = (PackageSetting)p.mExtras;
12310                if (ps != null) {
12311                    // System apps are never considered stopped for purposes of
12312                    // filtering, because there may be no way for the user to
12313                    // actually re-launch them.
12314                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12315                            && ps.getStopped(userId);
12316                }
12317            }
12318            return false;
12319        }
12320
12321        @Override
12322        protected boolean isPackageForFilter(String packageName,
12323                PackageParser.ServiceIntentInfo info) {
12324            return packageName.equals(info.service.owner.packageName);
12325        }
12326
12327        @Override
12328        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12329                int match, int userId) {
12330            if (!sUserManager.exists(userId)) return null;
12331            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12332            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12333                return null;
12334            }
12335            final PackageParser.Service service = info.service;
12336            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12337            if (ps == null) {
12338                return null;
12339            }
12340            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12341                    ps.readUserState(userId), userId);
12342            if (si == null) {
12343                return null;
12344            }
12345            final ResolveInfo res = new ResolveInfo();
12346            res.serviceInfo = si;
12347            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12348                res.filter = filter;
12349            }
12350            res.priority = info.getPriority();
12351            res.preferredOrder = service.owner.mPreferredOrder;
12352            res.match = match;
12353            res.isDefault = info.hasDefault;
12354            res.labelRes = info.labelRes;
12355            res.nonLocalizedLabel = info.nonLocalizedLabel;
12356            res.icon = info.icon;
12357            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12358            return res;
12359        }
12360
12361        @Override
12362        protected void sortResults(List<ResolveInfo> results) {
12363            Collections.sort(results, mResolvePrioritySorter);
12364        }
12365
12366        @Override
12367        protected void dumpFilter(PrintWriter out, String prefix,
12368                PackageParser.ServiceIntentInfo filter) {
12369            out.print(prefix); out.print(
12370                    Integer.toHexString(System.identityHashCode(filter.service)));
12371                    out.print(' ');
12372                    filter.service.printComponentShortName(out);
12373                    out.print(" filter ");
12374                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12375        }
12376
12377        @Override
12378        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12379            return filter.service;
12380        }
12381
12382        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12383            PackageParser.Service service = (PackageParser.Service)label;
12384            out.print(prefix); out.print(
12385                    Integer.toHexString(System.identityHashCode(service)));
12386                    out.print(' ');
12387                    service.printComponentShortName(out);
12388            if (count > 1) {
12389                out.print(" ("); out.print(count); out.print(" filters)");
12390            }
12391            out.println();
12392        }
12393
12394//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12395//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12396//            final List<ResolveInfo> retList = Lists.newArrayList();
12397//            while (i.hasNext()) {
12398//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12399//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12400//                    retList.add(resolveInfo);
12401//                }
12402//            }
12403//            return retList;
12404//        }
12405
12406        // Keys are String (activity class name), values are Activity.
12407        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12408                = new ArrayMap<ComponentName, PackageParser.Service>();
12409        private int mFlags;
12410    }
12411
12412    private final class ProviderIntentResolver
12413            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12414        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12415                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
12416            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12417            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
12418                    isEphemeral, userId);
12419        }
12420
12421        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12422                int userId) {
12423            if (!sUserManager.exists(userId))
12424                return null;
12425            mFlags = flags;
12426            return super.queryIntent(intent, resolvedType,
12427                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12428                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
12429                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
12430        }
12431
12432        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12433                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12434            if (!sUserManager.exists(userId))
12435                return null;
12436            if (packageProviders == null) {
12437                return null;
12438            }
12439            mFlags = flags;
12440            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12441            final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0;
12442            final boolean vislbleToEphemeral =
12443                    (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
12444            final int N = packageProviders.size();
12445            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12446                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12447
12448            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12449            for (int i = 0; i < N; ++i) {
12450                intentFilters = packageProviders.get(i).intents;
12451                if (intentFilters != null && intentFilters.size() > 0) {
12452                    PackageParser.ProviderIntentInfo[] array =
12453                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12454                    intentFilters.toArray(array);
12455                    listCut.add(array);
12456                }
12457            }
12458            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
12459                    vislbleToEphemeral, isEphemeral, listCut, userId);
12460        }
12461
12462        public final void addProvider(PackageParser.Provider p) {
12463            if (mProviders.containsKey(p.getComponentName())) {
12464                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12465                return;
12466            }
12467
12468            mProviders.put(p.getComponentName(), p);
12469            if (DEBUG_SHOW_INFO) {
12470                Log.v(TAG, "  "
12471                        + (p.info.nonLocalizedLabel != null
12472                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12473                Log.v(TAG, "    Class=" + p.info.name);
12474            }
12475            final int NI = p.intents.size();
12476            int j;
12477            for (j = 0; j < NI; j++) {
12478                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12479                if (DEBUG_SHOW_INFO) {
12480                    Log.v(TAG, "    IntentFilter:");
12481                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12482                }
12483                if (!intent.debugCheck()) {
12484                    Log.w(TAG, "==> For Provider " + p.info.name);
12485                }
12486                addFilter(intent);
12487            }
12488        }
12489
12490        public final void removeProvider(PackageParser.Provider p) {
12491            mProviders.remove(p.getComponentName());
12492            if (DEBUG_SHOW_INFO) {
12493                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12494                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12495                Log.v(TAG, "    Class=" + p.info.name);
12496            }
12497            final int NI = p.intents.size();
12498            int j;
12499            for (j = 0; j < NI; j++) {
12500                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12501                if (DEBUG_SHOW_INFO) {
12502                    Log.v(TAG, "    IntentFilter:");
12503                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12504                }
12505                removeFilter(intent);
12506            }
12507        }
12508
12509        @Override
12510        protected boolean allowFilterResult(
12511                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12512            ProviderInfo filterPi = filter.provider.info;
12513            for (int i = dest.size() - 1; i >= 0; i--) {
12514                ProviderInfo destPi = dest.get(i).providerInfo;
12515                if (destPi.name == filterPi.name
12516                        && destPi.packageName == filterPi.packageName) {
12517                    return false;
12518                }
12519            }
12520            return true;
12521        }
12522
12523        @Override
12524        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12525            return new PackageParser.ProviderIntentInfo[size];
12526        }
12527
12528        @Override
12529        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12530            if (!sUserManager.exists(userId))
12531                return true;
12532            PackageParser.Package p = filter.provider.owner;
12533            if (p != null) {
12534                PackageSetting ps = (PackageSetting) p.mExtras;
12535                if (ps != null) {
12536                    // System apps are never considered stopped for purposes of
12537                    // filtering, because there may be no way for the user to
12538                    // actually re-launch them.
12539                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12540                            && ps.getStopped(userId);
12541                }
12542            }
12543            return false;
12544        }
12545
12546        @Override
12547        protected boolean isPackageForFilter(String packageName,
12548                PackageParser.ProviderIntentInfo info) {
12549            return packageName.equals(info.provider.owner.packageName);
12550        }
12551
12552        @Override
12553        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12554                int match, int userId) {
12555            if (!sUserManager.exists(userId))
12556                return null;
12557            final PackageParser.ProviderIntentInfo info = filter;
12558            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12559                return null;
12560            }
12561            final PackageParser.Provider provider = info.provider;
12562            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12563            if (ps == null) {
12564                return null;
12565            }
12566            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12567                    ps.readUserState(userId), userId);
12568            if (pi == null) {
12569                return null;
12570            }
12571            final ResolveInfo res = new ResolveInfo();
12572            res.providerInfo = pi;
12573            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12574                res.filter = filter;
12575            }
12576            res.priority = info.getPriority();
12577            res.preferredOrder = provider.owner.mPreferredOrder;
12578            res.match = match;
12579            res.isDefault = info.hasDefault;
12580            res.labelRes = info.labelRes;
12581            res.nonLocalizedLabel = info.nonLocalizedLabel;
12582            res.icon = info.icon;
12583            res.system = res.providerInfo.applicationInfo.isSystemApp();
12584            return res;
12585        }
12586
12587        @Override
12588        protected void sortResults(List<ResolveInfo> results) {
12589            Collections.sort(results, mResolvePrioritySorter);
12590        }
12591
12592        @Override
12593        protected void dumpFilter(PrintWriter out, String prefix,
12594                PackageParser.ProviderIntentInfo filter) {
12595            out.print(prefix);
12596            out.print(
12597                    Integer.toHexString(System.identityHashCode(filter.provider)));
12598            out.print(' ');
12599            filter.provider.printComponentShortName(out);
12600            out.print(" filter ");
12601            out.println(Integer.toHexString(System.identityHashCode(filter)));
12602        }
12603
12604        @Override
12605        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12606            return filter.provider;
12607        }
12608
12609        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12610            PackageParser.Provider provider = (PackageParser.Provider)label;
12611            out.print(prefix); out.print(
12612                    Integer.toHexString(System.identityHashCode(provider)));
12613                    out.print(' ');
12614                    provider.printComponentShortName(out);
12615            if (count > 1) {
12616                out.print(" ("); out.print(count); out.print(" filters)");
12617            }
12618            out.println();
12619        }
12620
12621        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12622                = new ArrayMap<ComponentName, PackageParser.Provider>();
12623        private int mFlags;
12624    }
12625
12626    static final class EphemeralIntentResolver
12627            extends IntentResolver<EphemeralResponse, EphemeralResponse> {
12628        /**
12629         * The result that has the highest defined order. Ordering applies on a
12630         * per-package basis. Mapping is from package name to Pair of order and
12631         * EphemeralResolveInfo.
12632         * <p>
12633         * NOTE: This is implemented as a field variable for convenience and efficiency.
12634         * By having a field variable, we're able to track filter ordering as soon as
12635         * a non-zero order is defined. Otherwise, multiple loops across the result set
12636         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12637         * this needs to be contained entirely within {@link #filterResults()}.
12638         */
12639        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
12640
12641        @Override
12642        protected EphemeralResponse[] newArray(int size) {
12643            return new EphemeralResponse[size];
12644        }
12645
12646        @Override
12647        protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) {
12648            return true;
12649        }
12650
12651        @Override
12652        protected EphemeralResponse newResult(EphemeralResponse responseObj, int match,
12653                int userId) {
12654            if (!sUserManager.exists(userId)) {
12655                return null;
12656            }
12657            final String packageName = responseObj.resolveInfo.getPackageName();
12658            final Integer order = responseObj.getOrder();
12659            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
12660                    mOrderResult.get(packageName);
12661            // ordering is enabled and this item's order isn't high enough
12662            if (lastOrderResult != null && lastOrderResult.first >= order) {
12663                return null;
12664            }
12665            final EphemeralResolveInfo res = responseObj.resolveInfo;
12666            if (order > 0) {
12667                // non-zero order, enable ordering
12668                mOrderResult.put(packageName, new Pair<>(order, res));
12669            }
12670            return responseObj;
12671        }
12672
12673        @Override
12674        protected void filterResults(List<EphemeralResponse> results) {
12675            // only do work if ordering is enabled [most of the time it won't be]
12676            if (mOrderResult.size() == 0) {
12677                return;
12678            }
12679            int resultSize = results.size();
12680            for (int i = 0; i < resultSize; i++) {
12681                final EphemeralResolveInfo info = results.get(i).resolveInfo;
12682                final String packageName = info.getPackageName();
12683                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
12684                if (savedInfo == null) {
12685                    // package doesn't having ordering
12686                    continue;
12687                }
12688                if (savedInfo.second == info) {
12689                    // circled back to the highest ordered item; remove from order list
12690                    mOrderResult.remove(savedInfo);
12691                    if (mOrderResult.size() == 0) {
12692                        // no more ordered items
12693                        break;
12694                    }
12695                    continue;
12696                }
12697                // item has a worse order, remove it from the result list
12698                results.remove(i);
12699                resultSize--;
12700                i--;
12701            }
12702        }
12703    }
12704
12705    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12706            new Comparator<ResolveInfo>() {
12707        public int compare(ResolveInfo r1, ResolveInfo r2) {
12708            int v1 = r1.priority;
12709            int v2 = r2.priority;
12710            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12711            if (v1 != v2) {
12712                return (v1 > v2) ? -1 : 1;
12713            }
12714            v1 = r1.preferredOrder;
12715            v2 = r2.preferredOrder;
12716            if (v1 != v2) {
12717                return (v1 > v2) ? -1 : 1;
12718            }
12719            if (r1.isDefault != r2.isDefault) {
12720                return r1.isDefault ? -1 : 1;
12721            }
12722            v1 = r1.match;
12723            v2 = r2.match;
12724            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12725            if (v1 != v2) {
12726                return (v1 > v2) ? -1 : 1;
12727            }
12728            if (r1.system != r2.system) {
12729                return r1.system ? -1 : 1;
12730            }
12731            if (r1.activityInfo != null) {
12732                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12733            }
12734            if (r1.serviceInfo != null) {
12735                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12736            }
12737            if (r1.providerInfo != null) {
12738                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12739            }
12740            return 0;
12741        }
12742    };
12743
12744    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12745            new Comparator<ProviderInfo>() {
12746        public int compare(ProviderInfo p1, ProviderInfo p2) {
12747            final int v1 = p1.initOrder;
12748            final int v2 = p2.initOrder;
12749            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12750        }
12751    };
12752
12753    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12754            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12755            final int[] userIds) {
12756        mHandler.post(new Runnable() {
12757            @Override
12758            public void run() {
12759                try {
12760                    final IActivityManager am = ActivityManager.getService();
12761                    if (am == null) return;
12762                    final int[] resolvedUserIds;
12763                    if (userIds == null) {
12764                        resolvedUserIds = am.getRunningUserIds();
12765                    } else {
12766                        resolvedUserIds = userIds;
12767                    }
12768                    for (int id : resolvedUserIds) {
12769                        final Intent intent = new Intent(action,
12770                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12771                        if (extras != null) {
12772                            intent.putExtras(extras);
12773                        }
12774                        if (targetPkg != null) {
12775                            intent.setPackage(targetPkg);
12776                        }
12777                        // Modify the UID when posting to other users
12778                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12779                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12780                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12781                            intent.putExtra(Intent.EXTRA_UID, uid);
12782                        }
12783                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12784                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12785                        if (DEBUG_BROADCASTS) {
12786                            RuntimeException here = new RuntimeException("here");
12787                            here.fillInStackTrace();
12788                            Slog.d(TAG, "Sending to user " + id + ": "
12789                                    + intent.toShortString(false, true, false, false)
12790                                    + " " + intent.getExtras(), here);
12791                        }
12792                        am.broadcastIntent(null, intent, null, finishedReceiver,
12793                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12794                                null, finishedReceiver != null, false, id);
12795                    }
12796                } catch (RemoteException ex) {
12797                }
12798            }
12799        });
12800    }
12801
12802    /**
12803     * Check if the external storage media is available. This is true if there
12804     * is a mounted external storage medium or if the external storage is
12805     * emulated.
12806     */
12807    private boolean isExternalMediaAvailable() {
12808        return mMediaMounted || Environment.isExternalStorageEmulated();
12809    }
12810
12811    @Override
12812    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12813        // writer
12814        synchronized (mPackages) {
12815            if (!isExternalMediaAvailable()) {
12816                // If the external storage is no longer mounted at this point,
12817                // the caller may not have been able to delete all of this
12818                // packages files and can not delete any more.  Bail.
12819                return null;
12820            }
12821            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12822            if (lastPackage != null) {
12823                pkgs.remove(lastPackage);
12824            }
12825            if (pkgs.size() > 0) {
12826                return pkgs.get(0);
12827            }
12828        }
12829        return null;
12830    }
12831
12832    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
12833        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12834                userId, andCode ? 1 : 0, packageName);
12835        if (mSystemReady) {
12836            msg.sendToTarget();
12837        } else {
12838            if (mPostSystemReadyMessages == null) {
12839                mPostSystemReadyMessages = new ArrayList<>();
12840            }
12841            mPostSystemReadyMessages.add(msg);
12842        }
12843    }
12844
12845    void startCleaningPackages() {
12846        // reader
12847        if (!isExternalMediaAvailable()) {
12848            return;
12849        }
12850        synchronized (mPackages) {
12851            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
12852                return;
12853            }
12854        }
12855        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
12856        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
12857        IActivityManager am = ActivityManager.getService();
12858        if (am != null) {
12859            try {
12860                am.startService(null, intent, null, -1, null, mContext.getOpPackageName(),
12861                        UserHandle.USER_SYSTEM);
12862            } catch (RemoteException e) {
12863            }
12864        }
12865    }
12866
12867    @Override
12868    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
12869            int installFlags, String installerPackageName, int userId) {
12870        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
12871
12872        final int callingUid = Binder.getCallingUid();
12873        enforceCrossUserPermission(callingUid, userId,
12874                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
12875
12876        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12877            try {
12878                if (observer != null) {
12879                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
12880                }
12881            } catch (RemoteException re) {
12882            }
12883            return;
12884        }
12885
12886        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
12887            installFlags |= PackageManager.INSTALL_FROM_ADB;
12888
12889        } else {
12890            // Caller holds INSTALL_PACKAGES permission, so we're less strict
12891            // about installerPackageName.
12892
12893            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
12894            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
12895        }
12896
12897        UserHandle user;
12898        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
12899            user = UserHandle.ALL;
12900        } else {
12901            user = new UserHandle(userId);
12902        }
12903
12904        // Only system components can circumvent runtime permissions when installing.
12905        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
12906                && mContext.checkCallingOrSelfPermission(Manifest.permission
12907                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
12908            throw new SecurityException("You need the "
12909                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
12910                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
12911        }
12912
12913        final File originFile = new File(originPath);
12914        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
12915
12916        final Message msg = mHandler.obtainMessage(INIT_COPY);
12917        final VerificationInfo verificationInfo = new VerificationInfo(
12918                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
12919        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
12920                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
12921                null /*packageAbiOverride*/, null /*grantedPermissions*/,
12922                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
12923        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
12924        msg.obj = params;
12925
12926        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
12927                System.identityHashCode(msg.obj));
12928        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12929                System.identityHashCode(msg.obj));
12930
12931        mHandler.sendMessage(msg);
12932    }
12933
12934
12935    /**
12936     * Ensure that the install reason matches what we know about the package installer (e.g. whether
12937     * it is acting on behalf on an enterprise or the user).
12938     *
12939     * Note that the ordering of the conditionals in this method is important. The checks we perform
12940     * are as follows, in this order:
12941     *
12942     * 1) If the install is being performed by a system app, we can trust the app to have set the
12943     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
12944     *    what it is.
12945     * 2) If the install is being performed by a device or profile owner app, the install reason
12946     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
12947     *    set the install reason correctly. If the app targets an older SDK version where install
12948     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
12949     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
12950     * 3) In all other cases, the install is being performed by a regular app that is neither part
12951     *    of the system nor a device or profile owner. We have no reason to believe that this app is
12952     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
12953     *    set to enterprise policy and if so, change it to unknown instead.
12954     */
12955    private int fixUpInstallReason(String installerPackageName, int installerUid,
12956            int installReason) {
12957        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
12958                == PERMISSION_GRANTED) {
12959            // If the install is being performed by a system app, we trust that app to have set the
12960            // install reason correctly.
12961            return installReason;
12962        }
12963
12964        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12965            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12966        if (dpm != null) {
12967            ComponentName owner = null;
12968            try {
12969                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
12970                if (owner == null) {
12971                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
12972                }
12973            } catch (RemoteException e) {
12974            }
12975            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
12976                // If the install is being performed by a device or profile owner, the install
12977                // reason should be enterprise policy.
12978                return PackageManager.INSTALL_REASON_POLICY;
12979            }
12980        }
12981
12982        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
12983            // If the install is being performed by a regular app (i.e. neither system app nor
12984            // device or profile owner), we have no reason to believe that the app is acting on
12985            // behalf of an enterprise. If the app set the install reason to enterprise policy,
12986            // change it to unknown instead.
12987            return PackageManager.INSTALL_REASON_UNKNOWN;
12988        }
12989
12990        // If the install is being performed by a regular app and the install reason was set to any
12991        // value but enterprise policy, leave the install reason unchanged.
12992        return installReason;
12993    }
12994
12995    void installStage(String packageName, File stagedDir, String stagedCid,
12996            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
12997            String installerPackageName, int installerUid, UserHandle user,
12998            Certificate[][] certificates) {
12999        if (DEBUG_EPHEMERAL) {
13000            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
13001                Slog.d(TAG, "Ephemeral install of " + packageName);
13002            }
13003        }
13004        final VerificationInfo verificationInfo = new VerificationInfo(
13005                sessionParams.originatingUri, sessionParams.referrerUri,
13006                sessionParams.originatingUid, installerUid);
13007
13008        final OriginInfo origin;
13009        if (stagedDir != null) {
13010            origin = OriginInfo.fromStagedFile(stagedDir);
13011        } else {
13012            origin = OriginInfo.fromStagedContainer(stagedCid);
13013        }
13014
13015        final Message msg = mHandler.obtainMessage(INIT_COPY);
13016        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13017                sessionParams.installReason);
13018        final InstallParams params = new InstallParams(origin, null, observer,
13019                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13020                verificationInfo, user, sessionParams.abiOverride,
13021                sessionParams.grantedRuntimePermissions, certificates, installReason);
13022        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13023        msg.obj = params;
13024
13025        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13026                System.identityHashCode(msg.obj));
13027        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13028                System.identityHashCode(msg.obj));
13029
13030        mHandler.sendMessage(msg);
13031    }
13032
13033    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13034            int userId) {
13035        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13036        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13037    }
13038
13039    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
13040            int appId, int... userIds) {
13041        if (ArrayUtils.isEmpty(userIds)) {
13042            return;
13043        }
13044        Bundle extras = new Bundle(1);
13045        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13046        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13047
13048        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13049                packageName, extras, 0, null, null, userIds);
13050        if (isSystem) {
13051            mHandler.post(() -> {
13052                        for (int userId : userIds) {
13053                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13054                        }
13055                    }
13056            );
13057        }
13058    }
13059
13060    /**
13061     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13062     * automatically without needing an explicit launch.
13063     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13064     */
13065    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13066        // If user is not running, the app didn't miss any broadcast
13067        if (!mUserManagerInternal.isUserRunning(userId)) {
13068            return;
13069        }
13070        final IActivityManager am = ActivityManager.getService();
13071        try {
13072            // Deliver LOCKED_BOOT_COMPLETED first
13073            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13074                    .setPackage(packageName);
13075            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13076            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13077                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13078
13079            // Deliver BOOT_COMPLETED only if user is unlocked
13080            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13081                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13082                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13083                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13084            }
13085        } catch (RemoteException e) {
13086            throw e.rethrowFromSystemServer();
13087        }
13088    }
13089
13090    @Override
13091    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13092            int userId) {
13093        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13094        PackageSetting pkgSetting;
13095        final int uid = Binder.getCallingUid();
13096        enforceCrossUserPermission(uid, userId,
13097                true /* requireFullPermission */, true /* checkShell */,
13098                "setApplicationHiddenSetting for user " + userId);
13099
13100        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13101            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13102            return false;
13103        }
13104
13105        long callingId = Binder.clearCallingIdentity();
13106        try {
13107            boolean sendAdded = false;
13108            boolean sendRemoved = false;
13109            // writer
13110            synchronized (mPackages) {
13111                pkgSetting = mSettings.mPackages.get(packageName);
13112                if (pkgSetting == null) {
13113                    return false;
13114                }
13115                // Do not allow "android" is being disabled
13116                if ("android".equals(packageName)) {
13117                    Slog.w(TAG, "Cannot hide package: android");
13118                    return false;
13119                }
13120                // Cannot hide static shared libs as they are considered
13121                // a part of the using app (emulating static linking). Also
13122                // static libs are installed always on internal storage.
13123                PackageParser.Package pkg = mPackages.get(packageName);
13124                if (pkg != null && pkg.staticSharedLibName != null) {
13125                    Slog.w(TAG, "Cannot hide package: " + packageName
13126                            + " providing static shared library: "
13127                            + pkg.staticSharedLibName);
13128                    return false;
13129                }
13130                // Only allow protected packages to hide themselves.
13131                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13132                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13133                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13134                    return false;
13135                }
13136
13137                if (pkgSetting.getHidden(userId) != hidden) {
13138                    pkgSetting.setHidden(hidden, userId);
13139                    mSettings.writePackageRestrictionsLPr(userId);
13140                    if (hidden) {
13141                        sendRemoved = true;
13142                    } else {
13143                        sendAdded = true;
13144                    }
13145                }
13146            }
13147            if (sendAdded) {
13148                sendPackageAddedForUser(packageName, pkgSetting, userId);
13149                return true;
13150            }
13151            if (sendRemoved) {
13152                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13153                        "hiding pkg");
13154                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13155                return true;
13156            }
13157        } finally {
13158            Binder.restoreCallingIdentity(callingId);
13159        }
13160        return false;
13161    }
13162
13163    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13164            int userId) {
13165        final PackageRemovedInfo info = new PackageRemovedInfo();
13166        info.removedPackage = packageName;
13167        info.removedUsers = new int[] {userId};
13168        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13169        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13170    }
13171
13172    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13173        if (pkgList.length > 0) {
13174            Bundle extras = new Bundle(1);
13175            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13176
13177            sendPackageBroadcast(
13178                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13179                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13180                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13181                    new int[] {userId});
13182        }
13183    }
13184
13185    /**
13186     * Returns true if application is not found or there was an error. Otherwise it returns
13187     * the hidden state of the package for the given user.
13188     */
13189    @Override
13190    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13191        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13192        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13193                true /* requireFullPermission */, false /* checkShell */,
13194                "getApplicationHidden for user " + userId);
13195        PackageSetting pkgSetting;
13196        long callingId = Binder.clearCallingIdentity();
13197        try {
13198            // writer
13199            synchronized (mPackages) {
13200                pkgSetting = mSettings.mPackages.get(packageName);
13201                if (pkgSetting == null) {
13202                    return true;
13203                }
13204                return pkgSetting.getHidden(userId);
13205            }
13206        } finally {
13207            Binder.restoreCallingIdentity(callingId);
13208        }
13209    }
13210
13211    /**
13212     * @hide
13213     */
13214    @Override
13215    public int installExistingPackageAsUser(String packageName, int userId, int installReason) {
13216        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13217                null);
13218        PackageSetting pkgSetting;
13219        final int uid = Binder.getCallingUid();
13220        enforceCrossUserPermission(uid, userId,
13221                true /* requireFullPermission */, true /* checkShell */,
13222                "installExistingPackage for user " + userId);
13223        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13224            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13225        }
13226
13227        long callingId = Binder.clearCallingIdentity();
13228        try {
13229            boolean installed = false;
13230
13231            // writer
13232            synchronized (mPackages) {
13233                pkgSetting = mSettings.mPackages.get(packageName);
13234                if (pkgSetting == null) {
13235                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13236                }
13237                if (!pkgSetting.getInstalled(userId)) {
13238                    pkgSetting.setInstalled(true, userId);
13239                    pkgSetting.setHidden(false, userId);
13240                    pkgSetting.setInstallReason(installReason, userId);
13241                    mSettings.writePackageRestrictionsLPr(userId);
13242                    installed = true;
13243                }
13244            }
13245
13246            if (installed) {
13247                if (pkgSetting.pkg != null) {
13248                    synchronized (mInstallLock) {
13249                        // We don't need to freeze for a brand new install
13250                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13251                    }
13252                }
13253                sendPackageAddedForUser(packageName, pkgSetting, userId);
13254            }
13255        } finally {
13256            Binder.restoreCallingIdentity(callingId);
13257        }
13258
13259        return PackageManager.INSTALL_SUCCEEDED;
13260    }
13261
13262    boolean isUserRestricted(int userId, String restrictionKey) {
13263        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13264        if (restrictions.getBoolean(restrictionKey, false)) {
13265            Log.w(TAG, "User is restricted: " + restrictionKey);
13266            return true;
13267        }
13268        return false;
13269    }
13270
13271    @Override
13272    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13273            int userId) {
13274        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13275        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13276                true /* requireFullPermission */, true /* checkShell */,
13277                "setPackagesSuspended for user " + userId);
13278
13279        if (ArrayUtils.isEmpty(packageNames)) {
13280            return packageNames;
13281        }
13282
13283        // List of package names for whom the suspended state has changed.
13284        List<String> changedPackages = new ArrayList<>(packageNames.length);
13285        // List of package names for whom the suspended state is not set as requested in this
13286        // method.
13287        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13288        long callingId = Binder.clearCallingIdentity();
13289        try {
13290            for (int i = 0; i < packageNames.length; i++) {
13291                String packageName = packageNames[i];
13292                boolean changed = false;
13293                final int appId;
13294                synchronized (mPackages) {
13295                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13296                    if (pkgSetting == null) {
13297                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13298                                + "\". Skipping suspending/un-suspending.");
13299                        unactionedPackages.add(packageName);
13300                        continue;
13301                    }
13302                    appId = pkgSetting.appId;
13303                    if (pkgSetting.getSuspended(userId) != suspended) {
13304                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13305                            unactionedPackages.add(packageName);
13306                            continue;
13307                        }
13308                        pkgSetting.setSuspended(suspended, userId);
13309                        mSettings.writePackageRestrictionsLPr(userId);
13310                        changed = true;
13311                        changedPackages.add(packageName);
13312                    }
13313                }
13314
13315                if (changed && suspended) {
13316                    killApplication(packageName, UserHandle.getUid(userId, appId),
13317                            "suspending package");
13318                }
13319            }
13320        } finally {
13321            Binder.restoreCallingIdentity(callingId);
13322        }
13323
13324        if (!changedPackages.isEmpty()) {
13325            sendPackagesSuspendedForUser(changedPackages.toArray(
13326                    new String[changedPackages.size()]), userId, suspended);
13327        }
13328
13329        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13330    }
13331
13332    @Override
13333    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13334        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13335                true /* requireFullPermission */, false /* checkShell */,
13336                "isPackageSuspendedForUser for user " + userId);
13337        synchronized (mPackages) {
13338            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13339            if (pkgSetting == null) {
13340                throw new IllegalArgumentException("Unknown target package: " + packageName);
13341            }
13342            return pkgSetting.getSuspended(userId);
13343        }
13344    }
13345
13346    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13347        if (isPackageDeviceAdmin(packageName, userId)) {
13348            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13349                    + "\": has an active device admin");
13350            return false;
13351        }
13352
13353        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13354        if (packageName.equals(activeLauncherPackageName)) {
13355            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13356                    + "\": contains the active launcher");
13357            return false;
13358        }
13359
13360        if (packageName.equals(mRequiredInstallerPackage)) {
13361            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13362                    + "\": required for package installation");
13363            return false;
13364        }
13365
13366        if (packageName.equals(mRequiredUninstallerPackage)) {
13367            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13368                    + "\": required for package uninstallation");
13369            return false;
13370        }
13371
13372        if (packageName.equals(mRequiredVerifierPackage)) {
13373            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13374                    + "\": required for package verification");
13375            return false;
13376        }
13377
13378        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13379            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13380                    + "\": is the default dialer");
13381            return false;
13382        }
13383
13384        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13385            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13386                    + "\": protected package");
13387            return false;
13388        }
13389
13390        // Cannot suspend static shared libs as they are considered
13391        // a part of the using app (emulating static linking). Also
13392        // static libs are installed always on internal storage.
13393        PackageParser.Package pkg = mPackages.get(packageName);
13394        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13395            Slog.w(TAG, "Cannot suspend package: " + packageName
13396                    + " providing static shared library: "
13397                    + pkg.staticSharedLibName);
13398            return false;
13399        }
13400
13401        return true;
13402    }
13403
13404    private String getActiveLauncherPackageName(int userId) {
13405        Intent intent = new Intent(Intent.ACTION_MAIN);
13406        intent.addCategory(Intent.CATEGORY_HOME);
13407        ResolveInfo resolveInfo = resolveIntent(
13408                intent,
13409                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13410                PackageManager.MATCH_DEFAULT_ONLY,
13411                userId);
13412
13413        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13414    }
13415
13416    private String getDefaultDialerPackageName(int userId) {
13417        synchronized (mPackages) {
13418            return mSettings.getDefaultDialerPackageNameLPw(userId);
13419        }
13420    }
13421
13422    @Override
13423    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13424        mContext.enforceCallingOrSelfPermission(
13425                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13426                "Only package verification agents can verify applications");
13427
13428        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13429        final PackageVerificationResponse response = new PackageVerificationResponse(
13430                verificationCode, Binder.getCallingUid());
13431        msg.arg1 = id;
13432        msg.obj = response;
13433        mHandler.sendMessage(msg);
13434    }
13435
13436    @Override
13437    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13438            long millisecondsToDelay) {
13439        mContext.enforceCallingOrSelfPermission(
13440                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13441                "Only package verification agents can extend verification timeouts");
13442
13443        final PackageVerificationState state = mPendingVerification.get(id);
13444        final PackageVerificationResponse response = new PackageVerificationResponse(
13445                verificationCodeAtTimeout, Binder.getCallingUid());
13446
13447        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13448            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13449        }
13450        if (millisecondsToDelay < 0) {
13451            millisecondsToDelay = 0;
13452        }
13453        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13454                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13455            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13456        }
13457
13458        if ((state != null) && !state.timeoutExtended()) {
13459            state.extendTimeout();
13460
13461            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13462            msg.arg1 = id;
13463            msg.obj = response;
13464            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13465        }
13466    }
13467
13468    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13469            int verificationCode, UserHandle user) {
13470        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13471        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13472        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13473        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13474        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13475
13476        mContext.sendBroadcastAsUser(intent, user,
13477                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13478    }
13479
13480    private ComponentName matchComponentForVerifier(String packageName,
13481            List<ResolveInfo> receivers) {
13482        ActivityInfo targetReceiver = null;
13483
13484        final int NR = receivers.size();
13485        for (int i = 0; i < NR; i++) {
13486            final ResolveInfo info = receivers.get(i);
13487            if (info.activityInfo == null) {
13488                continue;
13489            }
13490
13491            if (packageName.equals(info.activityInfo.packageName)) {
13492                targetReceiver = info.activityInfo;
13493                break;
13494            }
13495        }
13496
13497        if (targetReceiver == null) {
13498            return null;
13499        }
13500
13501        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13502    }
13503
13504    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13505            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13506        if (pkgInfo.verifiers.length == 0) {
13507            return null;
13508        }
13509
13510        final int N = pkgInfo.verifiers.length;
13511        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13512        for (int i = 0; i < N; i++) {
13513            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13514
13515            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13516                    receivers);
13517            if (comp == null) {
13518                continue;
13519            }
13520
13521            final int verifierUid = getUidForVerifier(verifierInfo);
13522            if (verifierUid == -1) {
13523                continue;
13524            }
13525
13526            if (DEBUG_VERIFY) {
13527                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13528                        + " with the correct signature");
13529            }
13530            sufficientVerifiers.add(comp);
13531            verificationState.addSufficientVerifier(verifierUid);
13532        }
13533
13534        return sufficientVerifiers;
13535    }
13536
13537    private int getUidForVerifier(VerifierInfo verifierInfo) {
13538        synchronized (mPackages) {
13539            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13540            if (pkg == null) {
13541                return -1;
13542            } else if (pkg.mSignatures.length != 1) {
13543                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13544                        + " has more than one signature; ignoring");
13545                return -1;
13546            }
13547
13548            /*
13549             * If the public key of the package's signature does not match
13550             * our expected public key, then this is a different package and
13551             * we should skip.
13552             */
13553
13554            final byte[] expectedPublicKey;
13555            try {
13556                final Signature verifierSig = pkg.mSignatures[0];
13557                final PublicKey publicKey = verifierSig.getPublicKey();
13558                expectedPublicKey = publicKey.getEncoded();
13559            } catch (CertificateException e) {
13560                return -1;
13561            }
13562
13563            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13564
13565            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13566                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13567                        + " does not have the expected public key; ignoring");
13568                return -1;
13569            }
13570
13571            return pkg.applicationInfo.uid;
13572        }
13573    }
13574
13575    @Override
13576    public void finishPackageInstall(int token, boolean didLaunch) {
13577        enforceSystemOrRoot("Only the system is allowed to finish installs");
13578
13579        if (DEBUG_INSTALL) {
13580            Slog.v(TAG, "BM finishing package install for " + token);
13581        }
13582        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13583
13584        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13585        mHandler.sendMessage(msg);
13586    }
13587
13588    /**
13589     * Get the verification agent timeout.
13590     *
13591     * @return verification timeout in milliseconds
13592     */
13593    private long getVerificationTimeout() {
13594        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13595                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13596                DEFAULT_VERIFICATION_TIMEOUT);
13597    }
13598
13599    /**
13600     * Get the default verification agent response code.
13601     *
13602     * @return default verification response code
13603     */
13604    private int getDefaultVerificationResponse() {
13605        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13606                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13607                DEFAULT_VERIFICATION_RESPONSE);
13608    }
13609
13610    /**
13611     * Check whether or not package verification has been enabled.
13612     *
13613     * @return true if verification should be performed
13614     */
13615    private boolean isVerificationEnabled(int userId, int installFlags) {
13616        if (!DEFAULT_VERIFY_ENABLE) {
13617            return false;
13618        }
13619        // Ephemeral apps don't get the full verification treatment
13620        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
13621            if (DEBUG_EPHEMERAL) {
13622                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
13623            }
13624            return false;
13625        }
13626
13627        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13628
13629        // Check if installing from ADB
13630        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13631            // Do not run verification in a test harness environment
13632            if (ActivityManager.isRunningInTestHarness()) {
13633                return false;
13634            }
13635            if (ensureVerifyAppsEnabled) {
13636                return true;
13637            }
13638            // Check if the developer does not want package verification for ADB installs
13639            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13640                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13641                return false;
13642            }
13643        }
13644
13645        if (ensureVerifyAppsEnabled) {
13646            return true;
13647        }
13648
13649        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13650                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13651    }
13652
13653    @Override
13654    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13655            throws RemoteException {
13656        mContext.enforceCallingOrSelfPermission(
13657                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13658                "Only intentfilter verification agents can verify applications");
13659
13660        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13661        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13662                Binder.getCallingUid(), verificationCode, failedDomains);
13663        msg.arg1 = id;
13664        msg.obj = response;
13665        mHandler.sendMessage(msg);
13666    }
13667
13668    @Override
13669    public int getIntentVerificationStatus(String packageName, int userId) {
13670        synchronized (mPackages) {
13671            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13672        }
13673    }
13674
13675    @Override
13676    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13677        mContext.enforceCallingOrSelfPermission(
13678                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13679
13680        boolean result = false;
13681        synchronized (mPackages) {
13682            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13683        }
13684        if (result) {
13685            scheduleWritePackageRestrictionsLocked(userId);
13686        }
13687        return result;
13688    }
13689
13690    @Override
13691    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13692            String packageName) {
13693        synchronized (mPackages) {
13694            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13695        }
13696    }
13697
13698    @Override
13699    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13700        if (TextUtils.isEmpty(packageName)) {
13701            return ParceledListSlice.emptyList();
13702        }
13703        synchronized (mPackages) {
13704            PackageParser.Package pkg = mPackages.get(packageName);
13705            if (pkg == null || pkg.activities == null) {
13706                return ParceledListSlice.emptyList();
13707            }
13708            final int count = pkg.activities.size();
13709            ArrayList<IntentFilter> result = new ArrayList<>();
13710            for (int n=0; n<count; n++) {
13711                PackageParser.Activity activity = pkg.activities.get(n);
13712                if (activity.intents != null && activity.intents.size() > 0) {
13713                    result.addAll(activity.intents);
13714                }
13715            }
13716            return new ParceledListSlice<>(result);
13717        }
13718    }
13719
13720    @Override
13721    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13722        mContext.enforceCallingOrSelfPermission(
13723                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13724
13725        synchronized (mPackages) {
13726            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13727            if (packageName != null) {
13728                result |= updateIntentVerificationStatus(packageName,
13729                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
13730                        userId);
13731                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
13732                        packageName, userId);
13733            }
13734            return result;
13735        }
13736    }
13737
13738    @Override
13739    public String getDefaultBrowserPackageName(int userId) {
13740        synchronized (mPackages) {
13741            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13742        }
13743    }
13744
13745    /**
13746     * Get the "allow unknown sources" setting.
13747     *
13748     * @return the current "allow unknown sources" setting
13749     */
13750    private int getUnknownSourcesSettings() {
13751        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13752                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13753                -1);
13754    }
13755
13756    @Override
13757    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13758        final int uid = Binder.getCallingUid();
13759        // writer
13760        synchronized (mPackages) {
13761            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13762            if (targetPackageSetting == null) {
13763                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13764            }
13765
13766            PackageSetting installerPackageSetting;
13767            if (installerPackageName != null) {
13768                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13769                if (installerPackageSetting == null) {
13770                    throw new IllegalArgumentException("Unknown installer package: "
13771                            + installerPackageName);
13772                }
13773            } else {
13774                installerPackageSetting = null;
13775            }
13776
13777            Signature[] callerSignature;
13778            Object obj = mSettings.getUserIdLPr(uid);
13779            if (obj != null) {
13780                if (obj instanceof SharedUserSetting) {
13781                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13782                } else if (obj instanceof PackageSetting) {
13783                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
13784                } else {
13785                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
13786                }
13787            } else {
13788                throw new SecurityException("Unknown calling UID: " + uid);
13789            }
13790
13791            // Verify: can't set installerPackageName to a package that is
13792            // not signed with the same cert as the caller.
13793            if (installerPackageSetting != null) {
13794                if (compareSignatures(callerSignature,
13795                        installerPackageSetting.signatures.mSignatures)
13796                        != PackageManager.SIGNATURE_MATCH) {
13797                    throw new SecurityException(
13798                            "Caller does not have same cert as new installer package "
13799                            + installerPackageName);
13800                }
13801            }
13802
13803            // Verify: if target already has an installer package, it must
13804            // be signed with the same cert as the caller.
13805            if (targetPackageSetting.installerPackageName != null) {
13806                PackageSetting setting = mSettings.mPackages.get(
13807                        targetPackageSetting.installerPackageName);
13808                // If the currently set package isn't valid, then it's always
13809                // okay to change it.
13810                if (setting != null) {
13811                    if (compareSignatures(callerSignature,
13812                            setting.signatures.mSignatures)
13813                            != PackageManager.SIGNATURE_MATCH) {
13814                        throw new SecurityException(
13815                                "Caller does not have same cert as old installer package "
13816                                + targetPackageSetting.installerPackageName);
13817                    }
13818                }
13819            }
13820
13821            // Okay!
13822            targetPackageSetting.installerPackageName = installerPackageName;
13823            if (installerPackageName != null) {
13824                mSettings.mInstallerPackages.add(installerPackageName);
13825            }
13826            scheduleWriteSettingsLocked();
13827        }
13828    }
13829
13830    @Override
13831    public void setApplicationCategoryHint(String packageName, int categoryHint,
13832            String callerPackageName) {
13833        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
13834                callerPackageName);
13835        synchronized (mPackages) {
13836            PackageSetting ps = mSettings.mPackages.get(packageName);
13837            if (ps == null) {
13838                throw new IllegalArgumentException("Unknown target package " + packageName);
13839            }
13840
13841            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
13842                throw new IllegalArgumentException("Calling package " + callerPackageName
13843                        + " is not installer for " + packageName);
13844            }
13845
13846            if (ps.categoryHint != categoryHint) {
13847                ps.categoryHint = categoryHint;
13848                scheduleWriteSettingsLocked();
13849            }
13850        }
13851    }
13852
13853    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
13854        // Queue up an async operation since the package installation may take a little while.
13855        mHandler.post(new Runnable() {
13856            public void run() {
13857                mHandler.removeCallbacks(this);
13858                 // Result object to be returned
13859                PackageInstalledInfo res = new PackageInstalledInfo();
13860                res.setReturnCode(currentStatus);
13861                res.uid = -1;
13862                res.pkg = null;
13863                res.removedInfo = null;
13864                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13865                    args.doPreInstall(res.returnCode);
13866                    synchronized (mInstallLock) {
13867                        installPackageTracedLI(args, res);
13868                    }
13869                    args.doPostInstall(res.returnCode, res.uid);
13870                }
13871
13872                // A restore should be performed at this point if (a) the install
13873                // succeeded, (b) the operation is not an update, and (c) the new
13874                // package has not opted out of backup participation.
13875                final boolean update = res.removedInfo != null
13876                        && res.removedInfo.removedPackage != null;
13877                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
13878                boolean doRestore = !update
13879                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
13880
13881                // Set up the post-install work request bookkeeping.  This will be used
13882                // and cleaned up by the post-install event handling regardless of whether
13883                // there's a restore pass performed.  Token values are >= 1.
13884                int token;
13885                if (mNextInstallToken < 0) mNextInstallToken = 1;
13886                token = mNextInstallToken++;
13887
13888                PostInstallData data = new PostInstallData(args, res);
13889                mRunningInstalls.put(token, data);
13890                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
13891
13892                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
13893                    // Pass responsibility to the Backup Manager.  It will perform a
13894                    // restore if appropriate, then pass responsibility back to the
13895                    // Package Manager to run the post-install observer callbacks
13896                    // and broadcasts.
13897                    IBackupManager bm = IBackupManager.Stub.asInterface(
13898                            ServiceManager.getService(Context.BACKUP_SERVICE));
13899                    if (bm != null) {
13900                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
13901                                + " to BM for possible restore");
13902                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13903                        try {
13904                            // TODO: http://b/22388012
13905                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
13906                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
13907                            } else {
13908                                doRestore = false;
13909                            }
13910                        } catch (RemoteException e) {
13911                            // can't happen; the backup manager is local
13912                        } catch (Exception e) {
13913                            Slog.e(TAG, "Exception trying to enqueue restore", e);
13914                            doRestore = false;
13915                        }
13916                    } else {
13917                        Slog.e(TAG, "Backup Manager not found!");
13918                        doRestore = false;
13919                    }
13920                }
13921
13922                if (!doRestore) {
13923                    // No restore possible, or the Backup Manager was mysteriously not
13924                    // available -- just fire the post-install work request directly.
13925                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
13926
13927                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
13928
13929                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
13930                    mHandler.sendMessage(msg);
13931                }
13932            }
13933        });
13934    }
13935
13936    /**
13937     * Callback from PackageSettings whenever an app is first transitioned out of the
13938     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
13939     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
13940     * here whether the app is the target of an ongoing install, and only send the
13941     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
13942     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
13943     * handling.
13944     */
13945    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
13946        // Serialize this with the rest of the install-process message chain.  In the
13947        // restore-at-install case, this Runnable will necessarily run before the
13948        // POST_INSTALL message is processed, so the contents of mRunningInstalls
13949        // are coherent.  In the non-restore case, the app has already completed install
13950        // and been launched through some other means, so it is not in a problematic
13951        // state for observers to see the FIRST_LAUNCH signal.
13952        mHandler.post(new Runnable() {
13953            @Override
13954            public void run() {
13955                for (int i = 0; i < mRunningInstalls.size(); i++) {
13956                    final PostInstallData data = mRunningInstalls.valueAt(i);
13957                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13958                        continue;
13959                    }
13960                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
13961                        // right package; but is it for the right user?
13962                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
13963                            if (userId == data.res.newUsers[uIndex]) {
13964                                if (DEBUG_BACKUP) {
13965                                    Slog.i(TAG, "Package " + pkgName
13966                                            + " being restored so deferring FIRST_LAUNCH");
13967                                }
13968                                return;
13969                            }
13970                        }
13971                    }
13972                }
13973                // didn't find it, so not being restored
13974                if (DEBUG_BACKUP) {
13975                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
13976                }
13977                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
13978            }
13979        });
13980    }
13981
13982    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
13983        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
13984                installerPkg, null, userIds);
13985    }
13986
13987    private abstract class HandlerParams {
13988        private static final int MAX_RETRIES = 4;
13989
13990        /**
13991         * Number of times startCopy() has been attempted and had a non-fatal
13992         * error.
13993         */
13994        private int mRetries = 0;
13995
13996        /** User handle for the user requesting the information or installation. */
13997        private final UserHandle mUser;
13998        String traceMethod;
13999        int traceCookie;
14000
14001        HandlerParams(UserHandle user) {
14002            mUser = user;
14003        }
14004
14005        UserHandle getUser() {
14006            return mUser;
14007        }
14008
14009        HandlerParams setTraceMethod(String traceMethod) {
14010            this.traceMethod = traceMethod;
14011            return this;
14012        }
14013
14014        HandlerParams setTraceCookie(int traceCookie) {
14015            this.traceCookie = traceCookie;
14016            return this;
14017        }
14018
14019        final boolean startCopy() {
14020            boolean res;
14021            try {
14022                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14023
14024                if (++mRetries > MAX_RETRIES) {
14025                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14026                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14027                    handleServiceError();
14028                    return false;
14029                } else {
14030                    handleStartCopy();
14031                    res = true;
14032                }
14033            } catch (RemoteException e) {
14034                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14035                mHandler.sendEmptyMessage(MCS_RECONNECT);
14036                res = false;
14037            }
14038            handleReturnCode();
14039            return res;
14040        }
14041
14042        final void serviceError() {
14043            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14044            handleServiceError();
14045            handleReturnCode();
14046        }
14047
14048        abstract void handleStartCopy() throws RemoteException;
14049        abstract void handleServiceError();
14050        abstract void handleReturnCode();
14051    }
14052
14053    class MeasureParams extends HandlerParams {
14054        private final PackageStats mStats;
14055        private boolean mSuccess;
14056
14057        private final IPackageStatsObserver mObserver;
14058
14059        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
14060            super(new UserHandle(stats.userHandle));
14061            mObserver = observer;
14062            mStats = stats;
14063        }
14064
14065        @Override
14066        public String toString() {
14067            return "MeasureParams{"
14068                + Integer.toHexString(System.identityHashCode(this))
14069                + " " + mStats.packageName + "}";
14070        }
14071
14072        @Override
14073        void handleStartCopy() throws RemoteException {
14074            synchronized (mInstallLock) {
14075                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
14076            }
14077
14078            if (mSuccess) {
14079                boolean mounted = false;
14080                try {
14081                    final String status = Environment.getExternalStorageState();
14082                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
14083                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
14084                } catch (Exception e) {
14085                }
14086
14087                if (mounted) {
14088                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
14089
14090                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
14091                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
14092
14093                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
14094                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
14095
14096                    // Always subtract cache size, since it's a subdirectory
14097                    mStats.externalDataSize -= mStats.externalCacheSize;
14098
14099                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
14100                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
14101
14102                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
14103                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
14104                }
14105            }
14106        }
14107
14108        @Override
14109        void handleReturnCode() {
14110            if (mObserver != null) {
14111                try {
14112                    mObserver.onGetStatsCompleted(mStats, mSuccess);
14113                } catch (RemoteException e) {
14114                    Slog.i(TAG, "Observer no longer exists.");
14115                }
14116            }
14117        }
14118
14119        @Override
14120        void handleServiceError() {
14121            Slog.e(TAG, "Could not measure application " + mStats.packageName
14122                            + " external storage");
14123        }
14124    }
14125
14126    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
14127            throws RemoteException {
14128        long result = 0;
14129        for (File path : paths) {
14130            result += mcs.calculateDirectorySize(path.getAbsolutePath());
14131        }
14132        return result;
14133    }
14134
14135    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14136        for (File path : paths) {
14137            try {
14138                mcs.clearDirectory(path.getAbsolutePath());
14139            } catch (RemoteException e) {
14140            }
14141        }
14142    }
14143
14144    static class OriginInfo {
14145        /**
14146         * Location where install is coming from, before it has been
14147         * copied/renamed into place. This could be a single monolithic APK
14148         * file, or a cluster directory. This location may be untrusted.
14149         */
14150        final File file;
14151        final String cid;
14152
14153        /**
14154         * Flag indicating that {@link #file} or {@link #cid} has already been
14155         * staged, meaning downstream users don't need to defensively copy the
14156         * contents.
14157         */
14158        final boolean staged;
14159
14160        /**
14161         * Flag indicating that {@link #file} or {@link #cid} is an already
14162         * installed app that is being moved.
14163         */
14164        final boolean existing;
14165
14166        final String resolvedPath;
14167        final File resolvedFile;
14168
14169        static OriginInfo fromNothing() {
14170            return new OriginInfo(null, null, false, false);
14171        }
14172
14173        static OriginInfo fromUntrustedFile(File file) {
14174            return new OriginInfo(file, null, false, false);
14175        }
14176
14177        static OriginInfo fromExistingFile(File file) {
14178            return new OriginInfo(file, null, false, true);
14179        }
14180
14181        static OriginInfo fromStagedFile(File file) {
14182            return new OriginInfo(file, null, true, false);
14183        }
14184
14185        static OriginInfo fromStagedContainer(String cid) {
14186            return new OriginInfo(null, cid, true, false);
14187        }
14188
14189        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14190            this.file = file;
14191            this.cid = cid;
14192            this.staged = staged;
14193            this.existing = existing;
14194
14195            if (cid != null) {
14196                resolvedPath = PackageHelper.getSdDir(cid);
14197                resolvedFile = new File(resolvedPath);
14198            } else if (file != null) {
14199                resolvedPath = file.getAbsolutePath();
14200                resolvedFile = file;
14201            } else {
14202                resolvedPath = null;
14203                resolvedFile = null;
14204            }
14205        }
14206    }
14207
14208    static class MoveInfo {
14209        final int moveId;
14210        final String fromUuid;
14211        final String toUuid;
14212        final String packageName;
14213        final String dataAppName;
14214        final int appId;
14215        final String seinfo;
14216        final int targetSdkVersion;
14217
14218        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14219                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14220            this.moveId = moveId;
14221            this.fromUuid = fromUuid;
14222            this.toUuid = toUuid;
14223            this.packageName = packageName;
14224            this.dataAppName = dataAppName;
14225            this.appId = appId;
14226            this.seinfo = seinfo;
14227            this.targetSdkVersion = targetSdkVersion;
14228        }
14229    }
14230
14231    static class VerificationInfo {
14232        /** A constant used to indicate that a uid value is not present. */
14233        public static final int NO_UID = -1;
14234
14235        /** URI referencing where the package was downloaded from. */
14236        final Uri originatingUri;
14237
14238        /** HTTP referrer URI associated with the originatingURI. */
14239        final Uri referrer;
14240
14241        /** UID of the application that the install request originated from. */
14242        final int originatingUid;
14243
14244        /** UID of application requesting the install */
14245        final int installerUid;
14246
14247        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14248            this.originatingUri = originatingUri;
14249            this.referrer = referrer;
14250            this.originatingUid = originatingUid;
14251            this.installerUid = installerUid;
14252        }
14253    }
14254
14255    class InstallParams extends HandlerParams {
14256        final OriginInfo origin;
14257        final MoveInfo move;
14258        final IPackageInstallObserver2 observer;
14259        int installFlags;
14260        final String installerPackageName;
14261        final String volumeUuid;
14262        private InstallArgs mArgs;
14263        private int mRet;
14264        final String packageAbiOverride;
14265        final String[] grantedRuntimePermissions;
14266        final VerificationInfo verificationInfo;
14267        final Certificate[][] certificates;
14268        final int installReason;
14269
14270        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14271                int installFlags, String installerPackageName, String volumeUuid,
14272                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14273                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14274            super(user);
14275            this.origin = origin;
14276            this.move = move;
14277            this.observer = observer;
14278            this.installFlags = installFlags;
14279            this.installerPackageName = installerPackageName;
14280            this.volumeUuid = volumeUuid;
14281            this.verificationInfo = verificationInfo;
14282            this.packageAbiOverride = packageAbiOverride;
14283            this.grantedRuntimePermissions = grantedPermissions;
14284            this.certificates = certificates;
14285            this.installReason = installReason;
14286        }
14287
14288        @Override
14289        public String toString() {
14290            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14291                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14292        }
14293
14294        private int installLocationPolicy(PackageInfoLite pkgLite) {
14295            String packageName = pkgLite.packageName;
14296            int installLocation = pkgLite.installLocation;
14297            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14298            // reader
14299            synchronized (mPackages) {
14300                // Currently installed package which the new package is attempting to replace or
14301                // null if no such package is installed.
14302                PackageParser.Package installedPkg = mPackages.get(packageName);
14303                // Package which currently owns the data which the new package will own if installed.
14304                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14305                // will be null whereas dataOwnerPkg will contain information about the package
14306                // which was uninstalled while keeping its data.
14307                PackageParser.Package dataOwnerPkg = installedPkg;
14308                if (dataOwnerPkg  == null) {
14309                    PackageSetting ps = mSettings.mPackages.get(packageName);
14310                    if (ps != null) {
14311                        dataOwnerPkg = ps.pkg;
14312                    }
14313                }
14314
14315                if (dataOwnerPkg != null) {
14316                    // If installed, the package will get access to data left on the device by its
14317                    // predecessor. As a security measure, this is permited only if this is not a
14318                    // version downgrade or if the predecessor package is marked as debuggable and
14319                    // a downgrade is explicitly requested.
14320                    //
14321                    // On debuggable platform builds, downgrades are permitted even for
14322                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14323                    // not offer security guarantees and thus it's OK to disable some security
14324                    // mechanisms to make debugging/testing easier on those builds. However, even on
14325                    // debuggable builds downgrades of packages are permitted only if requested via
14326                    // installFlags. This is because we aim to keep the behavior of debuggable
14327                    // platform builds as close as possible to the behavior of non-debuggable
14328                    // platform builds.
14329                    final boolean downgradeRequested =
14330                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14331                    final boolean packageDebuggable =
14332                                (dataOwnerPkg.applicationInfo.flags
14333                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14334                    final boolean downgradePermitted =
14335                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14336                    if (!downgradePermitted) {
14337                        try {
14338                            checkDowngrade(dataOwnerPkg, pkgLite);
14339                        } catch (PackageManagerException e) {
14340                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14341                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14342                        }
14343                    }
14344                }
14345
14346                if (installedPkg != null) {
14347                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14348                        // Check for updated system application.
14349                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14350                            if (onSd) {
14351                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14352                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14353                            }
14354                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14355                        } else {
14356                            if (onSd) {
14357                                // Install flag overrides everything.
14358                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14359                            }
14360                            // If current upgrade specifies particular preference
14361                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14362                                // Application explicitly specified internal.
14363                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14364                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14365                                // App explictly prefers external. Let policy decide
14366                            } else {
14367                                // Prefer previous location
14368                                if (isExternal(installedPkg)) {
14369                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14370                                }
14371                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14372                            }
14373                        }
14374                    } else {
14375                        // Invalid install. Return error code
14376                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14377                    }
14378                }
14379            }
14380            // All the special cases have been taken care of.
14381            // Return result based on recommended install location.
14382            if (onSd) {
14383                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14384            }
14385            return pkgLite.recommendedInstallLocation;
14386        }
14387
14388        /*
14389         * Invoke remote method to get package information and install
14390         * location values. Override install location based on default
14391         * policy if needed and then create install arguments based
14392         * on the install location.
14393         */
14394        public void handleStartCopy() throws RemoteException {
14395            int ret = PackageManager.INSTALL_SUCCEEDED;
14396
14397            // If we're already staged, we've firmly committed to an install location
14398            if (origin.staged) {
14399                if (origin.file != null) {
14400                    installFlags |= PackageManager.INSTALL_INTERNAL;
14401                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14402                } else if (origin.cid != null) {
14403                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14404                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14405                } else {
14406                    throw new IllegalStateException("Invalid stage location");
14407                }
14408            }
14409
14410            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14411            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14412            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14413            PackageInfoLite pkgLite = null;
14414
14415            if (onInt && onSd) {
14416                // Check if both bits are set.
14417                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14418                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14419            } else if (onSd && ephemeral) {
14420                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14421                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14422            } else {
14423                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14424                        packageAbiOverride);
14425
14426                if (DEBUG_EPHEMERAL && ephemeral) {
14427                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14428                }
14429
14430                /*
14431                 * If we have too little free space, try to free cache
14432                 * before giving up.
14433                 */
14434                if (!origin.staged && pkgLite.recommendedInstallLocation
14435                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14436                    // TODO: focus freeing disk space on the target device
14437                    final StorageManager storage = StorageManager.from(mContext);
14438                    final long lowThreshold = storage.getStorageLowBytes(
14439                            Environment.getDataDirectory());
14440
14441                    final long sizeBytes = mContainerService.calculateInstalledSize(
14442                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14443
14444                    try {
14445                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14446                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14447                                installFlags, packageAbiOverride);
14448                    } catch (InstallerException e) {
14449                        Slog.w(TAG, "Failed to free cache", e);
14450                    }
14451
14452                    /*
14453                     * The cache free must have deleted the file we
14454                     * downloaded to install.
14455                     *
14456                     * TODO: fix the "freeCache" call to not delete
14457                     *       the file we care about.
14458                     */
14459                    if (pkgLite.recommendedInstallLocation
14460                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14461                        pkgLite.recommendedInstallLocation
14462                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14463                    }
14464                }
14465            }
14466
14467            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14468                int loc = pkgLite.recommendedInstallLocation;
14469                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14470                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14471                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14472                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14473                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14474                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14475                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14476                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14477                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14478                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14479                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14480                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14481                } else {
14482                    // Override with defaults if needed.
14483                    loc = installLocationPolicy(pkgLite);
14484                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14485                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14486                    } else if (!onSd && !onInt) {
14487                        // Override install location with flags
14488                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14489                            // Set the flag to install on external media.
14490                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14491                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14492                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14493                            if (DEBUG_EPHEMERAL) {
14494                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14495                            }
14496                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
14497                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14498                                    |PackageManager.INSTALL_INTERNAL);
14499                        } else {
14500                            // Make sure the flag for installing on external
14501                            // media is unset
14502                            installFlags |= PackageManager.INSTALL_INTERNAL;
14503                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14504                        }
14505                    }
14506                }
14507            }
14508
14509            final InstallArgs args = createInstallArgs(this);
14510            mArgs = args;
14511
14512            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14513                // TODO: http://b/22976637
14514                // Apps installed for "all" users use the device owner to verify the app
14515                UserHandle verifierUser = getUser();
14516                if (verifierUser == UserHandle.ALL) {
14517                    verifierUser = UserHandle.SYSTEM;
14518                }
14519
14520                /*
14521                 * Determine if we have any installed package verifiers. If we
14522                 * do, then we'll defer to them to verify the packages.
14523                 */
14524                final int requiredUid = mRequiredVerifierPackage == null ? -1
14525                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14526                                verifierUser.getIdentifier());
14527                if (!origin.existing && requiredUid != -1
14528                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
14529                    final Intent verification = new Intent(
14530                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14531                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14532                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14533                            PACKAGE_MIME_TYPE);
14534                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14535
14536                    // Query all live verifiers based on current user state
14537                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14538                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
14539
14540                    if (DEBUG_VERIFY) {
14541                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14542                                + verification.toString() + " with " + pkgLite.verifiers.length
14543                                + " optional verifiers");
14544                    }
14545
14546                    final int verificationId = mPendingVerificationToken++;
14547
14548                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14549
14550                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14551                            installerPackageName);
14552
14553                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14554                            installFlags);
14555
14556                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14557                            pkgLite.packageName);
14558
14559                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14560                            pkgLite.versionCode);
14561
14562                    if (verificationInfo != null) {
14563                        if (verificationInfo.originatingUri != null) {
14564                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14565                                    verificationInfo.originatingUri);
14566                        }
14567                        if (verificationInfo.referrer != null) {
14568                            verification.putExtra(Intent.EXTRA_REFERRER,
14569                                    verificationInfo.referrer);
14570                        }
14571                        if (verificationInfo.originatingUid >= 0) {
14572                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14573                                    verificationInfo.originatingUid);
14574                        }
14575                        if (verificationInfo.installerUid >= 0) {
14576                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14577                                    verificationInfo.installerUid);
14578                        }
14579                    }
14580
14581                    final PackageVerificationState verificationState = new PackageVerificationState(
14582                            requiredUid, args);
14583
14584                    mPendingVerification.append(verificationId, verificationState);
14585
14586                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14587                            receivers, verificationState);
14588
14589                    /*
14590                     * If any sufficient verifiers were listed in the package
14591                     * manifest, attempt to ask them.
14592                     */
14593                    if (sufficientVerifiers != null) {
14594                        final int N = sufficientVerifiers.size();
14595                        if (N == 0) {
14596                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14597                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14598                        } else {
14599                            for (int i = 0; i < N; i++) {
14600                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14601
14602                                final Intent sufficientIntent = new Intent(verification);
14603                                sufficientIntent.setComponent(verifierComponent);
14604                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14605                            }
14606                        }
14607                    }
14608
14609                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14610                            mRequiredVerifierPackage, receivers);
14611                    if (ret == PackageManager.INSTALL_SUCCEEDED
14612                            && mRequiredVerifierPackage != null) {
14613                        Trace.asyncTraceBegin(
14614                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14615                        /*
14616                         * Send the intent to the required verification agent,
14617                         * but only start the verification timeout after the
14618                         * target BroadcastReceivers have run.
14619                         */
14620                        verification.setComponent(requiredVerifierComponent);
14621                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14622                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14623                                new BroadcastReceiver() {
14624                                    @Override
14625                                    public void onReceive(Context context, Intent intent) {
14626                                        final Message msg = mHandler
14627                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14628                                        msg.arg1 = verificationId;
14629                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14630                                    }
14631                                }, null, 0, null, null);
14632
14633                        /*
14634                         * We don't want the copy to proceed until verification
14635                         * succeeds, so null out this field.
14636                         */
14637                        mArgs = null;
14638                    }
14639                } else {
14640                    /*
14641                     * No package verification is enabled, so immediately start
14642                     * the remote call to initiate copy using temporary file.
14643                     */
14644                    ret = args.copyApk(mContainerService, true);
14645                }
14646            }
14647
14648            mRet = ret;
14649        }
14650
14651        @Override
14652        void handleReturnCode() {
14653            // If mArgs is null, then MCS couldn't be reached. When it
14654            // reconnects, it will try again to install. At that point, this
14655            // will succeed.
14656            if (mArgs != null) {
14657                processPendingInstall(mArgs, mRet);
14658            }
14659        }
14660
14661        @Override
14662        void handleServiceError() {
14663            mArgs = createInstallArgs(this);
14664            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14665        }
14666
14667        public boolean isForwardLocked() {
14668            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14669        }
14670    }
14671
14672    /**
14673     * Used during creation of InstallArgs
14674     *
14675     * @param installFlags package installation flags
14676     * @return true if should be installed on external storage
14677     */
14678    private static boolean installOnExternalAsec(int installFlags) {
14679        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
14680            return false;
14681        }
14682        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14683            return true;
14684        }
14685        return false;
14686    }
14687
14688    /**
14689     * Used during creation of InstallArgs
14690     *
14691     * @param installFlags package installation flags
14692     * @return true if should be installed as forward locked
14693     */
14694    private static boolean installForwardLocked(int installFlags) {
14695        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14696    }
14697
14698    private InstallArgs createInstallArgs(InstallParams params) {
14699        if (params.move != null) {
14700            return new MoveInstallArgs(params);
14701        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
14702            return new AsecInstallArgs(params);
14703        } else {
14704            return new FileInstallArgs(params);
14705        }
14706    }
14707
14708    /**
14709     * Create args that describe an existing installed package. Typically used
14710     * when cleaning up old installs, or used as a move source.
14711     */
14712    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14713            String resourcePath, String[] instructionSets) {
14714        final boolean isInAsec;
14715        if (installOnExternalAsec(installFlags)) {
14716            /* Apps on SD card are always in ASEC containers. */
14717            isInAsec = true;
14718        } else if (installForwardLocked(installFlags)
14719                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
14720            /*
14721             * Forward-locked apps are only in ASEC containers if they're the
14722             * new style
14723             */
14724            isInAsec = true;
14725        } else {
14726            isInAsec = false;
14727        }
14728
14729        if (isInAsec) {
14730            return new AsecInstallArgs(codePath, instructionSets,
14731                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
14732        } else {
14733            return new FileInstallArgs(codePath, resourcePath, instructionSets);
14734        }
14735    }
14736
14737    static abstract class InstallArgs {
14738        /** @see InstallParams#origin */
14739        final OriginInfo origin;
14740        /** @see InstallParams#move */
14741        final MoveInfo move;
14742
14743        final IPackageInstallObserver2 observer;
14744        // Always refers to PackageManager flags only
14745        final int installFlags;
14746        final String installerPackageName;
14747        final String volumeUuid;
14748        final UserHandle user;
14749        final String abiOverride;
14750        final String[] installGrantPermissions;
14751        /** If non-null, drop an async trace when the install completes */
14752        final String traceMethod;
14753        final int traceCookie;
14754        final Certificate[][] certificates;
14755        final int installReason;
14756
14757        // The list of instruction sets supported by this app. This is currently
14758        // only used during the rmdex() phase to clean up resources. We can get rid of this
14759        // if we move dex files under the common app path.
14760        /* nullable */ String[] instructionSets;
14761
14762        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14763                int installFlags, String installerPackageName, String volumeUuid,
14764                UserHandle user, String[] instructionSets,
14765                String abiOverride, String[] installGrantPermissions,
14766                String traceMethod, int traceCookie, Certificate[][] certificates,
14767                int installReason) {
14768            this.origin = origin;
14769            this.move = move;
14770            this.installFlags = installFlags;
14771            this.observer = observer;
14772            this.installerPackageName = installerPackageName;
14773            this.volumeUuid = volumeUuid;
14774            this.user = user;
14775            this.instructionSets = instructionSets;
14776            this.abiOverride = abiOverride;
14777            this.installGrantPermissions = installGrantPermissions;
14778            this.traceMethod = traceMethod;
14779            this.traceCookie = traceCookie;
14780            this.certificates = certificates;
14781            this.installReason = installReason;
14782        }
14783
14784        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14785        abstract int doPreInstall(int status);
14786
14787        /**
14788         * Rename package into final resting place. All paths on the given
14789         * scanned package should be updated to reflect the rename.
14790         */
14791        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14792        abstract int doPostInstall(int status, int uid);
14793
14794        /** @see PackageSettingBase#codePathString */
14795        abstract String getCodePath();
14796        /** @see PackageSettingBase#resourcePathString */
14797        abstract String getResourcePath();
14798
14799        // Need installer lock especially for dex file removal.
14800        abstract void cleanUpResourcesLI();
14801        abstract boolean doPostDeleteLI(boolean delete);
14802
14803        /**
14804         * Called before the source arguments are copied. This is used mostly
14805         * for MoveParams when it needs to read the source file to put it in the
14806         * destination.
14807         */
14808        int doPreCopy() {
14809            return PackageManager.INSTALL_SUCCEEDED;
14810        }
14811
14812        /**
14813         * Called after the source arguments are copied. This is used mostly for
14814         * MoveParams when it needs to read the source file to put it in the
14815         * destination.
14816         */
14817        int doPostCopy(int uid) {
14818            return PackageManager.INSTALL_SUCCEEDED;
14819        }
14820
14821        protected boolean isFwdLocked() {
14822            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14823        }
14824
14825        protected boolean isExternalAsec() {
14826            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14827        }
14828
14829        protected boolean isEphemeral() {
14830            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14831        }
14832
14833        UserHandle getUser() {
14834            return user;
14835        }
14836    }
14837
14838    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14839        if (!allCodePaths.isEmpty()) {
14840            if (instructionSets == null) {
14841                throw new IllegalStateException("instructionSet == null");
14842            }
14843            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14844            for (String codePath : allCodePaths) {
14845                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14846                    try {
14847                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14848                    } catch (InstallerException ignored) {
14849                    }
14850                }
14851            }
14852        }
14853    }
14854
14855    /**
14856     * Logic to handle installation of non-ASEC applications, including copying
14857     * and renaming logic.
14858     */
14859    class FileInstallArgs extends InstallArgs {
14860        private File codeFile;
14861        private File resourceFile;
14862
14863        // Example topology:
14864        // /data/app/com.example/base.apk
14865        // /data/app/com.example/split_foo.apk
14866        // /data/app/com.example/lib/arm/libfoo.so
14867        // /data/app/com.example/lib/arm64/libfoo.so
14868        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
14869
14870        /** New install */
14871        FileInstallArgs(InstallParams params) {
14872            super(params.origin, params.move, params.observer, params.installFlags,
14873                    params.installerPackageName, params.volumeUuid,
14874                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
14875                    params.grantedRuntimePermissions,
14876                    params.traceMethod, params.traceCookie, params.certificates,
14877                    params.installReason);
14878            if (isFwdLocked()) {
14879                throw new IllegalArgumentException("Forward locking only supported in ASEC");
14880            }
14881        }
14882
14883        /** Existing install */
14884        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
14885            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
14886                    null, null, null, 0, null /*certificates*/,
14887                    PackageManager.INSTALL_REASON_UNKNOWN);
14888            this.codeFile = (codePath != null) ? new File(codePath) : null;
14889            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
14890        }
14891
14892        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14893            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
14894            try {
14895                return doCopyApk(imcs, temp);
14896            } finally {
14897                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14898            }
14899        }
14900
14901        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14902            if (origin.staged) {
14903                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
14904                codeFile = origin.file;
14905                resourceFile = origin.file;
14906                return PackageManager.INSTALL_SUCCEEDED;
14907            }
14908
14909            try {
14910                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14911                final File tempDir =
14912                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
14913                codeFile = tempDir;
14914                resourceFile = tempDir;
14915            } catch (IOException e) {
14916                Slog.w(TAG, "Failed to create copy file: " + e);
14917                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14918            }
14919
14920            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
14921                @Override
14922                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
14923                    if (!FileUtils.isValidExtFilename(name)) {
14924                        throw new IllegalArgumentException("Invalid filename: " + name);
14925                    }
14926                    try {
14927                        final File file = new File(codeFile, name);
14928                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
14929                                O_RDWR | O_CREAT, 0644);
14930                        Os.chmod(file.getAbsolutePath(), 0644);
14931                        return new ParcelFileDescriptor(fd);
14932                    } catch (ErrnoException e) {
14933                        throw new RemoteException("Failed to open: " + e.getMessage());
14934                    }
14935                }
14936            };
14937
14938            int ret = PackageManager.INSTALL_SUCCEEDED;
14939            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
14940            if (ret != PackageManager.INSTALL_SUCCEEDED) {
14941                Slog.e(TAG, "Failed to copy package");
14942                return ret;
14943            }
14944
14945            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
14946            NativeLibraryHelper.Handle handle = null;
14947            try {
14948                handle = NativeLibraryHelper.Handle.create(codeFile);
14949                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
14950                        abiOverride);
14951            } catch (IOException e) {
14952                Slog.e(TAG, "Copying native libraries failed", e);
14953                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14954            } finally {
14955                IoUtils.closeQuietly(handle);
14956            }
14957
14958            return ret;
14959        }
14960
14961        int doPreInstall(int status) {
14962            if (status != PackageManager.INSTALL_SUCCEEDED) {
14963                cleanUp();
14964            }
14965            return status;
14966        }
14967
14968        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14969            if (status != PackageManager.INSTALL_SUCCEEDED) {
14970                cleanUp();
14971                return false;
14972            }
14973
14974            final File targetDir = codeFile.getParentFile();
14975            final File beforeCodeFile = codeFile;
14976            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
14977
14978            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
14979            try {
14980                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
14981            } catch (ErrnoException e) {
14982                Slog.w(TAG, "Failed to rename", e);
14983                return false;
14984            }
14985
14986            if (!SELinux.restoreconRecursive(afterCodeFile)) {
14987                Slog.w(TAG, "Failed to restorecon");
14988                return false;
14989            }
14990
14991            // Reflect the rename internally
14992            codeFile = afterCodeFile;
14993            resourceFile = afterCodeFile;
14994
14995            // Reflect the rename in scanned details
14996            pkg.setCodePath(afterCodeFile.getAbsolutePath());
14997            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
14998                    afterCodeFile, pkg.baseCodePath));
14999            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15000                    afterCodeFile, pkg.splitCodePaths));
15001
15002            // Reflect the rename in app info
15003            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15004            pkg.setApplicationInfoCodePath(pkg.codePath);
15005            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15006            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15007            pkg.setApplicationInfoResourcePath(pkg.codePath);
15008            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15009            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15010
15011            return true;
15012        }
15013
15014        int doPostInstall(int status, int uid) {
15015            if (status != PackageManager.INSTALL_SUCCEEDED) {
15016                cleanUp();
15017            }
15018            return status;
15019        }
15020
15021        @Override
15022        String getCodePath() {
15023            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15024        }
15025
15026        @Override
15027        String getResourcePath() {
15028            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15029        }
15030
15031        private boolean cleanUp() {
15032            if (codeFile == null || !codeFile.exists()) {
15033                return false;
15034            }
15035
15036            removeCodePathLI(codeFile);
15037
15038            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15039                resourceFile.delete();
15040            }
15041
15042            return true;
15043        }
15044
15045        void cleanUpResourcesLI() {
15046            // Try enumerating all code paths before deleting
15047            List<String> allCodePaths = Collections.EMPTY_LIST;
15048            if (codeFile != null && codeFile.exists()) {
15049                try {
15050                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15051                    allCodePaths = pkg.getAllCodePaths();
15052                } catch (PackageParserException e) {
15053                    // Ignored; we tried our best
15054                }
15055            }
15056
15057            cleanUp();
15058            removeDexFiles(allCodePaths, instructionSets);
15059        }
15060
15061        boolean doPostDeleteLI(boolean delete) {
15062            // XXX err, shouldn't we respect the delete flag?
15063            cleanUpResourcesLI();
15064            return true;
15065        }
15066    }
15067
15068    private boolean isAsecExternal(String cid) {
15069        final String asecPath = PackageHelper.getSdFilesystem(cid);
15070        return !asecPath.startsWith(mAsecInternalPath);
15071    }
15072
15073    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15074            PackageManagerException {
15075        if (copyRet < 0) {
15076            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15077                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15078                throw new PackageManagerException(copyRet, message);
15079            }
15080        }
15081    }
15082
15083    /**
15084     * Extract the StorageManagerService "container ID" from the full code path of an
15085     * .apk.
15086     */
15087    static String cidFromCodePath(String fullCodePath) {
15088        int eidx = fullCodePath.lastIndexOf("/");
15089        String subStr1 = fullCodePath.substring(0, eidx);
15090        int sidx = subStr1.lastIndexOf("/");
15091        return subStr1.substring(sidx+1, eidx);
15092    }
15093
15094    /**
15095     * Logic to handle installation of ASEC applications, including copying and
15096     * renaming logic.
15097     */
15098    class AsecInstallArgs extends InstallArgs {
15099        static final String RES_FILE_NAME = "pkg.apk";
15100        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15101
15102        String cid;
15103        String packagePath;
15104        String resourcePath;
15105
15106        /** New install */
15107        AsecInstallArgs(InstallParams params) {
15108            super(params.origin, params.move, params.observer, params.installFlags,
15109                    params.installerPackageName, params.volumeUuid,
15110                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15111                    params.grantedRuntimePermissions,
15112                    params.traceMethod, params.traceCookie, params.certificates,
15113                    params.installReason);
15114        }
15115
15116        /** Existing install */
15117        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15118                        boolean isExternal, boolean isForwardLocked) {
15119            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15120                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15121                    instructionSets, null, null, null, 0, null /*certificates*/,
15122                    PackageManager.INSTALL_REASON_UNKNOWN);
15123            // Hackily pretend we're still looking at a full code path
15124            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15125                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15126            }
15127
15128            // Extract cid from fullCodePath
15129            int eidx = fullCodePath.lastIndexOf("/");
15130            String subStr1 = fullCodePath.substring(0, eidx);
15131            int sidx = subStr1.lastIndexOf("/");
15132            cid = subStr1.substring(sidx+1, eidx);
15133            setMountPath(subStr1);
15134        }
15135
15136        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15137            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15138                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15139                    instructionSets, null, null, null, 0, null /*certificates*/,
15140                    PackageManager.INSTALL_REASON_UNKNOWN);
15141            this.cid = cid;
15142            setMountPath(PackageHelper.getSdDir(cid));
15143        }
15144
15145        void createCopyFile() {
15146            cid = mInstallerService.allocateExternalStageCidLegacy();
15147        }
15148
15149        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15150            if (origin.staged && origin.cid != null) {
15151                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15152                cid = origin.cid;
15153                setMountPath(PackageHelper.getSdDir(cid));
15154                return PackageManager.INSTALL_SUCCEEDED;
15155            }
15156
15157            if (temp) {
15158                createCopyFile();
15159            } else {
15160                /*
15161                 * Pre-emptively destroy the container since it's destroyed if
15162                 * copying fails due to it existing anyway.
15163                 */
15164                PackageHelper.destroySdDir(cid);
15165            }
15166
15167            final String newMountPath = imcs.copyPackageToContainer(
15168                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15169                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15170
15171            if (newMountPath != null) {
15172                setMountPath(newMountPath);
15173                return PackageManager.INSTALL_SUCCEEDED;
15174            } else {
15175                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15176            }
15177        }
15178
15179        @Override
15180        String getCodePath() {
15181            return packagePath;
15182        }
15183
15184        @Override
15185        String getResourcePath() {
15186            return resourcePath;
15187        }
15188
15189        int doPreInstall(int status) {
15190            if (status != PackageManager.INSTALL_SUCCEEDED) {
15191                // Destroy container
15192                PackageHelper.destroySdDir(cid);
15193            } else {
15194                boolean mounted = PackageHelper.isContainerMounted(cid);
15195                if (!mounted) {
15196                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15197                            Process.SYSTEM_UID);
15198                    if (newMountPath != null) {
15199                        setMountPath(newMountPath);
15200                    } else {
15201                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15202                    }
15203                }
15204            }
15205            return status;
15206        }
15207
15208        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15209            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15210            String newMountPath = null;
15211            if (PackageHelper.isContainerMounted(cid)) {
15212                // Unmount the container
15213                if (!PackageHelper.unMountSdDir(cid)) {
15214                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15215                    return false;
15216                }
15217            }
15218            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15219                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15220                        " which might be stale. Will try to clean up.");
15221                // Clean up the stale container and proceed to recreate.
15222                if (!PackageHelper.destroySdDir(newCacheId)) {
15223                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15224                    return false;
15225                }
15226                // Successfully cleaned up stale container. Try to rename again.
15227                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15228                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15229                            + " inspite of cleaning it up.");
15230                    return false;
15231                }
15232            }
15233            if (!PackageHelper.isContainerMounted(newCacheId)) {
15234                Slog.w(TAG, "Mounting container " + newCacheId);
15235                newMountPath = PackageHelper.mountSdDir(newCacheId,
15236                        getEncryptKey(), Process.SYSTEM_UID);
15237            } else {
15238                newMountPath = PackageHelper.getSdDir(newCacheId);
15239            }
15240            if (newMountPath == null) {
15241                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15242                return false;
15243            }
15244            Log.i(TAG, "Succesfully renamed " + cid +
15245                    " to " + newCacheId +
15246                    " at new path: " + newMountPath);
15247            cid = newCacheId;
15248
15249            final File beforeCodeFile = new File(packagePath);
15250            setMountPath(newMountPath);
15251            final File afterCodeFile = new File(packagePath);
15252
15253            // Reflect the rename in scanned details
15254            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15255            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15256                    afterCodeFile, pkg.baseCodePath));
15257            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15258                    afterCodeFile, pkg.splitCodePaths));
15259
15260            // Reflect the rename in app info
15261            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15262            pkg.setApplicationInfoCodePath(pkg.codePath);
15263            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15264            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15265            pkg.setApplicationInfoResourcePath(pkg.codePath);
15266            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15267            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15268
15269            return true;
15270        }
15271
15272        private void setMountPath(String mountPath) {
15273            final File mountFile = new File(mountPath);
15274
15275            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15276            if (monolithicFile.exists()) {
15277                packagePath = monolithicFile.getAbsolutePath();
15278                if (isFwdLocked()) {
15279                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15280                } else {
15281                    resourcePath = packagePath;
15282                }
15283            } else {
15284                packagePath = mountFile.getAbsolutePath();
15285                resourcePath = packagePath;
15286            }
15287        }
15288
15289        int doPostInstall(int status, int uid) {
15290            if (status != PackageManager.INSTALL_SUCCEEDED) {
15291                cleanUp();
15292            } else {
15293                final int groupOwner;
15294                final String protectedFile;
15295                if (isFwdLocked()) {
15296                    groupOwner = UserHandle.getSharedAppGid(uid);
15297                    protectedFile = RES_FILE_NAME;
15298                } else {
15299                    groupOwner = -1;
15300                    protectedFile = null;
15301                }
15302
15303                if (uid < Process.FIRST_APPLICATION_UID
15304                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15305                    Slog.e(TAG, "Failed to finalize " + cid);
15306                    PackageHelper.destroySdDir(cid);
15307                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15308                }
15309
15310                boolean mounted = PackageHelper.isContainerMounted(cid);
15311                if (!mounted) {
15312                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15313                }
15314            }
15315            return status;
15316        }
15317
15318        private void cleanUp() {
15319            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15320
15321            // Destroy secure container
15322            PackageHelper.destroySdDir(cid);
15323        }
15324
15325        private List<String> getAllCodePaths() {
15326            final File codeFile = new File(getCodePath());
15327            if (codeFile != null && codeFile.exists()) {
15328                try {
15329                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15330                    return pkg.getAllCodePaths();
15331                } catch (PackageParserException e) {
15332                    // Ignored; we tried our best
15333                }
15334            }
15335            return Collections.EMPTY_LIST;
15336        }
15337
15338        void cleanUpResourcesLI() {
15339            // Enumerate all code paths before deleting
15340            cleanUpResourcesLI(getAllCodePaths());
15341        }
15342
15343        private void cleanUpResourcesLI(List<String> allCodePaths) {
15344            cleanUp();
15345            removeDexFiles(allCodePaths, instructionSets);
15346        }
15347
15348        String getPackageName() {
15349            return getAsecPackageName(cid);
15350        }
15351
15352        boolean doPostDeleteLI(boolean delete) {
15353            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15354            final List<String> allCodePaths = getAllCodePaths();
15355            boolean mounted = PackageHelper.isContainerMounted(cid);
15356            if (mounted) {
15357                // Unmount first
15358                if (PackageHelper.unMountSdDir(cid)) {
15359                    mounted = false;
15360                }
15361            }
15362            if (!mounted && delete) {
15363                cleanUpResourcesLI(allCodePaths);
15364            }
15365            return !mounted;
15366        }
15367
15368        @Override
15369        int doPreCopy() {
15370            if (isFwdLocked()) {
15371                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15372                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15373                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15374                }
15375            }
15376
15377            return PackageManager.INSTALL_SUCCEEDED;
15378        }
15379
15380        @Override
15381        int doPostCopy(int uid) {
15382            if (isFwdLocked()) {
15383                if (uid < Process.FIRST_APPLICATION_UID
15384                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15385                                RES_FILE_NAME)) {
15386                    Slog.e(TAG, "Failed to finalize " + cid);
15387                    PackageHelper.destroySdDir(cid);
15388                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15389                }
15390            }
15391
15392            return PackageManager.INSTALL_SUCCEEDED;
15393        }
15394    }
15395
15396    /**
15397     * Logic to handle movement of existing installed applications.
15398     */
15399    class MoveInstallArgs extends InstallArgs {
15400        private File codeFile;
15401        private File resourceFile;
15402
15403        /** New install */
15404        MoveInstallArgs(InstallParams params) {
15405            super(params.origin, params.move, params.observer, params.installFlags,
15406                    params.installerPackageName, params.volumeUuid,
15407                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15408                    params.grantedRuntimePermissions,
15409                    params.traceMethod, params.traceCookie, params.certificates,
15410                    params.installReason);
15411        }
15412
15413        int copyApk(IMediaContainerService imcs, boolean temp) {
15414            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15415                    + move.fromUuid + " to " + move.toUuid);
15416            synchronized (mInstaller) {
15417                try {
15418                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15419                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15420                } catch (InstallerException e) {
15421                    Slog.w(TAG, "Failed to move app", e);
15422                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15423                }
15424            }
15425
15426            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15427            resourceFile = codeFile;
15428            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15429
15430            return PackageManager.INSTALL_SUCCEEDED;
15431        }
15432
15433        int doPreInstall(int status) {
15434            if (status != PackageManager.INSTALL_SUCCEEDED) {
15435                cleanUp(move.toUuid);
15436            }
15437            return status;
15438        }
15439
15440        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15441            if (status != PackageManager.INSTALL_SUCCEEDED) {
15442                cleanUp(move.toUuid);
15443                return false;
15444            }
15445
15446            // Reflect the move in app info
15447            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15448            pkg.setApplicationInfoCodePath(pkg.codePath);
15449            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15450            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15451            pkg.setApplicationInfoResourcePath(pkg.codePath);
15452            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15453            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15454
15455            return true;
15456        }
15457
15458        int doPostInstall(int status, int uid) {
15459            if (status == PackageManager.INSTALL_SUCCEEDED) {
15460                cleanUp(move.fromUuid);
15461            } else {
15462                cleanUp(move.toUuid);
15463            }
15464            return status;
15465        }
15466
15467        @Override
15468        String getCodePath() {
15469            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15470        }
15471
15472        @Override
15473        String getResourcePath() {
15474            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15475        }
15476
15477        private boolean cleanUp(String volumeUuid) {
15478            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15479                    move.dataAppName);
15480            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15481            final int[] userIds = sUserManager.getUserIds();
15482            synchronized (mInstallLock) {
15483                // Clean up both app data and code
15484                // All package moves are frozen until finished
15485                for (int userId : userIds) {
15486                    try {
15487                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15488                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15489                    } catch (InstallerException e) {
15490                        Slog.w(TAG, String.valueOf(e));
15491                    }
15492                }
15493                removeCodePathLI(codeFile);
15494            }
15495            return true;
15496        }
15497
15498        void cleanUpResourcesLI() {
15499            throw new UnsupportedOperationException();
15500        }
15501
15502        boolean doPostDeleteLI(boolean delete) {
15503            throw new UnsupportedOperationException();
15504        }
15505    }
15506
15507    static String getAsecPackageName(String packageCid) {
15508        int idx = packageCid.lastIndexOf("-");
15509        if (idx == -1) {
15510            return packageCid;
15511        }
15512        return packageCid.substring(0, idx);
15513    }
15514
15515    // Utility method used to create code paths based on package name and available index.
15516    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15517        String idxStr = "";
15518        int idx = 1;
15519        // Fall back to default value of idx=1 if prefix is not
15520        // part of oldCodePath
15521        if (oldCodePath != null) {
15522            String subStr = oldCodePath;
15523            // Drop the suffix right away
15524            if (suffix != null && subStr.endsWith(suffix)) {
15525                subStr = subStr.substring(0, subStr.length() - suffix.length());
15526            }
15527            // If oldCodePath already contains prefix find out the
15528            // ending index to either increment or decrement.
15529            int sidx = subStr.lastIndexOf(prefix);
15530            if (sidx != -1) {
15531                subStr = subStr.substring(sidx + prefix.length());
15532                if (subStr != null) {
15533                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15534                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15535                    }
15536                    try {
15537                        idx = Integer.parseInt(subStr);
15538                        if (idx <= 1) {
15539                            idx++;
15540                        } else {
15541                            idx--;
15542                        }
15543                    } catch(NumberFormatException e) {
15544                    }
15545                }
15546            }
15547        }
15548        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15549        return prefix + idxStr;
15550    }
15551
15552    private File getNextCodePath(File targetDir, String packageName) {
15553        File result;
15554        SecureRandom random = new SecureRandom();
15555        byte[] bytes = new byte[16];
15556        do {
15557            random.nextBytes(bytes);
15558            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15559            result = new File(targetDir, packageName + "-" + suffix);
15560        } while (result.exists());
15561        return result;
15562    }
15563
15564    // Utility method that returns the relative package path with respect
15565    // to the installation directory. Like say for /data/data/com.test-1.apk
15566    // string com.test-1 is returned.
15567    static String deriveCodePathName(String codePath) {
15568        if (codePath == null) {
15569            return null;
15570        }
15571        final File codeFile = new File(codePath);
15572        final String name = codeFile.getName();
15573        if (codeFile.isDirectory()) {
15574            return name;
15575        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15576            final int lastDot = name.lastIndexOf('.');
15577            return name.substring(0, lastDot);
15578        } else {
15579            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15580            return null;
15581        }
15582    }
15583
15584    static class PackageInstalledInfo {
15585        String name;
15586        int uid;
15587        // The set of users that originally had this package installed.
15588        int[] origUsers;
15589        // The set of users that now have this package installed.
15590        int[] newUsers;
15591        PackageParser.Package pkg;
15592        int returnCode;
15593        String returnMsg;
15594        PackageRemovedInfo removedInfo;
15595        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15596
15597        public void setError(int code, String msg) {
15598            setReturnCode(code);
15599            setReturnMessage(msg);
15600            Slog.w(TAG, msg);
15601        }
15602
15603        public void setError(String msg, PackageParserException e) {
15604            setReturnCode(e.error);
15605            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15606            Slog.w(TAG, msg, e);
15607        }
15608
15609        public void setError(String msg, PackageManagerException e) {
15610            returnCode = e.error;
15611            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15612            Slog.w(TAG, msg, e);
15613        }
15614
15615        public void setReturnCode(int returnCode) {
15616            this.returnCode = returnCode;
15617            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15618            for (int i = 0; i < childCount; i++) {
15619                addedChildPackages.valueAt(i).returnCode = returnCode;
15620            }
15621        }
15622
15623        private void setReturnMessage(String returnMsg) {
15624            this.returnMsg = returnMsg;
15625            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15626            for (int i = 0; i < childCount; i++) {
15627                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15628            }
15629        }
15630
15631        // In some error cases we want to convey more info back to the observer
15632        String origPackage;
15633        String origPermission;
15634    }
15635
15636    /*
15637     * Install a non-existing package.
15638     */
15639    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15640            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15641            PackageInstalledInfo res, int installReason) {
15642        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15643
15644        // Remember this for later, in case we need to rollback this install
15645        String pkgName = pkg.packageName;
15646
15647        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15648
15649        synchronized(mPackages) {
15650            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15651            if (renamedPackage != null) {
15652                // A package with the same name is already installed, though
15653                // it has been renamed to an older name.  The package we
15654                // are trying to install should be installed as an update to
15655                // the existing one, but that has not been requested, so bail.
15656                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15657                        + " without first uninstalling package running as "
15658                        + renamedPackage);
15659                return;
15660            }
15661            if (mPackages.containsKey(pkgName)) {
15662                // Don't allow installation over an existing package with the same name.
15663                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15664                        + " without first uninstalling.");
15665                return;
15666            }
15667        }
15668
15669        try {
15670            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15671                    System.currentTimeMillis(), user);
15672
15673            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15674
15675            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15676                prepareAppDataAfterInstallLIF(newPackage);
15677
15678            } else {
15679                // Remove package from internal structures, but keep around any
15680                // data that might have already existed
15681                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15682                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15683            }
15684        } catch (PackageManagerException e) {
15685            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15686        }
15687
15688        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15689    }
15690
15691    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
15692        // Can't rotate keys during boot or if sharedUser.
15693        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
15694                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
15695            return false;
15696        }
15697        // app is using upgradeKeySets; make sure all are valid
15698        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15699        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
15700        for (int i = 0; i < upgradeKeySets.length; i++) {
15701            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
15702                Slog.wtf(TAG, "Package "
15703                         + (oldPs.name != null ? oldPs.name : "<null>")
15704                         + " contains upgrade-key-set reference to unknown key-set: "
15705                         + upgradeKeySets[i]
15706                         + " reverting to signatures check.");
15707                return false;
15708            }
15709        }
15710        return true;
15711    }
15712
15713    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
15714        // Upgrade keysets are being used.  Determine if new package has a superset of the
15715        // required keys.
15716        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
15717        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15718        for (int i = 0; i < upgradeKeySets.length; i++) {
15719            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
15720            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
15721                return true;
15722            }
15723        }
15724        return false;
15725    }
15726
15727    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15728        try (DigestInputStream digestStream =
15729                new DigestInputStream(new FileInputStream(file), digest)) {
15730            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15731        }
15732    }
15733
15734    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
15735            UserHandle user, String installerPackageName, PackageInstalledInfo res,
15736            int installReason) {
15737        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
15738
15739        final PackageParser.Package oldPackage;
15740        final String pkgName = pkg.packageName;
15741        final int[] allUsers;
15742        final int[] installedUsers;
15743
15744        synchronized(mPackages) {
15745            oldPackage = mPackages.get(pkgName);
15746            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15747
15748            // don't allow upgrade to target a release SDK from a pre-release SDK
15749            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15750                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15751            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15752                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15753            if (oldTargetsPreRelease
15754                    && !newTargetsPreRelease
15755                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15756                Slog.w(TAG, "Can't install package targeting released sdk");
15757                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15758                return;
15759            }
15760
15761            // don't allow an upgrade from full to ephemeral
15762            final boolean oldIsEphemeral = oldPackage.applicationInfo.isInstantApp();
15763            if (isEphemeral && !oldIsEphemeral) {
15764                // can't downgrade from full to ephemeral
15765                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
15766                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
15767                return;
15768            }
15769
15770            // verify signatures are valid
15771            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15772            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15773                if (!checkUpgradeKeySetLP(ps, pkg)) {
15774                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15775                            "New package not signed by keys specified by upgrade-keysets: "
15776                                    + pkgName);
15777                    return;
15778                }
15779            } else {
15780                // default to original signature matching
15781                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15782                        != PackageManager.SIGNATURE_MATCH) {
15783                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15784                            "New package has a different signature: " + pkgName);
15785                    return;
15786                }
15787            }
15788
15789            // don't allow a system upgrade unless the upgrade hash matches
15790            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
15791                byte[] digestBytes = null;
15792                try {
15793                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15794                    updateDigest(digest, new File(pkg.baseCodePath));
15795                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15796                        for (String path : pkg.splitCodePaths) {
15797                            updateDigest(digest, new File(path));
15798                        }
15799                    }
15800                    digestBytes = digest.digest();
15801                } catch (NoSuchAlgorithmException | IOException e) {
15802                    res.setError(INSTALL_FAILED_INVALID_APK,
15803                            "Could not compute hash: " + pkgName);
15804                    return;
15805                }
15806                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15807                    res.setError(INSTALL_FAILED_INVALID_APK,
15808                            "New package fails restrict-update check: " + pkgName);
15809                    return;
15810                }
15811                // retain upgrade restriction
15812                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15813            }
15814
15815            // Check for shared user id changes
15816            String invalidPackageName =
15817                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15818            if (invalidPackageName != null) {
15819                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15820                        "Package " + invalidPackageName + " tried to change user "
15821                                + oldPackage.mSharedUserId);
15822                return;
15823            }
15824
15825            // In case of rollback, remember per-user/profile install state
15826            allUsers = sUserManager.getUserIds();
15827            installedUsers = ps.queryInstalledUsers(allUsers, true);
15828        }
15829
15830        // Update what is removed
15831        res.removedInfo = new PackageRemovedInfo();
15832        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15833        res.removedInfo.removedPackage = oldPackage.packageName;
15834        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15835        res.removedInfo.isUpdate = true;
15836        res.removedInfo.origUsers = installedUsers;
15837        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
15838        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15839        for (int i = 0; i < installedUsers.length; i++) {
15840            final int userId = installedUsers[i];
15841            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15842        }
15843
15844        final int childCount = (oldPackage.childPackages != null)
15845                ? oldPackage.childPackages.size() : 0;
15846        for (int i = 0; i < childCount; i++) {
15847            boolean childPackageUpdated = false;
15848            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15849            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15850            if (res.addedChildPackages != null) {
15851                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15852                if (childRes != null) {
15853                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15854                    childRes.removedInfo.removedPackage = childPkg.packageName;
15855                    childRes.removedInfo.isUpdate = true;
15856                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15857                    childPackageUpdated = true;
15858                }
15859            }
15860            if (!childPackageUpdated) {
15861                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
15862                childRemovedRes.removedPackage = childPkg.packageName;
15863                childRemovedRes.isUpdate = false;
15864                childRemovedRes.dataRemoved = true;
15865                synchronized (mPackages) {
15866                    if (childPs != null) {
15867                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15868                    }
15869                }
15870                if (res.removedInfo.removedChildPackages == null) {
15871                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15872                }
15873                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15874            }
15875        }
15876
15877        boolean sysPkg = (isSystemApp(oldPackage));
15878        if (sysPkg) {
15879            // Set the system/privileged flags as needed
15880            final boolean privileged =
15881                    (oldPackage.applicationInfo.privateFlags
15882                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15883            final int systemPolicyFlags = policyFlags
15884                    | PackageParser.PARSE_IS_SYSTEM
15885                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
15886
15887            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
15888                    user, allUsers, installerPackageName, res, installReason);
15889        } else {
15890            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
15891                    user, allUsers, installerPackageName, res, installReason);
15892        }
15893    }
15894
15895    public List<String> getPreviousCodePaths(String packageName) {
15896        final PackageSetting ps = mSettings.mPackages.get(packageName);
15897        final List<String> result = new ArrayList<String>();
15898        if (ps != null && ps.oldCodePaths != null) {
15899            result.addAll(ps.oldCodePaths);
15900        }
15901        return result;
15902    }
15903
15904    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
15905            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15906            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15907            int installReason) {
15908        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
15909                + deletedPackage);
15910
15911        String pkgName = deletedPackage.packageName;
15912        boolean deletedPkg = true;
15913        boolean addedPkg = false;
15914        boolean updatedSettings = false;
15915        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
15916        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
15917                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
15918
15919        final long origUpdateTime = (pkg.mExtras != null)
15920                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
15921
15922        // First delete the existing package while retaining the data directory
15923        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15924                res.removedInfo, true, pkg)) {
15925            // If the existing package wasn't successfully deleted
15926            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
15927            deletedPkg = false;
15928        } else {
15929            // Successfully deleted the old package; proceed with replace.
15930
15931            // If deleted package lived in a container, give users a chance to
15932            // relinquish resources before killing.
15933            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
15934                if (DEBUG_INSTALL) {
15935                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
15936                }
15937                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
15938                final ArrayList<String> pkgList = new ArrayList<String>(1);
15939                pkgList.add(deletedPackage.applicationInfo.packageName);
15940                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
15941            }
15942
15943            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15944                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15945            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15946
15947            try {
15948                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
15949                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
15950                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15951                        installReason);
15952
15953                // Update the in-memory copy of the previous code paths.
15954                PackageSetting ps = mSettings.mPackages.get(pkgName);
15955                if (!killApp) {
15956                    if (ps.oldCodePaths == null) {
15957                        ps.oldCodePaths = new ArraySet<>();
15958                    }
15959                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
15960                    if (deletedPackage.splitCodePaths != null) {
15961                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
15962                    }
15963                } else {
15964                    ps.oldCodePaths = null;
15965                }
15966                if (ps.childPackageNames != null) {
15967                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
15968                        final String childPkgName = ps.childPackageNames.get(i);
15969                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
15970                        childPs.oldCodePaths = ps.oldCodePaths;
15971                    }
15972                }
15973                prepareAppDataAfterInstallLIF(newPackage);
15974                addedPkg = true;
15975            } catch (PackageManagerException e) {
15976                res.setError("Package couldn't be installed in " + pkg.codePath, e);
15977            }
15978        }
15979
15980        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15981            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
15982
15983            // Revert all internal state mutations and added folders for the failed install
15984            if (addedPkg) {
15985                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15986                        res.removedInfo, true, null);
15987            }
15988
15989            // Restore the old package
15990            if (deletedPkg) {
15991                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
15992                File restoreFile = new File(deletedPackage.codePath);
15993                // Parse old package
15994                boolean oldExternal = isExternal(deletedPackage);
15995                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
15996                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
15997                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
15998                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
15999                try {
16000                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16001                            null);
16002                } catch (PackageManagerException e) {
16003                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16004                            + e.getMessage());
16005                    return;
16006                }
16007
16008                synchronized (mPackages) {
16009                    // Ensure the installer package name up to date
16010                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16011
16012                    // Update permissions for restored package
16013                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16014
16015                    mSettings.writeLPr();
16016                }
16017
16018                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16019            }
16020        } else {
16021            synchronized (mPackages) {
16022                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16023                if (ps != null) {
16024                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16025                    if (res.removedInfo.removedChildPackages != null) {
16026                        final int childCount = res.removedInfo.removedChildPackages.size();
16027                        // Iterate in reverse as we may modify the collection
16028                        for (int i = childCount - 1; i >= 0; i--) {
16029                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16030                            if (res.addedChildPackages.containsKey(childPackageName)) {
16031                                res.removedInfo.removedChildPackages.removeAt(i);
16032                            } else {
16033                                PackageRemovedInfo childInfo = res.removedInfo
16034                                        .removedChildPackages.valueAt(i);
16035                                childInfo.removedForAllUsers = mPackages.get(
16036                                        childInfo.removedPackage) == null;
16037                            }
16038                        }
16039                    }
16040                }
16041            }
16042        }
16043    }
16044
16045    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16046            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16047            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16048            int installReason) {
16049        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16050                + ", old=" + deletedPackage);
16051
16052        final boolean disabledSystem;
16053
16054        // Remove existing system package
16055        removePackageLI(deletedPackage, true);
16056
16057        synchronized (mPackages) {
16058            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16059        }
16060        if (!disabledSystem) {
16061            // We didn't need to disable the .apk as a current system package,
16062            // which means we are replacing another update that is already
16063            // installed.  We need to make sure to delete the older one's .apk.
16064            res.removedInfo.args = createInstallArgsForExisting(0,
16065                    deletedPackage.applicationInfo.getCodePath(),
16066                    deletedPackage.applicationInfo.getResourcePath(),
16067                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16068        } else {
16069            res.removedInfo.args = null;
16070        }
16071
16072        // Successfully disabled the old package. Now proceed with re-installation
16073        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16074                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16075        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16076
16077        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16078        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16079                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16080
16081        PackageParser.Package newPackage = null;
16082        try {
16083            // Add the package to the internal data structures
16084            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16085
16086            // Set the update and install times
16087            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16088            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16089                    System.currentTimeMillis());
16090
16091            // Update the package dynamic state if succeeded
16092            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16093                // Now that the install succeeded make sure we remove data
16094                // directories for any child package the update removed.
16095                final int deletedChildCount = (deletedPackage.childPackages != null)
16096                        ? deletedPackage.childPackages.size() : 0;
16097                final int newChildCount = (newPackage.childPackages != null)
16098                        ? newPackage.childPackages.size() : 0;
16099                for (int i = 0; i < deletedChildCount; i++) {
16100                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16101                    boolean childPackageDeleted = true;
16102                    for (int j = 0; j < newChildCount; j++) {
16103                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16104                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16105                            childPackageDeleted = false;
16106                            break;
16107                        }
16108                    }
16109                    if (childPackageDeleted) {
16110                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16111                                deletedChildPkg.packageName);
16112                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16113                            PackageRemovedInfo removedChildRes = res.removedInfo
16114                                    .removedChildPackages.get(deletedChildPkg.packageName);
16115                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16116                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16117                        }
16118                    }
16119                }
16120
16121                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16122                        installReason);
16123                prepareAppDataAfterInstallLIF(newPackage);
16124            }
16125        } catch (PackageManagerException e) {
16126            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16127            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16128        }
16129
16130        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16131            // Re installation failed. Restore old information
16132            // Remove new pkg information
16133            if (newPackage != null) {
16134                removeInstalledPackageLI(newPackage, true);
16135            }
16136            // Add back the old system package
16137            try {
16138                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16139            } catch (PackageManagerException e) {
16140                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16141            }
16142
16143            synchronized (mPackages) {
16144                if (disabledSystem) {
16145                    enableSystemPackageLPw(deletedPackage);
16146                }
16147
16148                // Ensure the installer package name up to date
16149                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16150
16151                // Update permissions for restored package
16152                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16153
16154                mSettings.writeLPr();
16155            }
16156
16157            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16158                    + " after failed upgrade");
16159        }
16160    }
16161
16162    /**
16163     * Checks whether the parent or any of the child packages have a change shared
16164     * user. For a package to be a valid update the shred users of the parent and
16165     * the children should match. We may later support changing child shared users.
16166     * @param oldPkg The updated package.
16167     * @param newPkg The update package.
16168     * @return The shared user that change between the versions.
16169     */
16170    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16171            PackageParser.Package newPkg) {
16172        // Check parent shared user
16173        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16174            return newPkg.packageName;
16175        }
16176        // Check child shared users
16177        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16178        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16179        for (int i = 0; i < newChildCount; i++) {
16180            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16181            // If this child was present, did it have the same shared user?
16182            for (int j = 0; j < oldChildCount; j++) {
16183                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16184                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16185                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16186                    return newChildPkg.packageName;
16187                }
16188            }
16189        }
16190        return null;
16191    }
16192
16193    private void removeNativeBinariesLI(PackageSetting ps) {
16194        // Remove the lib path for the parent package
16195        if (ps != null) {
16196            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16197            // Remove the lib path for the child packages
16198            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16199            for (int i = 0; i < childCount; i++) {
16200                PackageSetting childPs = null;
16201                synchronized (mPackages) {
16202                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16203                }
16204                if (childPs != null) {
16205                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16206                            .legacyNativeLibraryPathString);
16207                }
16208            }
16209        }
16210    }
16211
16212    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16213        // Enable the parent package
16214        mSettings.enableSystemPackageLPw(pkg.packageName);
16215        // Enable the child packages
16216        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16217        for (int i = 0; i < childCount; i++) {
16218            PackageParser.Package childPkg = pkg.childPackages.get(i);
16219            mSettings.enableSystemPackageLPw(childPkg.packageName);
16220        }
16221    }
16222
16223    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16224            PackageParser.Package newPkg) {
16225        // Disable the parent package (parent always replaced)
16226        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16227        // Disable the child packages
16228        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16229        for (int i = 0; i < childCount; i++) {
16230            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16231            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16232            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16233        }
16234        return disabled;
16235    }
16236
16237    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16238            String installerPackageName) {
16239        // Enable the parent package
16240        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16241        // Enable the child packages
16242        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16243        for (int i = 0; i < childCount; i++) {
16244            PackageParser.Package childPkg = pkg.childPackages.get(i);
16245            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16246        }
16247    }
16248
16249    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16250        // Collect all used permissions in the UID
16251        ArraySet<String> usedPermissions = new ArraySet<>();
16252        final int packageCount = su.packages.size();
16253        for (int i = 0; i < packageCount; i++) {
16254            PackageSetting ps = su.packages.valueAt(i);
16255            if (ps.pkg == null) {
16256                continue;
16257            }
16258            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16259            for (int j = 0; j < requestedPermCount; j++) {
16260                String permission = ps.pkg.requestedPermissions.get(j);
16261                BasePermission bp = mSettings.mPermissions.get(permission);
16262                if (bp != null) {
16263                    usedPermissions.add(permission);
16264                }
16265            }
16266        }
16267
16268        PermissionsState permissionsState = su.getPermissionsState();
16269        // Prune install permissions
16270        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16271        final int installPermCount = installPermStates.size();
16272        for (int i = installPermCount - 1; i >= 0;  i--) {
16273            PermissionState permissionState = installPermStates.get(i);
16274            if (!usedPermissions.contains(permissionState.getName())) {
16275                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16276                if (bp != null) {
16277                    permissionsState.revokeInstallPermission(bp);
16278                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16279                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16280                }
16281            }
16282        }
16283
16284        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16285
16286        // Prune runtime permissions
16287        for (int userId : allUserIds) {
16288            List<PermissionState> runtimePermStates = permissionsState
16289                    .getRuntimePermissionStates(userId);
16290            final int runtimePermCount = runtimePermStates.size();
16291            for (int i = runtimePermCount - 1; i >= 0; i--) {
16292                PermissionState permissionState = runtimePermStates.get(i);
16293                if (!usedPermissions.contains(permissionState.getName())) {
16294                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16295                    if (bp != null) {
16296                        permissionsState.revokeRuntimePermission(bp, userId);
16297                        permissionsState.updatePermissionFlags(bp, userId,
16298                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16299                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16300                                runtimePermissionChangedUserIds, userId);
16301                    }
16302                }
16303            }
16304        }
16305
16306        return runtimePermissionChangedUserIds;
16307    }
16308
16309    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16310            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16311        // Update the parent package setting
16312        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16313                res, user, installReason);
16314        // Update the child packages setting
16315        final int childCount = (newPackage.childPackages != null)
16316                ? newPackage.childPackages.size() : 0;
16317        for (int i = 0; i < childCount; i++) {
16318            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16319            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16320            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16321                    childRes.origUsers, childRes, user, installReason);
16322        }
16323    }
16324
16325    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16326            String installerPackageName, int[] allUsers, int[] installedForUsers,
16327            PackageInstalledInfo res, UserHandle user, int installReason) {
16328        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16329
16330        String pkgName = newPackage.packageName;
16331        synchronized (mPackages) {
16332            //write settings. the installStatus will be incomplete at this stage.
16333            //note that the new package setting would have already been
16334            //added to mPackages. It hasn't been persisted yet.
16335            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16336            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16337            mSettings.writeLPr();
16338            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16339        }
16340
16341        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16342        synchronized (mPackages) {
16343            updatePermissionsLPw(newPackage.packageName, newPackage,
16344                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16345                            ? UPDATE_PERMISSIONS_ALL : 0));
16346            // For system-bundled packages, we assume that installing an upgraded version
16347            // of the package implies that the user actually wants to run that new code,
16348            // so we enable the package.
16349            PackageSetting ps = mSettings.mPackages.get(pkgName);
16350            final int userId = user.getIdentifier();
16351            if (ps != null) {
16352                if (isSystemApp(newPackage)) {
16353                    if (DEBUG_INSTALL) {
16354                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16355                    }
16356                    // Enable system package for requested users
16357                    if (res.origUsers != null) {
16358                        for (int origUserId : res.origUsers) {
16359                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16360                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16361                                        origUserId, installerPackageName);
16362                            }
16363                        }
16364                    }
16365                    // Also convey the prior install/uninstall state
16366                    if (allUsers != null && installedForUsers != null) {
16367                        for (int currentUserId : allUsers) {
16368                            final boolean installed = ArrayUtils.contains(
16369                                    installedForUsers, currentUserId);
16370                            if (DEBUG_INSTALL) {
16371                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16372                            }
16373                            ps.setInstalled(installed, currentUserId);
16374                        }
16375                        // these install state changes will be persisted in the
16376                        // upcoming call to mSettings.writeLPr().
16377                    }
16378                }
16379                // It's implied that when a user requests installation, they want the app to be
16380                // installed and enabled.
16381                if (userId != UserHandle.USER_ALL) {
16382                    ps.setInstalled(true, userId);
16383                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16384                }
16385
16386                // When replacing an existing package, preserve the original install reason for all
16387                // users that had the package installed before.
16388                final Set<Integer> previousUserIds = new ArraySet<>();
16389                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16390                    final int installReasonCount = res.removedInfo.installReasons.size();
16391                    for (int i = 0; i < installReasonCount; i++) {
16392                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16393                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16394                        ps.setInstallReason(previousInstallReason, previousUserId);
16395                        previousUserIds.add(previousUserId);
16396                    }
16397                }
16398
16399                // Set install reason for users that are having the package newly installed.
16400                if (userId == UserHandle.USER_ALL) {
16401                    for (int currentUserId : sUserManager.getUserIds()) {
16402                        if (!previousUserIds.contains(currentUserId)) {
16403                            ps.setInstallReason(installReason, currentUserId);
16404                        }
16405                    }
16406                } else if (!previousUserIds.contains(userId)) {
16407                    ps.setInstallReason(installReason, userId);
16408                }
16409            }
16410            res.name = pkgName;
16411            res.uid = newPackage.applicationInfo.uid;
16412            res.pkg = newPackage;
16413            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16414            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16415            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16416            //to update install status
16417            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16418            mSettings.writeLPr();
16419            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16420        }
16421
16422        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16423    }
16424
16425    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16426        try {
16427            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16428            installPackageLI(args, res);
16429        } finally {
16430            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16431        }
16432    }
16433
16434    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16435        final int installFlags = args.installFlags;
16436        final String installerPackageName = args.installerPackageName;
16437        final String volumeUuid = args.volumeUuid;
16438        final File tmpPackageFile = new File(args.getCodePath());
16439        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16440        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16441                || (args.volumeUuid != null));
16442        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
16443        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16444        boolean replace = false;
16445        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16446        if (args.move != null) {
16447            // moving a complete application; perform an initial scan on the new install location
16448            scanFlags |= SCAN_INITIAL;
16449        }
16450        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16451            scanFlags |= SCAN_DONT_KILL_APP;
16452        }
16453
16454        // Result object to be returned
16455        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16456
16457        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16458
16459        // Sanity check
16460        if (ephemeral && (forwardLocked || onExternal)) {
16461            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16462                    + " external=" + onExternal);
16463            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
16464            return;
16465        }
16466
16467        // Retrieve PackageSettings and parse package
16468        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16469                | PackageParser.PARSE_ENFORCE_CODE
16470                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16471                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16472                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16473                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16474        PackageParser pp = new PackageParser();
16475        pp.setSeparateProcesses(mSeparateProcesses);
16476        pp.setDisplayMetrics(mMetrics);
16477
16478        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16479        final PackageParser.Package pkg;
16480        try {
16481            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16482        } catch (PackageParserException e) {
16483            res.setError("Failed parse during installPackageLI", e);
16484            return;
16485        } finally {
16486            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16487        }
16488
16489//        // Ephemeral apps must have target SDK >= O.
16490//        // TODO: Update conditional and error message when O gets locked down
16491//        if (ephemeral && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16492//            res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID,
16493//                    "Ephemeral apps must have target SDK version of at least O");
16494//            return;
16495//        }
16496
16497        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16498            // Static shared libraries have synthetic package names
16499            renameStaticSharedLibraryPackage(pkg);
16500
16501            // No static shared libs on external storage
16502            if (onExternal) {
16503                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16504                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16505                        "Packages declaring static-shared libs cannot be updated");
16506                return;
16507            }
16508        }
16509
16510        // If we are installing a clustered package add results for the children
16511        if (pkg.childPackages != null) {
16512            synchronized (mPackages) {
16513                final int childCount = pkg.childPackages.size();
16514                for (int i = 0; i < childCount; i++) {
16515                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16516                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16517                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16518                    childRes.pkg = childPkg;
16519                    childRes.name = childPkg.packageName;
16520                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16521                    if (childPs != null) {
16522                        childRes.origUsers = childPs.queryInstalledUsers(
16523                                sUserManager.getUserIds(), true);
16524                    }
16525                    if ((mPackages.containsKey(childPkg.packageName))) {
16526                        childRes.removedInfo = new PackageRemovedInfo();
16527                        childRes.removedInfo.removedPackage = childPkg.packageName;
16528                    }
16529                    if (res.addedChildPackages == null) {
16530                        res.addedChildPackages = new ArrayMap<>();
16531                    }
16532                    res.addedChildPackages.put(childPkg.packageName, childRes);
16533                }
16534            }
16535        }
16536
16537        // If package doesn't declare API override, mark that we have an install
16538        // time CPU ABI override.
16539        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16540            pkg.cpuAbiOverride = args.abiOverride;
16541        }
16542
16543        String pkgName = res.name = pkg.packageName;
16544        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16545            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16546                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16547                return;
16548            }
16549        }
16550
16551        try {
16552            // either use what we've been given or parse directly from the APK
16553            if (args.certificates != null) {
16554                try {
16555                    PackageParser.populateCertificates(pkg, args.certificates);
16556                } catch (PackageParserException e) {
16557                    // there was something wrong with the certificates we were given;
16558                    // try to pull them from the APK
16559                    PackageParser.collectCertificates(pkg, parseFlags);
16560                }
16561            } else {
16562                PackageParser.collectCertificates(pkg, parseFlags);
16563            }
16564        } catch (PackageParserException e) {
16565            res.setError("Failed collect during installPackageLI", e);
16566            return;
16567        }
16568
16569        // Get rid of all references to package scan path via parser.
16570        pp = null;
16571        String oldCodePath = null;
16572        boolean systemApp = false;
16573        synchronized (mPackages) {
16574            // Check if installing already existing package
16575            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16576                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16577                if (pkg.mOriginalPackages != null
16578                        && pkg.mOriginalPackages.contains(oldName)
16579                        && mPackages.containsKey(oldName)) {
16580                    // This package is derived from an original package,
16581                    // and this device has been updating from that original
16582                    // name.  We must continue using the original name, so
16583                    // rename the new package here.
16584                    pkg.setPackageName(oldName);
16585                    pkgName = pkg.packageName;
16586                    replace = true;
16587                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16588                            + oldName + " pkgName=" + pkgName);
16589                } else if (mPackages.containsKey(pkgName)) {
16590                    // This package, under its official name, already exists
16591                    // on the device; we should replace it.
16592                    replace = true;
16593                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16594                }
16595
16596                // Child packages are installed through the parent package
16597                if (pkg.parentPackage != null) {
16598                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16599                            "Package " + pkg.packageName + " is child of package "
16600                                    + pkg.parentPackage.parentPackage + ". Child packages "
16601                                    + "can be updated only through the parent package.");
16602                    return;
16603                }
16604
16605                if (replace) {
16606                    // Prevent apps opting out from runtime permissions
16607                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16608                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16609                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16610                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16611                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16612                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16613                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16614                                        + " doesn't support runtime permissions but the old"
16615                                        + " target SDK " + oldTargetSdk + " does.");
16616                        return;
16617                    }
16618
16619                    // Prevent installing of child packages
16620                    if (oldPackage.parentPackage != null) {
16621                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16622                                "Package " + pkg.packageName + " is child of package "
16623                                        + oldPackage.parentPackage + ". Child packages "
16624                                        + "can be updated only through the parent package.");
16625                        return;
16626                    }
16627                }
16628            }
16629
16630            PackageSetting ps = mSettings.mPackages.get(pkgName);
16631            if (ps != null) {
16632                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16633
16634                // Static shared libs have same package with different versions where
16635                // we internally use a synthetic package name to allow multiple versions
16636                // of the same package, therefore we need to compare signatures against
16637                // the package setting for the latest library version.
16638                PackageSetting signatureCheckPs = ps;
16639                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16640                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16641                    if (libraryEntry != null) {
16642                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16643                    }
16644                }
16645
16646                // Quick sanity check that we're signed correctly if updating;
16647                // we'll check this again later when scanning, but we want to
16648                // bail early here before tripping over redefined permissions.
16649                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
16650                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
16651                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16652                                + pkg.packageName + " upgrade keys do not match the "
16653                                + "previously installed version");
16654                        return;
16655                    }
16656                } else {
16657                    try {
16658                        verifySignaturesLP(signatureCheckPs, pkg);
16659                    } catch (PackageManagerException e) {
16660                        res.setError(e.error, e.getMessage());
16661                        return;
16662                    }
16663                }
16664
16665                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16666                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16667                    systemApp = (ps.pkg.applicationInfo.flags &
16668                            ApplicationInfo.FLAG_SYSTEM) != 0;
16669                }
16670                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16671            }
16672
16673            // Check whether the newly-scanned package wants to define an already-defined perm
16674            int N = pkg.permissions.size();
16675            for (int i = N-1; i >= 0; i--) {
16676                PackageParser.Permission perm = pkg.permissions.get(i);
16677                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
16678                if (bp != null) {
16679                    // If the defining package is signed with our cert, it's okay.  This
16680                    // also includes the "updating the same package" case, of course.
16681                    // "updating same package" could also involve key-rotation.
16682                    final boolean sigsOk;
16683                    if (bp.sourcePackage.equals(pkg.packageName)
16684                            && (bp.packageSetting instanceof PackageSetting)
16685                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
16686                                    scanFlags))) {
16687                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
16688                    } else {
16689                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
16690                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16691                    }
16692                    if (!sigsOk) {
16693                        // If the owning package is the system itself, we log but allow
16694                        // install to proceed; we fail the install on all other permission
16695                        // redefinitions.
16696                        if (!bp.sourcePackage.equals("android")) {
16697                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16698                                    + pkg.packageName + " attempting to redeclare permission "
16699                                    + perm.info.name + " already owned by " + bp.sourcePackage);
16700                            res.origPermission = perm.info.name;
16701                            res.origPackage = bp.sourcePackage;
16702                            return;
16703                        } else {
16704                            Slog.w(TAG, "Package " + pkg.packageName
16705                                    + " attempting to redeclare system permission "
16706                                    + perm.info.name + "; ignoring new declaration");
16707                            pkg.permissions.remove(i);
16708                        }
16709                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16710                        // Prevent apps to change protection level to dangerous from any other
16711                        // type as this would allow a privilege escalation where an app adds a
16712                        // normal/signature permission in other app's group and later redefines
16713                        // it as dangerous leading to the group auto-grant.
16714                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16715                                == PermissionInfo.PROTECTION_DANGEROUS) {
16716                            if (bp != null && !bp.isRuntime()) {
16717                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16718                                        + "non-runtime permission " + perm.info.name
16719                                        + " to runtime; keeping old protection level");
16720                                perm.info.protectionLevel = bp.protectionLevel;
16721                            }
16722                        }
16723                    }
16724                }
16725            }
16726        }
16727
16728        if (systemApp) {
16729            if (onExternal) {
16730                // Abort update; system app can't be replaced with app on sdcard
16731                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16732                        "Cannot install updates to system apps on sdcard");
16733                return;
16734            } else if (ephemeral) {
16735                // Abort update; system app can't be replaced with an ephemeral app
16736                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
16737                        "Cannot update a system app with an ephemeral app");
16738                return;
16739            }
16740        }
16741
16742        if (args.move != null) {
16743            // We did an in-place move, so dex is ready to roll
16744            scanFlags |= SCAN_NO_DEX;
16745            scanFlags |= SCAN_MOVE;
16746
16747            synchronized (mPackages) {
16748                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16749                if (ps == null) {
16750                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16751                            "Missing settings for moved package " + pkgName);
16752                }
16753
16754                // We moved the entire application as-is, so bring over the
16755                // previously derived ABI information.
16756                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16757                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16758            }
16759
16760        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16761            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16762            scanFlags |= SCAN_NO_DEX;
16763
16764            try {
16765                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16766                    args.abiOverride : pkg.cpuAbiOverride);
16767                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
16768                        true /*extractLibs*/, mAppLib32InstallDir);
16769            } catch (PackageManagerException pme) {
16770                Slog.e(TAG, "Error deriving application ABI", pme);
16771                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16772                return;
16773            }
16774
16775            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16776            // Do not run PackageDexOptimizer through the local performDexOpt
16777            // method because `pkg` may not be in `mPackages` yet.
16778            //
16779            // Also, don't fail application installs if the dexopt step fails.
16780            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16781                    null /* instructionSets */, false /* checkProfiles */,
16782                    getCompilerFilterForReason(REASON_INSTALL),
16783                    getOrCreateCompilerPackageStats(pkg));
16784            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16785
16786            // Notify BackgroundDexOptJobService that the package has been changed.
16787            // If this is an update of a package which used to fail to compile,
16788            // BDOS will remove it from its blacklist.
16789            // TODO: Layering violation
16790            BackgroundDexOptJobService.notifyPackageChanged(pkg.packageName);
16791        }
16792
16793        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16794            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16795            return;
16796        }
16797
16798        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16799
16800        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16801                "installPackageLI")) {
16802            if (replace) {
16803                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16804                    // Static libs have a synthetic package name containing the version
16805                    // and cannot be updated as an update would get a new package name,
16806                    // unless this is the exact same version code which is useful for
16807                    // development.
16808                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16809                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
16810                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16811                                + "static-shared libs cannot be updated");
16812                        return;
16813                    }
16814                }
16815                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
16816                        installerPackageName, res, args.installReason);
16817            } else {
16818                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16819                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16820            }
16821        }
16822        synchronized (mPackages) {
16823            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16824            if (ps != null) {
16825                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16826            }
16827
16828            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16829            for (int i = 0; i < childCount; i++) {
16830                PackageParser.Package childPkg = pkg.childPackages.get(i);
16831                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16832                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16833                if (childPs != null) {
16834                    childRes.newUsers = childPs.queryInstalledUsers(
16835                            sUserManager.getUserIds(), true);
16836                }
16837            }
16838        }
16839    }
16840
16841    private void startIntentFilterVerifications(int userId, boolean replacing,
16842            PackageParser.Package pkg) {
16843        if (mIntentFilterVerifierComponent == null) {
16844            Slog.w(TAG, "No IntentFilter verification will not be done as "
16845                    + "there is no IntentFilterVerifier available!");
16846            return;
16847        }
16848
16849        final int verifierUid = getPackageUid(
16850                mIntentFilterVerifierComponent.getPackageName(),
16851                MATCH_DEBUG_TRIAGED_MISSING,
16852                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16853
16854        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16855        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16856        mHandler.sendMessage(msg);
16857
16858        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16859        for (int i = 0; i < childCount; i++) {
16860            PackageParser.Package childPkg = pkg.childPackages.get(i);
16861            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16862            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
16863            mHandler.sendMessage(msg);
16864        }
16865    }
16866
16867    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
16868            PackageParser.Package pkg) {
16869        int size = pkg.activities.size();
16870        if (size == 0) {
16871            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16872                    "No activity, so no need to verify any IntentFilter!");
16873            return;
16874        }
16875
16876        final boolean hasDomainURLs = hasDomainURLs(pkg);
16877        if (!hasDomainURLs) {
16878            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16879                    "No domain URLs, so no need to verify any IntentFilter!");
16880            return;
16881        }
16882
16883        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
16884                + " if any IntentFilter from the " + size
16885                + " Activities needs verification ...");
16886
16887        int count = 0;
16888        final String packageName = pkg.packageName;
16889
16890        synchronized (mPackages) {
16891            // If this is a new install and we see that we've already run verification for this
16892            // package, we have nothing to do: it means the state was restored from backup.
16893            if (!replacing) {
16894                IntentFilterVerificationInfo ivi =
16895                        mSettings.getIntentFilterVerificationLPr(packageName);
16896                if (ivi != null) {
16897                    if (DEBUG_DOMAIN_VERIFICATION) {
16898                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
16899                                + ivi.getStatusString());
16900                    }
16901                    return;
16902                }
16903            }
16904
16905            // If any filters need to be verified, then all need to be.
16906            boolean needToVerify = false;
16907            for (PackageParser.Activity a : pkg.activities) {
16908                for (ActivityIntentInfo filter : a.intents) {
16909                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
16910                        if (DEBUG_DOMAIN_VERIFICATION) {
16911                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
16912                        }
16913                        needToVerify = true;
16914                        break;
16915                    }
16916                }
16917            }
16918
16919            if (needToVerify) {
16920                final int verificationId = mIntentFilterVerificationToken++;
16921                for (PackageParser.Activity a : pkg.activities) {
16922                    for (ActivityIntentInfo filter : a.intents) {
16923                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
16924                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16925                                    "Verification needed for IntentFilter:" + filter.toString());
16926                            mIntentFilterVerifier.addOneIntentFilterVerification(
16927                                    verifierUid, userId, verificationId, filter, packageName);
16928                            count++;
16929                        }
16930                    }
16931                }
16932            }
16933        }
16934
16935        if (count > 0) {
16936            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
16937                    + " IntentFilter verification" + (count > 1 ? "s" : "")
16938                    +  " for userId:" + userId);
16939            mIntentFilterVerifier.startVerifications(userId);
16940        } else {
16941            if (DEBUG_DOMAIN_VERIFICATION) {
16942                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
16943            }
16944        }
16945    }
16946
16947    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
16948        final ComponentName cn  = filter.activity.getComponentName();
16949        final String packageName = cn.getPackageName();
16950
16951        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
16952                packageName);
16953        if (ivi == null) {
16954            return true;
16955        }
16956        int status = ivi.getStatus();
16957        switch (status) {
16958            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
16959            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
16960                return true;
16961
16962            default:
16963                // Nothing to do
16964                return false;
16965        }
16966    }
16967
16968    private static boolean isMultiArch(ApplicationInfo info) {
16969        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
16970    }
16971
16972    private static boolean isExternal(PackageParser.Package pkg) {
16973        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16974    }
16975
16976    private static boolean isExternal(PackageSetting ps) {
16977        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16978    }
16979
16980    private static boolean isEphemeral(PackageParser.Package pkg) {
16981        return pkg.applicationInfo.isInstantApp();
16982    }
16983
16984    private static boolean isEphemeral(PackageSetting ps) {
16985        return ps.pkg != null && isEphemeral(ps.pkg);
16986    }
16987
16988    private static boolean isSystemApp(PackageParser.Package pkg) {
16989        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
16990    }
16991
16992    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
16993        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16994    }
16995
16996    private static boolean hasDomainURLs(PackageParser.Package pkg) {
16997        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
16998    }
16999
17000    private static boolean isSystemApp(PackageSetting ps) {
17001        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17002    }
17003
17004    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17005        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17006    }
17007
17008    private int packageFlagsToInstallFlags(PackageSetting ps) {
17009        int installFlags = 0;
17010        if (isEphemeral(ps)) {
17011            installFlags |= PackageManager.INSTALL_EPHEMERAL;
17012        }
17013        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17014            // This existing package was an external ASEC install when we have
17015            // the external flag without a UUID
17016            installFlags |= PackageManager.INSTALL_EXTERNAL;
17017        }
17018        if (ps.isForwardLocked()) {
17019            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17020        }
17021        return installFlags;
17022    }
17023
17024    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17025        if (isExternal(pkg)) {
17026            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17027                return StorageManager.UUID_PRIMARY_PHYSICAL;
17028            } else {
17029                return pkg.volumeUuid;
17030            }
17031        } else {
17032            return StorageManager.UUID_PRIVATE_INTERNAL;
17033        }
17034    }
17035
17036    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17037        if (isExternal(pkg)) {
17038            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17039                return mSettings.getExternalVersion();
17040            } else {
17041                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17042            }
17043        } else {
17044            return mSettings.getInternalVersion();
17045        }
17046    }
17047
17048    private void deleteTempPackageFiles() {
17049        final FilenameFilter filter = new FilenameFilter() {
17050            public boolean accept(File dir, String name) {
17051                return name.startsWith("vmdl") && name.endsWith(".tmp");
17052            }
17053        };
17054        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17055            file.delete();
17056        }
17057    }
17058
17059    @Override
17060    public void deletePackageAsUser(String packageName, int versionCode,
17061            IPackageDeleteObserver observer, int userId, int flags) {
17062        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17063                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17064    }
17065
17066    @Override
17067    public void deletePackageVersioned(VersionedPackage versionedPackage,
17068            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17069        mContext.enforceCallingOrSelfPermission(
17070                android.Manifest.permission.DELETE_PACKAGES, null);
17071        Preconditions.checkNotNull(versionedPackage);
17072        Preconditions.checkNotNull(observer);
17073        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17074                PackageManager.VERSION_CODE_HIGHEST,
17075                Integer.MAX_VALUE, "versionCode must be >= -1");
17076
17077        final String packageName = versionedPackage.getPackageName();
17078        // TODO: We will change version code to long, so in the new API it is long
17079        final int versionCode = (int) versionedPackage.getVersionCode();
17080        final String internalPackageName;
17081        synchronized (mPackages) {
17082            // Normalize package name to handle renamed packages and static libs
17083            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17084                    // TODO: We will change version code to long, so in the new API it is long
17085                    (int) versionedPackage.getVersionCode());
17086        }
17087
17088        final int uid = Binder.getCallingUid();
17089        if (!isOrphaned(internalPackageName)
17090                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17091            try {
17092                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17093                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17094                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17095                observer.onUserActionRequired(intent);
17096            } catch (RemoteException re) {
17097            }
17098            return;
17099        }
17100        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17101        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17102        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17103            mContext.enforceCallingOrSelfPermission(
17104                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17105                    "deletePackage for user " + userId);
17106        }
17107
17108        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17109            try {
17110                observer.onPackageDeleted(packageName,
17111                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17112            } catch (RemoteException re) {
17113            }
17114            return;
17115        }
17116
17117        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17118            try {
17119                observer.onPackageDeleted(packageName,
17120                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17121            } catch (RemoteException re) {
17122            }
17123            return;
17124        }
17125
17126        if (DEBUG_REMOVE) {
17127            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17128                    + " deleteAllUsers: " + deleteAllUsers + " version="
17129                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17130                    ? "VERSION_CODE_HIGHEST" : versionCode));
17131        }
17132        // Queue up an async operation since the package deletion may take a little while.
17133        mHandler.post(new Runnable() {
17134            public void run() {
17135                mHandler.removeCallbacks(this);
17136                int returnCode;
17137                if (!deleteAllUsers) {
17138                    returnCode = deletePackageX(internalPackageName, versionCode,
17139                            userId, deleteFlags);
17140                } else {
17141                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17142                            internalPackageName, users);
17143                    // If nobody is blocking uninstall, proceed with delete for all users
17144                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17145                        returnCode = deletePackageX(internalPackageName, versionCode,
17146                                userId, deleteFlags);
17147                    } else {
17148                        // Otherwise uninstall individually for users with blockUninstalls=false
17149                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17150                        for (int userId : users) {
17151                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17152                                returnCode = deletePackageX(internalPackageName, versionCode,
17153                                        userId, userFlags);
17154                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17155                                    Slog.w(TAG, "Package delete failed for user " + userId
17156                                            + ", returnCode " + returnCode);
17157                                }
17158                            }
17159                        }
17160                        // The app has only been marked uninstalled for certain users.
17161                        // We still need to report that delete was blocked
17162                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17163                    }
17164                }
17165                try {
17166                    observer.onPackageDeleted(packageName, returnCode, null);
17167                } catch (RemoteException e) {
17168                    Log.i(TAG, "Observer no longer exists.");
17169                } //end catch
17170            } //end run
17171        });
17172    }
17173
17174    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17175        if (pkg.staticSharedLibName != null) {
17176            return pkg.manifestPackageName;
17177        }
17178        return pkg.packageName;
17179    }
17180
17181    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17182        // Handle renamed packages
17183        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17184        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17185
17186        // Is this a static library?
17187        SparseArray<SharedLibraryEntry> versionedLib =
17188                mStaticLibsByDeclaringPackage.get(packageName);
17189        if (versionedLib == null || versionedLib.size() <= 0) {
17190            return packageName;
17191        }
17192
17193        // Figure out which lib versions the caller can see
17194        SparseIntArray versionsCallerCanSee = null;
17195        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17196        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17197                && callingAppId != Process.ROOT_UID) {
17198            versionsCallerCanSee = new SparseIntArray();
17199            String libName = versionedLib.valueAt(0).info.getName();
17200            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17201            if (uidPackages != null) {
17202                for (String uidPackage : uidPackages) {
17203                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17204                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17205                    if (libIdx >= 0) {
17206                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17207                        versionsCallerCanSee.append(libVersion, libVersion);
17208                    }
17209                }
17210            }
17211        }
17212
17213        // Caller can see nothing - done
17214        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17215            return packageName;
17216        }
17217
17218        // Find the version the caller can see and the app version code
17219        SharedLibraryEntry highestVersion = null;
17220        final int versionCount = versionedLib.size();
17221        for (int i = 0; i < versionCount; i++) {
17222            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17223            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17224                    libEntry.info.getVersion()) < 0) {
17225                continue;
17226            }
17227            // TODO: We will change version code to long, so in the new API it is long
17228            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17229            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17230                if (libVersionCode == versionCode) {
17231                    return libEntry.apk;
17232                }
17233            } else if (highestVersion == null) {
17234                highestVersion = libEntry;
17235            } else if (libVersionCode  > highestVersion.info
17236                    .getDeclaringPackage().getVersionCode()) {
17237                highestVersion = libEntry;
17238            }
17239        }
17240
17241        if (highestVersion != null) {
17242            return highestVersion.apk;
17243        }
17244
17245        return packageName;
17246    }
17247
17248    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17249        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17250              || callingUid == Process.SYSTEM_UID) {
17251            return true;
17252        }
17253        final int callingUserId = UserHandle.getUserId(callingUid);
17254        // If the caller installed the pkgName, then allow it to silently uninstall.
17255        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17256            return true;
17257        }
17258
17259        // Allow package verifier to silently uninstall.
17260        if (mRequiredVerifierPackage != null &&
17261                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17262            return true;
17263        }
17264
17265        // Allow package uninstaller to silently uninstall.
17266        if (mRequiredUninstallerPackage != null &&
17267                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17268            return true;
17269        }
17270
17271        // Allow storage manager to silently uninstall.
17272        if (mStorageManagerPackage != null &&
17273                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17274            return true;
17275        }
17276        return false;
17277    }
17278
17279    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17280        int[] result = EMPTY_INT_ARRAY;
17281        for (int userId : userIds) {
17282            if (getBlockUninstallForUser(packageName, userId)) {
17283                result = ArrayUtils.appendInt(result, userId);
17284            }
17285        }
17286        return result;
17287    }
17288
17289    @Override
17290    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17291        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17292    }
17293
17294    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17295        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17296                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17297        try {
17298            if (dpm != null) {
17299                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17300                        /* callingUserOnly =*/ false);
17301                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17302                        : deviceOwnerComponentName.getPackageName();
17303                // Does the package contains the device owner?
17304                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17305                // this check is probably not needed, since DO should be registered as a device
17306                // admin on some user too. (Original bug for this: b/17657954)
17307                if (packageName.equals(deviceOwnerPackageName)) {
17308                    return true;
17309                }
17310                // Does it contain a device admin for any user?
17311                int[] users;
17312                if (userId == UserHandle.USER_ALL) {
17313                    users = sUserManager.getUserIds();
17314                } else {
17315                    users = new int[]{userId};
17316                }
17317                for (int i = 0; i < users.length; ++i) {
17318                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17319                        return true;
17320                    }
17321                }
17322            }
17323        } catch (RemoteException e) {
17324        }
17325        return false;
17326    }
17327
17328    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17329        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17330    }
17331
17332    /**
17333     *  This method is an internal method that could be get invoked either
17334     *  to delete an installed package or to clean up a failed installation.
17335     *  After deleting an installed package, a broadcast is sent to notify any
17336     *  listeners that the package has been removed. For cleaning up a failed
17337     *  installation, the broadcast is not necessary since the package's
17338     *  installation wouldn't have sent the initial broadcast either
17339     *  The key steps in deleting a package are
17340     *  deleting the package information in internal structures like mPackages,
17341     *  deleting the packages base directories through installd
17342     *  updating mSettings to reflect current status
17343     *  persisting settings for later use
17344     *  sending a broadcast if necessary
17345     */
17346    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17347        final PackageRemovedInfo info = new PackageRemovedInfo();
17348        final boolean res;
17349
17350        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17351                ? UserHandle.USER_ALL : userId;
17352
17353        if (isPackageDeviceAdmin(packageName, removeUser)) {
17354            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17355            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17356        }
17357
17358        PackageSetting uninstalledPs = null;
17359
17360        // for the uninstall-updates case and restricted profiles, remember the per-
17361        // user handle installed state
17362        int[] allUsers;
17363        synchronized (mPackages) {
17364            uninstalledPs = mSettings.mPackages.get(packageName);
17365            if (uninstalledPs == null) {
17366                Slog.w(TAG, "Not removing non-existent package " + packageName);
17367                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17368            }
17369
17370            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17371                    && uninstalledPs.versionCode != versionCode) {
17372                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17373                        + uninstalledPs.versionCode + " != " + versionCode);
17374                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17375            }
17376
17377            // Static shared libs can be declared by any package, so let us not
17378            // allow removing a package if it provides a lib others depend on.
17379            PackageParser.Package pkg = mPackages.get(packageName);
17380            if (pkg != null && pkg.staticSharedLibName != null) {
17381                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17382                        pkg.staticSharedLibVersion);
17383                if (libEntry != null) {
17384                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17385                            libEntry.info, 0, userId);
17386                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17387                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17388                                + " hosting lib " + libEntry.info.getName() + " version "
17389                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17390                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17391                    }
17392                }
17393            }
17394
17395            allUsers = sUserManager.getUserIds();
17396            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17397        }
17398
17399        final int freezeUser;
17400        if (isUpdatedSystemApp(uninstalledPs)
17401                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17402            // We're downgrading a system app, which will apply to all users, so
17403            // freeze them all during the downgrade
17404            freezeUser = UserHandle.USER_ALL;
17405        } else {
17406            freezeUser = removeUser;
17407        }
17408
17409        synchronized (mInstallLock) {
17410            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17411            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17412                    deleteFlags, "deletePackageX")) {
17413                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17414                        deleteFlags | REMOVE_CHATTY, info, true, null);
17415            }
17416            synchronized (mPackages) {
17417                if (res) {
17418                    mInstantAppRegistry.onPackageUninstalledLPw(uninstalledPs.pkg,
17419                            info.removedUsers);
17420                }
17421            }
17422        }
17423
17424        if (res) {
17425            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17426            info.sendPackageRemovedBroadcasts(killApp);
17427            info.sendSystemPackageUpdatedBroadcasts();
17428            info.sendSystemPackageAppearedBroadcasts();
17429        }
17430        // Force a gc here.
17431        Runtime.getRuntime().gc();
17432        // Delete the resources here after sending the broadcast to let
17433        // other processes clean up before deleting resources.
17434        if (info.args != null) {
17435            synchronized (mInstallLock) {
17436                info.args.doPostDeleteLI(true);
17437            }
17438        }
17439
17440        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17441    }
17442
17443    class PackageRemovedInfo {
17444        String removedPackage;
17445        int uid = -1;
17446        int removedAppId = -1;
17447        int[] origUsers;
17448        int[] removedUsers = null;
17449        SparseArray<Integer> installReasons;
17450        boolean isRemovedPackageSystemUpdate = false;
17451        boolean isUpdate;
17452        boolean dataRemoved;
17453        boolean removedForAllUsers;
17454        boolean isStaticSharedLib;
17455        // Clean up resources deleted packages.
17456        InstallArgs args = null;
17457        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17458        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17459
17460        void sendPackageRemovedBroadcasts(boolean killApp) {
17461            sendPackageRemovedBroadcastInternal(killApp);
17462            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17463            for (int i = 0; i < childCount; i++) {
17464                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17465                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17466            }
17467        }
17468
17469        void sendSystemPackageUpdatedBroadcasts() {
17470            if (isRemovedPackageSystemUpdate) {
17471                sendSystemPackageUpdatedBroadcastsInternal();
17472                final int childCount = (removedChildPackages != null)
17473                        ? removedChildPackages.size() : 0;
17474                for (int i = 0; i < childCount; i++) {
17475                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17476                    if (childInfo.isRemovedPackageSystemUpdate) {
17477                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17478                    }
17479                }
17480            }
17481        }
17482
17483        void sendSystemPackageAppearedBroadcasts() {
17484            final int packageCount = (appearedChildPackages != null)
17485                    ? appearedChildPackages.size() : 0;
17486            for (int i = 0; i < packageCount; i++) {
17487                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17488                sendPackageAddedForNewUsers(installedInfo.name, true,
17489                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17490            }
17491        }
17492
17493        private void sendSystemPackageUpdatedBroadcastsInternal() {
17494            Bundle extras = new Bundle(2);
17495            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17496            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17497            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
17498                    extras, 0, null, null, null);
17499            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
17500                    extras, 0, null, null, null);
17501            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
17502                    null, 0, removedPackage, null, null);
17503        }
17504
17505        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17506            // Don't send static shared library removal broadcasts as these
17507            // libs are visible only the the apps that depend on them an one
17508            // cannot remove the library if it has a dependency.
17509            if (isStaticSharedLib) {
17510                return;
17511            }
17512            Bundle extras = new Bundle(2);
17513            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17514            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17515            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17516            if (isUpdate || isRemovedPackageSystemUpdate) {
17517                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17518            }
17519            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17520            if (removedPackage != null) {
17521                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
17522                        extras, 0, null, null, removedUsers);
17523                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17524                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17525                            removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17526                            null, null, removedUsers);
17527                }
17528            }
17529            if (removedAppId >= 0) {
17530                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
17531                        removedUsers);
17532            }
17533        }
17534    }
17535
17536    /*
17537     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17538     * flag is not set, the data directory is removed as well.
17539     * make sure this flag is set for partially installed apps. If not its meaningless to
17540     * delete a partially installed application.
17541     */
17542    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17543            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17544        String packageName = ps.name;
17545        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17546        // Retrieve object to delete permissions for shared user later on
17547        final PackageParser.Package deletedPkg;
17548        final PackageSetting deletedPs;
17549        // reader
17550        synchronized (mPackages) {
17551            deletedPkg = mPackages.get(packageName);
17552            deletedPs = mSettings.mPackages.get(packageName);
17553            if (outInfo != null) {
17554                outInfo.removedPackage = packageName;
17555                outInfo.isStaticSharedLib = deletedPkg != null
17556                        && deletedPkg.staticSharedLibName != null;
17557                outInfo.removedUsers = deletedPs != null
17558                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
17559                        : null;
17560            }
17561        }
17562
17563        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
17564
17565        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17566            final PackageParser.Package resolvedPkg;
17567            if (deletedPkg != null) {
17568                resolvedPkg = deletedPkg;
17569            } else {
17570                // We don't have a parsed package when it lives on an ejected
17571                // adopted storage device, so fake something together
17572                resolvedPkg = new PackageParser.Package(ps.name);
17573                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17574            }
17575            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17576                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17577            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17578            if (outInfo != null) {
17579                outInfo.dataRemoved = true;
17580            }
17581            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17582        }
17583
17584        int removedAppId = -1;
17585
17586        // writer
17587        synchronized (mPackages) {
17588            if (deletedPs != null) {
17589                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17590                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17591                    clearDefaultBrowserIfNeeded(packageName);
17592                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17593                    removedAppId = mSettings.removePackageLPw(packageName);
17594                    if (outInfo != null) {
17595                        outInfo.removedAppId = removedAppId;
17596                    }
17597                    updatePermissionsLPw(deletedPs.name, null, 0);
17598                    if (deletedPs.sharedUser != null) {
17599                        // Remove permissions associated with package. Since runtime
17600                        // permissions are per user we have to kill the removed package
17601                        // or packages running under the shared user of the removed
17602                        // package if revoking the permissions requested only by the removed
17603                        // package is successful and this causes a change in gids.
17604                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17605                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17606                                    userId);
17607                            if (userIdToKill == UserHandle.USER_ALL
17608                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17609                                // If gids changed for this user, kill all affected packages.
17610                                mHandler.post(new Runnable() {
17611                                    @Override
17612                                    public void run() {
17613                                        // This has to happen with no lock held.
17614                                        killApplication(deletedPs.name, deletedPs.appId,
17615                                                KILL_APP_REASON_GIDS_CHANGED);
17616                                    }
17617                                });
17618                                break;
17619                            }
17620                        }
17621                    }
17622                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17623                }
17624                // make sure to preserve per-user disabled state if this removal was just
17625                // a downgrade of a system app to the factory package
17626                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17627                    if (DEBUG_REMOVE) {
17628                        Slog.d(TAG, "Propagating install state across downgrade");
17629                    }
17630                    for (int userId : allUserHandles) {
17631                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17632                        if (DEBUG_REMOVE) {
17633                            Slog.d(TAG, "    user " + userId + " => " + installed);
17634                        }
17635                        ps.setInstalled(installed, userId);
17636                    }
17637                }
17638            }
17639            // can downgrade to reader
17640            if (writeSettings) {
17641                // Save settings now
17642                mSettings.writeLPr();
17643            }
17644        }
17645        if (removedAppId != -1) {
17646            // A user ID was deleted here. Go through all users and remove it
17647            // from KeyStore.
17648            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17649        }
17650    }
17651
17652    static boolean locationIsPrivileged(File path) {
17653        try {
17654            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
17655                    .getCanonicalPath();
17656            return path.getCanonicalPath().startsWith(privilegedAppDir);
17657        } catch (IOException e) {
17658            Slog.e(TAG, "Unable to access code path " + path);
17659        }
17660        return false;
17661    }
17662
17663    /*
17664     * Tries to delete system package.
17665     */
17666    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17667            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17668            boolean writeSettings) {
17669        if (deletedPs.parentPackageName != null) {
17670            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17671            return false;
17672        }
17673
17674        final boolean applyUserRestrictions
17675                = (allUserHandles != null) && (outInfo.origUsers != null);
17676        final PackageSetting disabledPs;
17677        // Confirm if the system package has been updated
17678        // An updated system app can be deleted. This will also have to restore
17679        // the system pkg from system partition
17680        // reader
17681        synchronized (mPackages) {
17682            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17683        }
17684
17685        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17686                + " disabledPs=" + disabledPs);
17687
17688        if (disabledPs == null) {
17689            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17690            return false;
17691        } else if (DEBUG_REMOVE) {
17692            Slog.d(TAG, "Deleting system pkg from data partition");
17693        }
17694
17695        if (DEBUG_REMOVE) {
17696            if (applyUserRestrictions) {
17697                Slog.d(TAG, "Remembering install states:");
17698                for (int userId : allUserHandles) {
17699                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17700                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17701                }
17702            }
17703        }
17704
17705        // Delete the updated package
17706        outInfo.isRemovedPackageSystemUpdate = true;
17707        if (outInfo.removedChildPackages != null) {
17708            final int childCount = (deletedPs.childPackageNames != null)
17709                    ? deletedPs.childPackageNames.size() : 0;
17710            for (int i = 0; i < childCount; i++) {
17711                String childPackageName = deletedPs.childPackageNames.get(i);
17712                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17713                        .contains(childPackageName)) {
17714                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17715                            childPackageName);
17716                    if (childInfo != null) {
17717                        childInfo.isRemovedPackageSystemUpdate = true;
17718                    }
17719                }
17720            }
17721        }
17722
17723        if (disabledPs.versionCode < deletedPs.versionCode) {
17724            // Delete data for downgrades
17725            flags &= ~PackageManager.DELETE_KEEP_DATA;
17726        } else {
17727            // Preserve data by setting flag
17728            flags |= PackageManager.DELETE_KEEP_DATA;
17729        }
17730
17731        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17732                outInfo, writeSettings, disabledPs.pkg);
17733        if (!ret) {
17734            return false;
17735        }
17736
17737        // writer
17738        synchronized (mPackages) {
17739            // Reinstate the old system package
17740            enableSystemPackageLPw(disabledPs.pkg);
17741            // Remove any native libraries from the upgraded package.
17742            removeNativeBinariesLI(deletedPs);
17743        }
17744
17745        // Install the system package
17746        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17747        int parseFlags = mDefParseFlags
17748                | PackageParser.PARSE_MUST_BE_APK
17749                | PackageParser.PARSE_IS_SYSTEM
17750                | PackageParser.PARSE_IS_SYSTEM_DIR;
17751        if (locationIsPrivileged(disabledPs.codePath)) {
17752            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
17753        }
17754
17755        final PackageParser.Package newPkg;
17756        try {
17757            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
17758                0 /* currentTime */, null);
17759        } catch (PackageManagerException e) {
17760            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17761                    + e.getMessage());
17762            return false;
17763        }
17764
17765        try {
17766            // update shared libraries for the newly re-installed system package
17767            updateSharedLibrariesLPr(newPkg, null);
17768        } catch (PackageManagerException e) {
17769            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17770        }
17771
17772        prepareAppDataAfterInstallLIF(newPkg);
17773
17774        // writer
17775        synchronized (mPackages) {
17776            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
17777
17778            // Propagate the permissions state as we do not want to drop on the floor
17779            // runtime permissions. The update permissions method below will take
17780            // care of removing obsolete permissions and grant install permissions.
17781            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
17782            updatePermissionsLPw(newPkg.packageName, newPkg,
17783                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
17784
17785            if (applyUserRestrictions) {
17786                if (DEBUG_REMOVE) {
17787                    Slog.d(TAG, "Propagating install state across reinstall");
17788                }
17789                for (int userId : allUserHandles) {
17790                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17791                    if (DEBUG_REMOVE) {
17792                        Slog.d(TAG, "    user " + userId + " => " + installed);
17793                    }
17794                    ps.setInstalled(installed, userId);
17795
17796                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17797                }
17798                // Regardless of writeSettings we need to ensure that this restriction
17799                // state propagation is persisted
17800                mSettings.writeAllUsersPackageRestrictionsLPr();
17801            }
17802            // can downgrade to reader here
17803            if (writeSettings) {
17804                mSettings.writeLPr();
17805            }
17806        }
17807        return true;
17808    }
17809
17810    private boolean deleteInstalledPackageLIF(PackageSetting ps,
17811            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
17812            PackageRemovedInfo outInfo, boolean writeSettings,
17813            PackageParser.Package replacingPackage) {
17814        synchronized (mPackages) {
17815            if (outInfo != null) {
17816                outInfo.uid = ps.appId;
17817            }
17818
17819            if (outInfo != null && outInfo.removedChildPackages != null) {
17820                final int childCount = (ps.childPackageNames != null)
17821                        ? ps.childPackageNames.size() : 0;
17822                for (int i = 0; i < childCount; i++) {
17823                    String childPackageName = ps.childPackageNames.get(i);
17824                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
17825                    if (childPs == null) {
17826                        return false;
17827                    }
17828                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17829                            childPackageName);
17830                    if (childInfo != null) {
17831                        childInfo.uid = childPs.appId;
17832                    }
17833                }
17834            }
17835        }
17836
17837        // Delete package data from internal structures and also remove data if flag is set
17838        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
17839
17840        // Delete the child packages data
17841        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17842        for (int i = 0; i < childCount; i++) {
17843            PackageSetting childPs;
17844            synchronized (mPackages) {
17845                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17846            }
17847            if (childPs != null) {
17848                PackageRemovedInfo childOutInfo = (outInfo != null
17849                        && outInfo.removedChildPackages != null)
17850                        ? outInfo.removedChildPackages.get(childPs.name) : null;
17851                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
17852                        && (replacingPackage != null
17853                        && !replacingPackage.hasChildPackage(childPs.name))
17854                        ? flags & ~DELETE_KEEP_DATA : flags;
17855                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
17856                        deleteFlags, writeSettings);
17857            }
17858        }
17859
17860        // Delete application code and resources only for parent packages
17861        if (ps.parentPackageName == null) {
17862            if (deleteCodeAndResources && (outInfo != null)) {
17863                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
17864                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
17865                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
17866            }
17867        }
17868
17869        return true;
17870    }
17871
17872    @Override
17873    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
17874            int userId) {
17875        mContext.enforceCallingOrSelfPermission(
17876                android.Manifest.permission.DELETE_PACKAGES, null);
17877        synchronized (mPackages) {
17878            PackageSetting ps = mSettings.mPackages.get(packageName);
17879            if (ps == null) {
17880                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
17881                return false;
17882            }
17883            // Cannot block uninstall of static shared libs as they are
17884            // considered a part of the using app (emulating static linking).
17885            // Also static libs are installed always on internal storage.
17886            PackageParser.Package pkg = mPackages.get(packageName);
17887            if (pkg != null && pkg.staticSharedLibName != null) {
17888                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
17889                        + " providing static shared library: " + pkg.staticSharedLibName);
17890                return false;
17891            }
17892            if (!ps.getInstalled(userId)) {
17893                // Can't block uninstall for an app that is not installed or enabled.
17894                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
17895                return false;
17896            }
17897            ps.setBlockUninstall(blockUninstall, userId);
17898            mSettings.writePackageRestrictionsLPr(userId);
17899        }
17900        return true;
17901    }
17902
17903    @Override
17904    public boolean getBlockUninstallForUser(String packageName, int userId) {
17905        synchronized (mPackages) {
17906            PackageSetting ps = mSettings.mPackages.get(packageName);
17907            if (ps == null) {
17908                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
17909                return false;
17910            }
17911            return ps.getBlockUninstall(userId);
17912        }
17913    }
17914
17915    @Override
17916    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
17917        int callingUid = Binder.getCallingUid();
17918        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
17919            throw new SecurityException(
17920                    "setRequiredForSystemUser can only be run by the system or root");
17921        }
17922        synchronized (mPackages) {
17923            PackageSetting ps = mSettings.mPackages.get(packageName);
17924            if (ps == null) {
17925                Log.w(TAG, "Package doesn't exist: " + packageName);
17926                return false;
17927            }
17928            if (systemUserApp) {
17929                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
17930            } else {
17931                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
17932            }
17933            mSettings.writeLPr();
17934        }
17935        return true;
17936    }
17937
17938    /*
17939     * This method handles package deletion in general
17940     */
17941    private boolean deletePackageLIF(String packageName, UserHandle user,
17942            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
17943            PackageRemovedInfo outInfo, boolean writeSettings,
17944            PackageParser.Package replacingPackage) {
17945        if (packageName == null) {
17946            Slog.w(TAG, "Attempt to delete null packageName.");
17947            return false;
17948        }
17949
17950        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
17951
17952        PackageSetting ps;
17953        synchronized (mPackages) {
17954            ps = mSettings.mPackages.get(packageName);
17955            if (ps == null) {
17956                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
17957                return false;
17958            }
17959
17960            if (ps.parentPackageName != null && (!isSystemApp(ps)
17961                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
17962                if (DEBUG_REMOVE) {
17963                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
17964                            + ((user == null) ? UserHandle.USER_ALL : user));
17965                }
17966                final int removedUserId = (user != null) ? user.getIdentifier()
17967                        : UserHandle.USER_ALL;
17968                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
17969                    return false;
17970                }
17971                markPackageUninstalledForUserLPw(ps, user);
17972                scheduleWritePackageRestrictionsLocked(user);
17973                return true;
17974            }
17975        }
17976
17977        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
17978                && user.getIdentifier() != UserHandle.USER_ALL)) {
17979            // The caller is asking that the package only be deleted for a single
17980            // user.  To do this, we just mark its uninstalled state and delete
17981            // its data. If this is a system app, we only allow this to happen if
17982            // they have set the special DELETE_SYSTEM_APP which requests different
17983            // semantics than normal for uninstalling system apps.
17984            markPackageUninstalledForUserLPw(ps, user);
17985
17986            if (!isSystemApp(ps)) {
17987                // Do not uninstall the APK if an app should be cached
17988                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
17989                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
17990                    // Other user still have this package installed, so all
17991                    // we need to do is clear this user's data and save that
17992                    // it is uninstalled.
17993                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
17994                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
17995                        return false;
17996                    }
17997                    scheduleWritePackageRestrictionsLocked(user);
17998                    return true;
17999                } else {
18000                    // We need to set it back to 'installed' so the uninstall
18001                    // broadcasts will be sent correctly.
18002                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18003                    ps.setInstalled(true, user.getIdentifier());
18004                }
18005            } else {
18006                // This is a system app, so we assume that the
18007                // other users still have this package installed, so all
18008                // we need to do is clear this user's data and save that
18009                // it is uninstalled.
18010                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18011                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18012                    return false;
18013                }
18014                scheduleWritePackageRestrictionsLocked(user);
18015                return true;
18016            }
18017        }
18018
18019        // If we are deleting a composite package for all users, keep track
18020        // of result for each child.
18021        if (ps.childPackageNames != null && outInfo != null) {
18022            synchronized (mPackages) {
18023                final int childCount = ps.childPackageNames.size();
18024                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18025                for (int i = 0; i < childCount; i++) {
18026                    String childPackageName = ps.childPackageNames.get(i);
18027                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
18028                    childInfo.removedPackage = childPackageName;
18029                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18030                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18031                    if (childPs != null) {
18032                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18033                    }
18034                }
18035            }
18036        }
18037
18038        boolean ret = false;
18039        if (isSystemApp(ps)) {
18040            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18041            // When an updated system application is deleted we delete the existing resources
18042            // as well and fall back to existing code in system partition
18043            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18044        } else {
18045            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18046            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18047                    outInfo, writeSettings, replacingPackage);
18048        }
18049
18050        // Take a note whether we deleted the package for all users
18051        if (outInfo != null) {
18052            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18053            if (outInfo.removedChildPackages != null) {
18054                synchronized (mPackages) {
18055                    final int childCount = outInfo.removedChildPackages.size();
18056                    for (int i = 0; i < childCount; i++) {
18057                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18058                        if (childInfo != null) {
18059                            childInfo.removedForAllUsers = mPackages.get(
18060                                    childInfo.removedPackage) == null;
18061                        }
18062                    }
18063                }
18064            }
18065            // If we uninstalled an update to a system app there may be some
18066            // child packages that appeared as they are declared in the system
18067            // app but were not declared in the update.
18068            if (isSystemApp(ps)) {
18069                synchronized (mPackages) {
18070                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18071                    final int childCount = (updatedPs.childPackageNames != null)
18072                            ? updatedPs.childPackageNames.size() : 0;
18073                    for (int i = 0; i < childCount; i++) {
18074                        String childPackageName = updatedPs.childPackageNames.get(i);
18075                        if (outInfo.removedChildPackages == null
18076                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18077                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18078                            if (childPs == null) {
18079                                continue;
18080                            }
18081                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18082                            installRes.name = childPackageName;
18083                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18084                            installRes.pkg = mPackages.get(childPackageName);
18085                            installRes.uid = childPs.pkg.applicationInfo.uid;
18086                            if (outInfo.appearedChildPackages == null) {
18087                                outInfo.appearedChildPackages = new ArrayMap<>();
18088                            }
18089                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18090                        }
18091                    }
18092                }
18093            }
18094        }
18095
18096        return ret;
18097    }
18098
18099    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18100        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18101                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18102        for (int nextUserId : userIds) {
18103            if (DEBUG_REMOVE) {
18104                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18105            }
18106            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18107                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
18108                    false /*hidden*/, false /*suspended*/, null, null, null,
18109                    false /*blockUninstall*/,
18110                    ps.readUserState(nextUserId).domainVerificationStatus, 0,
18111                    PackageManager.INSTALL_REASON_UNKNOWN);
18112        }
18113    }
18114
18115    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18116            PackageRemovedInfo outInfo) {
18117        final PackageParser.Package pkg;
18118        synchronized (mPackages) {
18119            pkg = mPackages.get(ps.name);
18120        }
18121
18122        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18123                : new int[] {userId};
18124        for (int nextUserId : userIds) {
18125            if (DEBUG_REMOVE) {
18126                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18127                        + nextUserId);
18128            }
18129
18130            destroyAppDataLIF(pkg, userId,
18131                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18132            destroyAppProfilesLIF(pkg, userId);
18133            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18134            schedulePackageCleaning(ps.name, nextUserId, false);
18135            synchronized (mPackages) {
18136                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18137                    scheduleWritePackageRestrictionsLocked(nextUserId);
18138                }
18139                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18140            }
18141        }
18142
18143        if (outInfo != null) {
18144            outInfo.removedPackage = ps.name;
18145            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18146            outInfo.removedAppId = ps.appId;
18147            outInfo.removedUsers = userIds;
18148        }
18149
18150        return true;
18151    }
18152
18153    private final class ClearStorageConnection implements ServiceConnection {
18154        IMediaContainerService mContainerService;
18155
18156        @Override
18157        public void onServiceConnected(ComponentName name, IBinder service) {
18158            synchronized (this) {
18159                mContainerService = IMediaContainerService.Stub
18160                        .asInterface(Binder.allowBlocking(service));
18161                notifyAll();
18162            }
18163        }
18164
18165        @Override
18166        public void onServiceDisconnected(ComponentName name) {
18167        }
18168    }
18169
18170    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18171        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18172
18173        final boolean mounted;
18174        if (Environment.isExternalStorageEmulated()) {
18175            mounted = true;
18176        } else {
18177            final String status = Environment.getExternalStorageState();
18178
18179            mounted = status.equals(Environment.MEDIA_MOUNTED)
18180                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18181        }
18182
18183        if (!mounted) {
18184            return;
18185        }
18186
18187        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18188        int[] users;
18189        if (userId == UserHandle.USER_ALL) {
18190            users = sUserManager.getUserIds();
18191        } else {
18192            users = new int[] { userId };
18193        }
18194        final ClearStorageConnection conn = new ClearStorageConnection();
18195        if (mContext.bindServiceAsUser(
18196                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18197            try {
18198                for (int curUser : users) {
18199                    long timeout = SystemClock.uptimeMillis() + 5000;
18200                    synchronized (conn) {
18201                        long now;
18202                        while (conn.mContainerService == null &&
18203                                (now = SystemClock.uptimeMillis()) < timeout) {
18204                            try {
18205                                conn.wait(timeout - now);
18206                            } catch (InterruptedException e) {
18207                            }
18208                        }
18209                    }
18210                    if (conn.mContainerService == null) {
18211                        return;
18212                    }
18213
18214                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18215                    clearDirectory(conn.mContainerService,
18216                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18217                    if (allData) {
18218                        clearDirectory(conn.mContainerService,
18219                                userEnv.buildExternalStorageAppDataDirs(packageName));
18220                        clearDirectory(conn.mContainerService,
18221                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18222                    }
18223                }
18224            } finally {
18225                mContext.unbindService(conn);
18226            }
18227        }
18228    }
18229
18230    @Override
18231    public void clearApplicationProfileData(String packageName) {
18232        enforceSystemOrRoot("Only the system can clear all profile data");
18233
18234        final PackageParser.Package pkg;
18235        synchronized (mPackages) {
18236            pkg = mPackages.get(packageName);
18237        }
18238
18239        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18240            synchronized (mInstallLock) {
18241                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18242                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
18243                        true /* removeBaseMarker */);
18244            }
18245        }
18246    }
18247
18248    @Override
18249    public void clearApplicationUserData(final String packageName,
18250            final IPackageDataObserver observer, final int userId) {
18251        mContext.enforceCallingOrSelfPermission(
18252                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18253
18254        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18255                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18256
18257        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18258            throw new SecurityException("Cannot clear data for a protected package: "
18259                    + packageName);
18260        }
18261        // Queue up an async operation since the package deletion may take a little while.
18262        mHandler.post(new Runnable() {
18263            public void run() {
18264                mHandler.removeCallbacks(this);
18265                final boolean succeeded;
18266                try (PackageFreezer freezer = freezePackage(packageName,
18267                        "clearApplicationUserData")) {
18268                    synchronized (mInstallLock) {
18269                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18270                    }
18271                    clearExternalStorageDataSync(packageName, userId, true);
18272                    synchronized (mPackages) {
18273                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18274                                packageName, userId);
18275                    }
18276                }
18277                if (succeeded) {
18278                    // invoke DeviceStorageMonitor's update method to clear any notifications
18279                    DeviceStorageMonitorInternal dsm = LocalServices
18280                            .getService(DeviceStorageMonitorInternal.class);
18281                    if (dsm != null) {
18282                        dsm.checkMemory();
18283                    }
18284                }
18285                if(observer != null) {
18286                    try {
18287                        observer.onRemoveCompleted(packageName, succeeded);
18288                    } catch (RemoteException e) {
18289                        Log.i(TAG, "Observer no longer exists.");
18290                    }
18291                } //end if observer
18292            } //end run
18293        });
18294    }
18295
18296    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18297        if (packageName == null) {
18298            Slog.w(TAG, "Attempt to delete null packageName.");
18299            return false;
18300        }
18301
18302        // Try finding details about the requested package
18303        PackageParser.Package pkg;
18304        synchronized (mPackages) {
18305            pkg = mPackages.get(packageName);
18306            if (pkg == null) {
18307                final PackageSetting ps = mSettings.mPackages.get(packageName);
18308                if (ps != null) {
18309                    pkg = ps.pkg;
18310                }
18311            }
18312
18313            if (pkg == null) {
18314                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18315                return false;
18316            }
18317
18318            PackageSetting ps = (PackageSetting) pkg.mExtras;
18319            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18320        }
18321
18322        clearAppDataLIF(pkg, userId,
18323                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18324
18325        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18326        removeKeystoreDataIfNeeded(userId, appId);
18327
18328        UserManagerInternal umInternal = getUserManagerInternal();
18329        final int flags;
18330        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18331            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18332        } else if (umInternal.isUserRunning(userId)) {
18333            flags = StorageManager.FLAG_STORAGE_DE;
18334        } else {
18335            flags = 0;
18336        }
18337        prepareAppDataContentsLIF(pkg, userId, flags);
18338
18339        return true;
18340    }
18341
18342    /**
18343     * Reverts user permission state changes (permissions and flags) in
18344     * all packages for a given user.
18345     *
18346     * @param userId The device user for which to do a reset.
18347     */
18348    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18349        final int packageCount = mPackages.size();
18350        for (int i = 0; i < packageCount; i++) {
18351            PackageParser.Package pkg = mPackages.valueAt(i);
18352            PackageSetting ps = (PackageSetting) pkg.mExtras;
18353            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18354        }
18355    }
18356
18357    private void resetNetworkPolicies(int userId) {
18358        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18359    }
18360
18361    /**
18362     * Reverts user permission state changes (permissions and flags).
18363     *
18364     * @param ps The package for which to reset.
18365     * @param userId The device user for which to do a reset.
18366     */
18367    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18368            final PackageSetting ps, final int userId) {
18369        if (ps.pkg == null) {
18370            return;
18371        }
18372
18373        // These are flags that can change base on user actions.
18374        final int userSettableMask = FLAG_PERMISSION_USER_SET
18375                | FLAG_PERMISSION_USER_FIXED
18376                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18377                | FLAG_PERMISSION_REVIEW_REQUIRED;
18378
18379        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18380                | FLAG_PERMISSION_POLICY_FIXED;
18381
18382        boolean writeInstallPermissions = false;
18383        boolean writeRuntimePermissions = false;
18384
18385        final int permissionCount = ps.pkg.requestedPermissions.size();
18386        for (int i = 0; i < permissionCount; i++) {
18387            String permission = ps.pkg.requestedPermissions.get(i);
18388
18389            BasePermission bp = mSettings.mPermissions.get(permission);
18390            if (bp == null) {
18391                continue;
18392            }
18393
18394            // If shared user we just reset the state to which only this app contributed.
18395            if (ps.sharedUser != null) {
18396                boolean used = false;
18397                final int packageCount = ps.sharedUser.packages.size();
18398                for (int j = 0; j < packageCount; j++) {
18399                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18400                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18401                            && pkg.pkg.requestedPermissions.contains(permission)) {
18402                        used = true;
18403                        break;
18404                    }
18405                }
18406                if (used) {
18407                    continue;
18408                }
18409            }
18410
18411            PermissionsState permissionsState = ps.getPermissionsState();
18412
18413            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
18414
18415            // Always clear the user settable flags.
18416            final boolean hasInstallState = permissionsState.getInstallPermissionState(
18417                    bp.name) != null;
18418            // If permission review is enabled and this is a legacy app, mark the
18419            // permission as requiring a review as this is the initial state.
18420            int flags = 0;
18421            if (mPermissionReviewRequired
18422                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18423                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18424            }
18425            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18426                if (hasInstallState) {
18427                    writeInstallPermissions = true;
18428                } else {
18429                    writeRuntimePermissions = true;
18430                }
18431            }
18432
18433            // Below is only runtime permission handling.
18434            if (!bp.isRuntime()) {
18435                continue;
18436            }
18437
18438            // Never clobber system or policy.
18439            if ((oldFlags & policyOrSystemFlags) != 0) {
18440                continue;
18441            }
18442
18443            // If this permission was granted by default, make sure it is.
18444            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18445                if (permissionsState.grantRuntimePermission(bp, userId)
18446                        != PERMISSION_OPERATION_FAILURE) {
18447                    writeRuntimePermissions = true;
18448                }
18449            // If permission review is enabled the permissions for a legacy apps
18450            // are represented as constantly granted runtime ones, so don't revoke.
18451            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18452                // Otherwise, reset the permission.
18453                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18454                switch (revokeResult) {
18455                    case PERMISSION_OPERATION_SUCCESS:
18456                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18457                        writeRuntimePermissions = true;
18458                        final int appId = ps.appId;
18459                        mHandler.post(new Runnable() {
18460                            @Override
18461                            public void run() {
18462                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18463                            }
18464                        });
18465                    } break;
18466                }
18467            }
18468        }
18469
18470        // Synchronously write as we are taking permissions away.
18471        if (writeRuntimePermissions) {
18472            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18473        }
18474
18475        // Synchronously write as we are taking permissions away.
18476        if (writeInstallPermissions) {
18477            mSettings.writeLPr();
18478        }
18479    }
18480
18481    /**
18482     * Remove entries from the keystore daemon. Will only remove it if the
18483     * {@code appId} is valid.
18484     */
18485    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18486        if (appId < 0) {
18487            return;
18488        }
18489
18490        final KeyStore keyStore = KeyStore.getInstance();
18491        if (keyStore != null) {
18492            if (userId == UserHandle.USER_ALL) {
18493                for (final int individual : sUserManager.getUserIds()) {
18494                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18495                }
18496            } else {
18497                keyStore.clearUid(UserHandle.getUid(userId, appId));
18498            }
18499        } else {
18500            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18501        }
18502    }
18503
18504    @Override
18505    public void deleteApplicationCacheFiles(final String packageName,
18506            final IPackageDataObserver observer) {
18507        final int userId = UserHandle.getCallingUserId();
18508        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18509    }
18510
18511    @Override
18512    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18513            final IPackageDataObserver observer) {
18514        mContext.enforceCallingOrSelfPermission(
18515                android.Manifest.permission.DELETE_CACHE_FILES, null);
18516        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18517                /* requireFullPermission= */ true, /* checkShell= */ false,
18518                "delete application cache files");
18519
18520        final PackageParser.Package pkg;
18521        synchronized (mPackages) {
18522            pkg = mPackages.get(packageName);
18523        }
18524
18525        // Queue up an async operation since the package deletion may take a little while.
18526        mHandler.post(new Runnable() {
18527            public void run() {
18528                synchronized (mInstallLock) {
18529                    final int flags = StorageManager.FLAG_STORAGE_DE
18530                            | StorageManager.FLAG_STORAGE_CE;
18531                    // We're only clearing cache files, so we don't care if the
18532                    // app is unfrozen and still able to run
18533                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18534                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18535                }
18536                clearExternalStorageDataSync(packageName, userId, false);
18537                if (observer != null) {
18538                    try {
18539                        observer.onRemoveCompleted(packageName, true);
18540                    } catch (RemoteException e) {
18541                        Log.i(TAG, "Observer no longer exists.");
18542                    }
18543                }
18544            }
18545        });
18546    }
18547
18548    @Override
18549    public void getPackageSizeInfo(final String packageName, int userHandle,
18550            final IPackageStatsObserver observer) {
18551        mContext.enforceCallingOrSelfPermission(
18552                android.Manifest.permission.GET_PACKAGE_SIZE, null);
18553        if (packageName == null) {
18554            throw new IllegalArgumentException("Attempt to get size of null packageName");
18555        }
18556
18557        PackageStats stats = new PackageStats(packageName, userHandle);
18558
18559        /*
18560         * Queue up an async operation since the package measurement may take a
18561         * little while.
18562         */
18563        Message msg = mHandler.obtainMessage(INIT_COPY);
18564        msg.obj = new MeasureParams(stats, observer);
18565        mHandler.sendMessage(msg);
18566    }
18567
18568    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18569        final PackageSetting ps;
18570        synchronized (mPackages) {
18571            ps = mSettings.mPackages.get(packageName);
18572            if (ps == null) {
18573                Slog.w(TAG, "Failed to find settings for " + packageName);
18574                return false;
18575            }
18576        }
18577
18578        final String[] packageNames = { packageName };
18579        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18580        final String[] codePaths = { ps.codePathString };
18581
18582        try {
18583            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18584                    ps.appId, ceDataInodes, codePaths, stats);
18585
18586            // For now, ignore code size of packages on system partition
18587            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18588                stats.codeSize = 0;
18589            }
18590
18591            // External clients expect these to be tracked separately
18592            stats.dataSize -= stats.cacheSize;
18593
18594        } catch (InstallerException e) {
18595            Slog.w(TAG, String.valueOf(e));
18596            return false;
18597        }
18598
18599        return true;
18600    }
18601
18602    private int getUidTargetSdkVersionLockedLPr(int uid) {
18603        Object obj = mSettings.getUserIdLPr(uid);
18604        if (obj instanceof SharedUserSetting) {
18605            final SharedUserSetting sus = (SharedUserSetting) obj;
18606            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18607            final Iterator<PackageSetting> it = sus.packages.iterator();
18608            while (it.hasNext()) {
18609                final PackageSetting ps = it.next();
18610                if (ps.pkg != null) {
18611                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18612                    if (v < vers) vers = v;
18613                }
18614            }
18615            return vers;
18616        } else if (obj instanceof PackageSetting) {
18617            final PackageSetting ps = (PackageSetting) obj;
18618            if (ps.pkg != null) {
18619                return ps.pkg.applicationInfo.targetSdkVersion;
18620            }
18621        }
18622        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18623    }
18624
18625    @Override
18626    public void addPreferredActivity(IntentFilter filter, int match,
18627            ComponentName[] set, ComponentName activity, int userId) {
18628        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18629                "Adding preferred");
18630    }
18631
18632    private void addPreferredActivityInternal(IntentFilter filter, int match,
18633            ComponentName[] set, ComponentName activity, boolean always, int userId,
18634            String opname) {
18635        // writer
18636        int callingUid = Binder.getCallingUid();
18637        enforceCrossUserPermission(callingUid, userId,
18638                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18639        if (filter.countActions() == 0) {
18640            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18641            return;
18642        }
18643        synchronized (mPackages) {
18644            if (mContext.checkCallingOrSelfPermission(
18645                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18646                    != PackageManager.PERMISSION_GRANTED) {
18647                if (getUidTargetSdkVersionLockedLPr(callingUid)
18648                        < Build.VERSION_CODES.FROYO) {
18649                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18650                            + callingUid);
18651                    return;
18652                }
18653                mContext.enforceCallingOrSelfPermission(
18654                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18655            }
18656
18657            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18658            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18659                    + userId + ":");
18660            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18661            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18662            scheduleWritePackageRestrictionsLocked(userId);
18663            postPreferredActivityChangedBroadcast(userId);
18664        }
18665    }
18666
18667    private void postPreferredActivityChangedBroadcast(int userId) {
18668        mHandler.post(() -> {
18669            final IActivityManager am = ActivityManager.getService();
18670            if (am == null) {
18671                return;
18672            }
18673
18674            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18675            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18676            try {
18677                am.broadcastIntent(null, intent, null, null,
18678                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18679                        null, false, false, userId);
18680            } catch (RemoteException e) {
18681            }
18682        });
18683    }
18684
18685    @Override
18686    public void replacePreferredActivity(IntentFilter filter, int match,
18687            ComponentName[] set, ComponentName activity, int userId) {
18688        if (filter.countActions() != 1) {
18689            throw new IllegalArgumentException(
18690                    "replacePreferredActivity expects filter to have only 1 action.");
18691        }
18692        if (filter.countDataAuthorities() != 0
18693                || filter.countDataPaths() != 0
18694                || filter.countDataSchemes() > 1
18695                || filter.countDataTypes() != 0) {
18696            throw new IllegalArgumentException(
18697                    "replacePreferredActivity expects filter to have no data authorities, " +
18698                    "paths, or types; and at most one scheme.");
18699        }
18700
18701        final int callingUid = Binder.getCallingUid();
18702        enforceCrossUserPermission(callingUid, userId,
18703                true /* requireFullPermission */, false /* checkShell */,
18704                "replace preferred activity");
18705        synchronized (mPackages) {
18706            if (mContext.checkCallingOrSelfPermission(
18707                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18708                    != PackageManager.PERMISSION_GRANTED) {
18709                if (getUidTargetSdkVersionLockedLPr(callingUid)
18710                        < Build.VERSION_CODES.FROYO) {
18711                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18712                            + Binder.getCallingUid());
18713                    return;
18714                }
18715                mContext.enforceCallingOrSelfPermission(
18716                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18717            }
18718
18719            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18720            if (pir != null) {
18721                // Get all of the existing entries that exactly match this filter.
18722                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18723                if (existing != null && existing.size() == 1) {
18724                    PreferredActivity cur = existing.get(0);
18725                    if (DEBUG_PREFERRED) {
18726                        Slog.i(TAG, "Checking replace of preferred:");
18727                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18728                        if (!cur.mPref.mAlways) {
18729                            Slog.i(TAG, "  -- CUR; not mAlways!");
18730                        } else {
18731                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18732                            Slog.i(TAG, "  -- CUR: mSet="
18733                                    + Arrays.toString(cur.mPref.mSetComponents));
18734                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18735                            Slog.i(TAG, "  -- NEW: mMatch="
18736                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18737                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18738                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18739                        }
18740                    }
18741                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18742                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18743                            && cur.mPref.sameSet(set)) {
18744                        // Setting the preferred activity to what it happens to be already
18745                        if (DEBUG_PREFERRED) {
18746                            Slog.i(TAG, "Replacing with same preferred activity "
18747                                    + cur.mPref.mShortComponent + " for user "
18748                                    + userId + ":");
18749                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18750                        }
18751                        return;
18752                    }
18753                }
18754
18755                if (existing != null) {
18756                    if (DEBUG_PREFERRED) {
18757                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
18758                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18759                    }
18760                    for (int i = 0; i < existing.size(); i++) {
18761                        PreferredActivity pa = existing.get(i);
18762                        if (DEBUG_PREFERRED) {
18763                            Slog.i(TAG, "Removing existing preferred activity "
18764                                    + pa.mPref.mComponent + ":");
18765                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
18766                        }
18767                        pir.removeFilter(pa);
18768                    }
18769                }
18770            }
18771            addPreferredActivityInternal(filter, match, set, activity, true, userId,
18772                    "Replacing preferred");
18773        }
18774    }
18775
18776    @Override
18777    public void clearPackagePreferredActivities(String packageName) {
18778        final int uid = Binder.getCallingUid();
18779        // writer
18780        synchronized (mPackages) {
18781            PackageParser.Package pkg = mPackages.get(packageName);
18782            if (pkg == null || pkg.applicationInfo.uid != uid) {
18783                if (mContext.checkCallingOrSelfPermission(
18784                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18785                        != PackageManager.PERMISSION_GRANTED) {
18786                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
18787                            < Build.VERSION_CODES.FROYO) {
18788                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
18789                                + Binder.getCallingUid());
18790                        return;
18791                    }
18792                    mContext.enforceCallingOrSelfPermission(
18793                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18794                }
18795            }
18796
18797            int user = UserHandle.getCallingUserId();
18798            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
18799                scheduleWritePackageRestrictionsLocked(user);
18800            }
18801        }
18802    }
18803
18804    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18805    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
18806        ArrayList<PreferredActivity> removed = null;
18807        boolean changed = false;
18808        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18809            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
18810            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18811            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
18812                continue;
18813            }
18814            Iterator<PreferredActivity> it = pir.filterIterator();
18815            while (it.hasNext()) {
18816                PreferredActivity pa = it.next();
18817                // Mark entry for removal only if it matches the package name
18818                // and the entry is of type "always".
18819                if (packageName == null ||
18820                        (pa.mPref.mComponent.getPackageName().equals(packageName)
18821                                && pa.mPref.mAlways)) {
18822                    if (removed == null) {
18823                        removed = new ArrayList<PreferredActivity>();
18824                    }
18825                    removed.add(pa);
18826                }
18827            }
18828            if (removed != null) {
18829                for (int j=0; j<removed.size(); j++) {
18830                    PreferredActivity pa = removed.get(j);
18831                    pir.removeFilter(pa);
18832                }
18833                changed = true;
18834            }
18835        }
18836        if (changed) {
18837            postPreferredActivityChangedBroadcast(userId);
18838        }
18839        return changed;
18840    }
18841
18842    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18843    private void clearIntentFilterVerificationsLPw(int userId) {
18844        final int packageCount = mPackages.size();
18845        for (int i = 0; i < packageCount; i++) {
18846            PackageParser.Package pkg = mPackages.valueAt(i);
18847            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
18848        }
18849    }
18850
18851    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18852    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
18853        if (userId == UserHandle.USER_ALL) {
18854            if (mSettings.removeIntentFilterVerificationLPw(packageName,
18855                    sUserManager.getUserIds())) {
18856                for (int oneUserId : sUserManager.getUserIds()) {
18857                    scheduleWritePackageRestrictionsLocked(oneUserId);
18858                }
18859            }
18860        } else {
18861            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
18862                scheduleWritePackageRestrictionsLocked(userId);
18863            }
18864        }
18865    }
18866
18867    void clearDefaultBrowserIfNeeded(String packageName) {
18868        for (int oneUserId : sUserManager.getUserIds()) {
18869            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
18870            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
18871            if (packageName.equals(defaultBrowserPackageName)) {
18872                setDefaultBrowserPackageName(null, oneUserId);
18873            }
18874        }
18875    }
18876
18877    @Override
18878    public void resetApplicationPreferences(int userId) {
18879        mContext.enforceCallingOrSelfPermission(
18880                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18881        final long identity = Binder.clearCallingIdentity();
18882        // writer
18883        try {
18884            synchronized (mPackages) {
18885                clearPackagePreferredActivitiesLPw(null, userId);
18886                mSettings.applyDefaultPreferredAppsLPw(this, userId);
18887                // TODO: We have to reset the default SMS and Phone. This requires
18888                // significant refactoring to keep all default apps in the package
18889                // manager (cleaner but more work) or have the services provide
18890                // callbacks to the package manager to request a default app reset.
18891                applyFactoryDefaultBrowserLPw(userId);
18892                clearIntentFilterVerificationsLPw(userId);
18893                primeDomainVerificationsLPw(userId);
18894                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
18895                scheduleWritePackageRestrictionsLocked(userId);
18896            }
18897            resetNetworkPolicies(userId);
18898        } finally {
18899            Binder.restoreCallingIdentity(identity);
18900        }
18901    }
18902
18903    @Override
18904    public int getPreferredActivities(List<IntentFilter> outFilters,
18905            List<ComponentName> outActivities, String packageName) {
18906
18907        int num = 0;
18908        final int userId = UserHandle.getCallingUserId();
18909        // reader
18910        synchronized (mPackages) {
18911            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18912            if (pir != null) {
18913                final Iterator<PreferredActivity> it = pir.filterIterator();
18914                while (it.hasNext()) {
18915                    final PreferredActivity pa = it.next();
18916                    if (packageName == null
18917                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
18918                                    && pa.mPref.mAlways)) {
18919                        if (outFilters != null) {
18920                            outFilters.add(new IntentFilter(pa));
18921                        }
18922                        if (outActivities != null) {
18923                            outActivities.add(pa.mPref.mComponent);
18924                        }
18925                    }
18926                }
18927            }
18928        }
18929
18930        return num;
18931    }
18932
18933    @Override
18934    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
18935            int userId) {
18936        int callingUid = Binder.getCallingUid();
18937        if (callingUid != Process.SYSTEM_UID) {
18938            throw new SecurityException(
18939                    "addPersistentPreferredActivity can only be run by the system");
18940        }
18941        if (filter.countActions() == 0) {
18942            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18943            return;
18944        }
18945        synchronized (mPackages) {
18946            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
18947                    ":");
18948            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18949            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
18950                    new PersistentPreferredActivity(filter, activity));
18951            scheduleWritePackageRestrictionsLocked(userId);
18952            postPreferredActivityChangedBroadcast(userId);
18953        }
18954    }
18955
18956    @Override
18957    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
18958        int callingUid = Binder.getCallingUid();
18959        if (callingUid != Process.SYSTEM_UID) {
18960            throw new SecurityException(
18961                    "clearPackagePersistentPreferredActivities can only be run by the system");
18962        }
18963        ArrayList<PersistentPreferredActivity> removed = null;
18964        boolean changed = false;
18965        synchronized (mPackages) {
18966            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
18967                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
18968                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
18969                        .valueAt(i);
18970                if (userId != thisUserId) {
18971                    continue;
18972                }
18973                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
18974                while (it.hasNext()) {
18975                    PersistentPreferredActivity ppa = it.next();
18976                    // Mark entry for removal only if it matches the package name.
18977                    if (ppa.mComponent.getPackageName().equals(packageName)) {
18978                        if (removed == null) {
18979                            removed = new ArrayList<PersistentPreferredActivity>();
18980                        }
18981                        removed.add(ppa);
18982                    }
18983                }
18984                if (removed != null) {
18985                    for (int j=0; j<removed.size(); j++) {
18986                        PersistentPreferredActivity ppa = removed.get(j);
18987                        ppir.removeFilter(ppa);
18988                    }
18989                    changed = true;
18990                }
18991            }
18992
18993            if (changed) {
18994                scheduleWritePackageRestrictionsLocked(userId);
18995                postPreferredActivityChangedBroadcast(userId);
18996            }
18997        }
18998    }
18999
19000    /**
19001     * Common machinery for picking apart a restored XML blob and passing
19002     * it to a caller-supplied functor to be applied to the running system.
19003     */
19004    private void restoreFromXml(XmlPullParser parser, int userId,
19005            String expectedStartTag, BlobXmlRestorer functor)
19006            throws IOException, XmlPullParserException {
19007        int type;
19008        while ((type = parser.next()) != XmlPullParser.START_TAG
19009                && type != XmlPullParser.END_DOCUMENT) {
19010        }
19011        if (type != XmlPullParser.START_TAG) {
19012            // oops didn't find a start tag?!
19013            if (DEBUG_BACKUP) {
19014                Slog.e(TAG, "Didn't find start tag during restore");
19015            }
19016            return;
19017        }
19018Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19019        // this is supposed to be TAG_PREFERRED_BACKUP
19020        if (!expectedStartTag.equals(parser.getName())) {
19021            if (DEBUG_BACKUP) {
19022                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19023            }
19024            return;
19025        }
19026
19027        // skip interfering stuff, then we're aligned with the backing implementation
19028        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19029Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19030        functor.apply(parser, userId);
19031    }
19032
19033    private interface BlobXmlRestorer {
19034        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19035    }
19036
19037    /**
19038     * Non-Binder method, support for the backup/restore mechanism: write the
19039     * full set of preferred activities in its canonical XML format.  Returns the
19040     * XML output as a byte array, or null if there is none.
19041     */
19042    @Override
19043    public byte[] getPreferredActivityBackup(int userId) {
19044        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19045            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19046        }
19047
19048        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19049        try {
19050            final XmlSerializer serializer = new FastXmlSerializer();
19051            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19052            serializer.startDocument(null, true);
19053            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19054
19055            synchronized (mPackages) {
19056                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19057            }
19058
19059            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19060            serializer.endDocument();
19061            serializer.flush();
19062        } catch (Exception e) {
19063            if (DEBUG_BACKUP) {
19064                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19065            }
19066            return null;
19067        }
19068
19069        return dataStream.toByteArray();
19070    }
19071
19072    @Override
19073    public void restorePreferredActivities(byte[] backup, int userId) {
19074        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19075            throw new SecurityException("Only the system may call restorePreferredActivities()");
19076        }
19077
19078        try {
19079            final XmlPullParser parser = Xml.newPullParser();
19080            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19081            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19082                    new BlobXmlRestorer() {
19083                        @Override
19084                        public void apply(XmlPullParser parser, int userId)
19085                                throws XmlPullParserException, IOException {
19086                            synchronized (mPackages) {
19087                                mSettings.readPreferredActivitiesLPw(parser, userId);
19088                            }
19089                        }
19090                    } );
19091        } catch (Exception e) {
19092            if (DEBUG_BACKUP) {
19093                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19094            }
19095        }
19096    }
19097
19098    /**
19099     * Non-Binder method, support for the backup/restore mechanism: write the
19100     * default browser (etc) settings in its canonical XML format.  Returns the default
19101     * browser XML representation as a byte array, or null if there is none.
19102     */
19103    @Override
19104    public byte[] getDefaultAppsBackup(int userId) {
19105        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19106            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19107        }
19108
19109        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19110        try {
19111            final XmlSerializer serializer = new FastXmlSerializer();
19112            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19113            serializer.startDocument(null, true);
19114            serializer.startTag(null, TAG_DEFAULT_APPS);
19115
19116            synchronized (mPackages) {
19117                mSettings.writeDefaultAppsLPr(serializer, userId);
19118            }
19119
19120            serializer.endTag(null, TAG_DEFAULT_APPS);
19121            serializer.endDocument();
19122            serializer.flush();
19123        } catch (Exception e) {
19124            if (DEBUG_BACKUP) {
19125                Slog.e(TAG, "Unable to write default apps for backup", e);
19126            }
19127            return null;
19128        }
19129
19130        return dataStream.toByteArray();
19131    }
19132
19133    @Override
19134    public void restoreDefaultApps(byte[] backup, int userId) {
19135        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19136            throw new SecurityException("Only the system may call restoreDefaultApps()");
19137        }
19138
19139        try {
19140            final XmlPullParser parser = Xml.newPullParser();
19141            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19142            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19143                    new BlobXmlRestorer() {
19144                        @Override
19145                        public void apply(XmlPullParser parser, int userId)
19146                                throws XmlPullParserException, IOException {
19147                            synchronized (mPackages) {
19148                                mSettings.readDefaultAppsLPw(parser, userId);
19149                            }
19150                        }
19151                    } );
19152        } catch (Exception e) {
19153            if (DEBUG_BACKUP) {
19154                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19155            }
19156        }
19157    }
19158
19159    @Override
19160    public byte[] getIntentFilterVerificationBackup(int userId) {
19161        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19162            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19163        }
19164
19165        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19166        try {
19167            final XmlSerializer serializer = new FastXmlSerializer();
19168            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19169            serializer.startDocument(null, true);
19170            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19171
19172            synchronized (mPackages) {
19173                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19174            }
19175
19176            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19177            serializer.endDocument();
19178            serializer.flush();
19179        } catch (Exception e) {
19180            if (DEBUG_BACKUP) {
19181                Slog.e(TAG, "Unable to write default apps for backup", e);
19182            }
19183            return null;
19184        }
19185
19186        return dataStream.toByteArray();
19187    }
19188
19189    @Override
19190    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19191        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19192            throw new SecurityException("Only the system may call restorePreferredActivities()");
19193        }
19194
19195        try {
19196            final XmlPullParser parser = Xml.newPullParser();
19197            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19198            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19199                    new BlobXmlRestorer() {
19200                        @Override
19201                        public void apply(XmlPullParser parser, int userId)
19202                                throws XmlPullParserException, IOException {
19203                            synchronized (mPackages) {
19204                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19205                                mSettings.writeLPr();
19206                            }
19207                        }
19208                    } );
19209        } catch (Exception e) {
19210            if (DEBUG_BACKUP) {
19211                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19212            }
19213        }
19214    }
19215
19216    @Override
19217    public byte[] getPermissionGrantBackup(int userId) {
19218        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19219            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19220        }
19221
19222        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19223        try {
19224            final XmlSerializer serializer = new FastXmlSerializer();
19225            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19226            serializer.startDocument(null, true);
19227            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19228
19229            synchronized (mPackages) {
19230                serializeRuntimePermissionGrantsLPr(serializer, userId);
19231            }
19232
19233            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19234            serializer.endDocument();
19235            serializer.flush();
19236        } catch (Exception e) {
19237            if (DEBUG_BACKUP) {
19238                Slog.e(TAG, "Unable to write default apps for backup", e);
19239            }
19240            return null;
19241        }
19242
19243        return dataStream.toByteArray();
19244    }
19245
19246    @Override
19247    public void restorePermissionGrants(byte[] backup, int userId) {
19248        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19249            throw new SecurityException("Only the system may call restorePermissionGrants()");
19250        }
19251
19252        try {
19253            final XmlPullParser parser = Xml.newPullParser();
19254            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19255            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19256                    new BlobXmlRestorer() {
19257                        @Override
19258                        public void apply(XmlPullParser parser, int userId)
19259                                throws XmlPullParserException, IOException {
19260                            synchronized (mPackages) {
19261                                processRestoredPermissionGrantsLPr(parser, userId);
19262                            }
19263                        }
19264                    } );
19265        } catch (Exception e) {
19266            if (DEBUG_BACKUP) {
19267                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19268            }
19269        }
19270    }
19271
19272    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19273            throws IOException {
19274        serializer.startTag(null, TAG_ALL_GRANTS);
19275
19276        final int N = mSettings.mPackages.size();
19277        for (int i = 0; i < N; i++) {
19278            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19279            boolean pkgGrantsKnown = false;
19280
19281            PermissionsState packagePerms = ps.getPermissionsState();
19282
19283            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19284                final int grantFlags = state.getFlags();
19285                // only look at grants that are not system/policy fixed
19286                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19287                    final boolean isGranted = state.isGranted();
19288                    // And only back up the user-twiddled state bits
19289                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19290                        final String packageName = mSettings.mPackages.keyAt(i);
19291                        if (!pkgGrantsKnown) {
19292                            serializer.startTag(null, TAG_GRANT);
19293                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19294                            pkgGrantsKnown = true;
19295                        }
19296
19297                        final boolean userSet =
19298                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19299                        final boolean userFixed =
19300                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19301                        final boolean revoke =
19302                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19303
19304                        serializer.startTag(null, TAG_PERMISSION);
19305                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19306                        if (isGranted) {
19307                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19308                        }
19309                        if (userSet) {
19310                            serializer.attribute(null, ATTR_USER_SET, "true");
19311                        }
19312                        if (userFixed) {
19313                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19314                        }
19315                        if (revoke) {
19316                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19317                        }
19318                        serializer.endTag(null, TAG_PERMISSION);
19319                    }
19320                }
19321            }
19322
19323            if (pkgGrantsKnown) {
19324                serializer.endTag(null, TAG_GRANT);
19325            }
19326        }
19327
19328        serializer.endTag(null, TAG_ALL_GRANTS);
19329    }
19330
19331    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19332            throws XmlPullParserException, IOException {
19333        String pkgName = null;
19334        int outerDepth = parser.getDepth();
19335        int type;
19336        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19337                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19338            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19339                continue;
19340            }
19341
19342            final String tagName = parser.getName();
19343            if (tagName.equals(TAG_GRANT)) {
19344                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19345                if (DEBUG_BACKUP) {
19346                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19347                }
19348            } else if (tagName.equals(TAG_PERMISSION)) {
19349
19350                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19351                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19352
19353                int newFlagSet = 0;
19354                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19355                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19356                }
19357                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19358                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19359                }
19360                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19361                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19362                }
19363                if (DEBUG_BACKUP) {
19364                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
19365                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
19366                }
19367                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19368                if (ps != null) {
19369                    // Already installed so we apply the grant immediately
19370                    if (DEBUG_BACKUP) {
19371                        Slog.v(TAG, "        + already installed; applying");
19372                    }
19373                    PermissionsState perms = ps.getPermissionsState();
19374                    BasePermission bp = mSettings.mPermissions.get(permName);
19375                    if (bp != null) {
19376                        if (isGranted) {
19377                            perms.grantRuntimePermission(bp, userId);
19378                        }
19379                        if (newFlagSet != 0) {
19380                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19381                        }
19382                    }
19383                } else {
19384                    // Need to wait for post-restore install to apply the grant
19385                    if (DEBUG_BACKUP) {
19386                        Slog.v(TAG, "        - not yet installed; saving for later");
19387                    }
19388                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19389                            isGranted, newFlagSet, userId);
19390                }
19391            } else {
19392                PackageManagerService.reportSettingsProblem(Log.WARN,
19393                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19394                XmlUtils.skipCurrentTag(parser);
19395            }
19396        }
19397
19398        scheduleWriteSettingsLocked();
19399        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19400    }
19401
19402    @Override
19403    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19404            int sourceUserId, int targetUserId, int flags) {
19405        mContext.enforceCallingOrSelfPermission(
19406                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19407        int callingUid = Binder.getCallingUid();
19408        enforceOwnerRights(ownerPackage, callingUid);
19409        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19410        if (intentFilter.countActions() == 0) {
19411            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19412            return;
19413        }
19414        synchronized (mPackages) {
19415            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19416                    ownerPackage, targetUserId, flags);
19417            CrossProfileIntentResolver resolver =
19418                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19419            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19420            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19421            if (existing != null) {
19422                int size = existing.size();
19423                for (int i = 0; i < size; i++) {
19424                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19425                        return;
19426                    }
19427                }
19428            }
19429            resolver.addFilter(newFilter);
19430            scheduleWritePackageRestrictionsLocked(sourceUserId);
19431        }
19432    }
19433
19434    @Override
19435    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19436        mContext.enforceCallingOrSelfPermission(
19437                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19438        int callingUid = Binder.getCallingUid();
19439        enforceOwnerRights(ownerPackage, callingUid);
19440        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19441        synchronized (mPackages) {
19442            CrossProfileIntentResolver resolver =
19443                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19444            ArraySet<CrossProfileIntentFilter> set =
19445                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19446            for (CrossProfileIntentFilter filter : set) {
19447                if (filter.getOwnerPackage().equals(ownerPackage)) {
19448                    resolver.removeFilter(filter);
19449                }
19450            }
19451            scheduleWritePackageRestrictionsLocked(sourceUserId);
19452        }
19453    }
19454
19455    // Enforcing that callingUid is owning pkg on userId
19456    private void enforceOwnerRights(String pkg, int callingUid) {
19457        // The system owns everything.
19458        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19459            return;
19460        }
19461        int callingUserId = UserHandle.getUserId(callingUid);
19462        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19463        if (pi == null) {
19464            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19465                    + callingUserId);
19466        }
19467        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19468            throw new SecurityException("Calling uid " + callingUid
19469                    + " does not own package " + pkg);
19470        }
19471    }
19472
19473    @Override
19474    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19475        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19476    }
19477
19478    private Intent getHomeIntent() {
19479        Intent intent = new Intent(Intent.ACTION_MAIN);
19480        intent.addCategory(Intent.CATEGORY_HOME);
19481        intent.addCategory(Intent.CATEGORY_DEFAULT);
19482        return intent;
19483    }
19484
19485    private IntentFilter getHomeFilter() {
19486        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19487        filter.addCategory(Intent.CATEGORY_HOME);
19488        filter.addCategory(Intent.CATEGORY_DEFAULT);
19489        return filter;
19490    }
19491
19492    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19493            int userId) {
19494        Intent intent  = getHomeIntent();
19495        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19496                PackageManager.GET_META_DATA, userId);
19497        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19498                true, false, false, userId);
19499
19500        allHomeCandidates.clear();
19501        if (list != null) {
19502            for (ResolveInfo ri : list) {
19503                allHomeCandidates.add(ri);
19504            }
19505        }
19506        return (preferred == null || preferred.activityInfo == null)
19507                ? null
19508                : new ComponentName(preferred.activityInfo.packageName,
19509                        preferred.activityInfo.name);
19510    }
19511
19512    @Override
19513    public void setHomeActivity(ComponentName comp, int userId) {
19514        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19515        getHomeActivitiesAsUser(homeActivities, userId);
19516
19517        boolean found = false;
19518
19519        final int size = homeActivities.size();
19520        final ComponentName[] set = new ComponentName[size];
19521        for (int i = 0; i < size; i++) {
19522            final ResolveInfo candidate = homeActivities.get(i);
19523            final ActivityInfo info = candidate.activityInfo;
19524            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19525            set[i] = activityName;
19526            if (!found && activityName.equals(comp)) {
19527                found = true;
19528            }
19529        }
19530        if (!found) {
19531            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19532                    + userId);
19533        }
19534        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19535                set, comp, userId);
19536    }
19537
19538    private @Nullable String getSetupWizardPackageName() {
19539        final Intent intent = new Intent(Intent.ACTION_MAIN);
19540        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19541
19542        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19543                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19544                        | MATCH_DISABLED_COMPONENTS,
19545                UserHandle.myUserId());
19546        if (matches.size() == 1) {
19547            return matches.get(0).getComponentInfo().packageName;
19548        } else {
19549            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19550                    + ": matches=" + matches);
19551            return null;
19552        }
19553    }
19554
19555    private @Nullable String getStorageManagerPackageName() {
19556        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19557
19558        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19559                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19560                        | MATCH_DISABLED_COMPONENTS,
19561                UserHandle.myUserId());
19562        if (matches.size() == 1) {
19563            return matches.get(0).getComponentInfo().packageName;
19564        } else {
19565            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19566                    + matches.size() + ": matches=" + matches);
19567            return null;
19568        }
19569    }
19570
19571    @Override
19572    public void setApplicationEnabledSetting(String appPackageName,
19573            int newState, int flags, int userId, String callingPackage) {
19574        if (!sUserManager.exists(userId)) return;
19575        if (callingPackage == null) {
19576            callingPackage = Integer.toString(Binder.getCallingUid());
19577        }
19578        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19579    }
19580
19581    @Override
19582    public void setComponentEnabledSetting(ComponentName componentName,
19583            int newState, int flags, int userId) {
19584        if (!sUserManager.exists(userId)) return;
19585        setEnabledSetting(componentName.getPackageName(),
19586                componentName.getClassName(), newState, flags, userId, null);
19587    }
19588
19589    private void setEnabledSetting(final String packageName, String className, int newState,
19590            final int flags, int userId, String callingPackage) {
19591        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19592              || newState == COMPONENT_ENABLED_STATE_ENABLED
19593              || newState == COMPONENT_ENABLED_STATE_DISABLED
19594              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19595              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19596            throw new IllegalArgumentException("Invalid new component state: "
19597                    + newState);
19598        }
19599        PackageSetting pkgSetting;
19600        final int uid = Binder.getCallingUid();
19601        final int permission;
19602        if (uid == Process.SYSTEM_UID) {
19603            permission = PackageManager.PERMISSION_GRANTED;
19604        } else {
19605            permission = mContext.checkCallingOrSelfPermission(
19606                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19607        }
19608        enforceCrossUserPermission(uid, userId,
19609                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19610        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19611        boolean sendNow = false;
19612        boolean isApp = (className == null);
19613        String componentName = isApp ? packageName : className;
19614        int packageUid = -1;
19615        ArrayList<String> components;
19616
19617        // writer
19618        synchronized (mPackages) {
19619            pkgSetting = mSettings.mPackages.get(packageName);
19620            if (pkgSetting == null) {
19621                if (className == null) {
19622                    throw new IllegalArgumentException("Unknown package: " + packageName);
19623                }
19624                throw new IllegalArgumentException(
19625                        "Unknown component: " + packageName + "/" + className);
19626            }
19627        }
19628
19629        // Limit who can change which apps
19630        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
19631            // Don't allow apps that don't have permission to modify other apps
19632            if (!allowedByPermission) {
19633                throw new SecurityException(
19634                        "Permission Denial: attempt to change component state from pid="
19635                        + Binder.getCallingPid()
19636                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
19637            }
19638            // Don't allow changing protected packages.
19639            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19640                throw new SecurityException("Cannot disable a protected package: " + packageName);
19641            }
19642        }
19643
19644        synchronized (mPackages) {
19645            if (uid == Process.SHELL_UID
19646                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19647                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19648                // unless it is a test package.
19649                int oldState = pkgSetting.getEnabled(userId);
19650                if (className == null
19651                    &&
19652                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19653                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19654                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19655                    &&
19656                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19657                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
19658                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19659                    // ok
19660                } else {
19661                    throw new SecurityException(
19662                            "Shell cannot change component state for " + packageName + "/"
19663                            + className + " to " + newState);
19664                }
19665            }
19666            if (className == null) {
19667                // We're dealing with an application/package level state change
19668                if (pkgSetting.getEnabled(userId) == newState) {
19669                    // Nothing to do
19670                    return;
19671                }
19672                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19673                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
19674                    // Don't care about who enables an app.
19675                    callingPackage = null;
19676                }
19677                pkgSetting.setEnabled(newState, userId, callingPackage);
19678                // pkgSetting.pkg.mSetEnabled = newState;
19679            } else {
19680                // We're dealing with a component level state change
19681                // First, verify that this is a valid class name.
19682                PackageParser.Package pkg = pkgSetting.pkg;
19683                if (pkg == null || !pkg.hasComponentClassName(className)) {
19684                    if (pkg != null &&
19685                            pkg.applicationInfo.targetSdkVersion >=
19686                                    Build.VERSION_CODES.JELLY_BEAN) {
19687                        throw new IllegalArgumentException("Component class " + className
19688                                + " does not exist in " + packageName);
19689                    } else {
19690                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
19691                                + className + " does not exist in " + packageName);
19692                    }
19693                }
19694                switch (newState) {
19695                case COMPONENT_ENABLED_STATE_ENABLED:
19696                    if (!pkgSetting.enableComponentLPw(className, userId)) {
19697                        return;
19698                    }
19699                    break;
19700                case COMPONENT_ENABLED_STATE_DISABLED:
19701                    if (!pkgSetting.disableComponentLPw(className, userId)) {
19702                        return;
19703                    }
19704                    break;
19705                case COMPONENT_ENABLED_STATE_DEFAULT:
19706                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
19707                        return;
19708                    }
19709                    break;
19710                default:
19711                    Slog.e(TAG, "Invalid new component state: " + newState);
19712                    return;
19713                }
19714            }
19715            scheduleWritePackageRestrictionsLocked(userId);
19716            components = mPendingBroadcasts.get(userId, packageName);
19717            final boolean newPackage = components == null;
19718            if (newPackage) {
19719                components = new ArrayList<String>();
19720            }
19721            if (!components.contains(componentName)) {
19722                components.add(componentName);
19723            }
19724            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
19725                sendNow = true;
19726                // Purge entry from pending broadcast list if another one exists already
19727                // since we are sending one right away.
19728                mPendingBroadcasts.remove(userId, packageName);
19729            } else {
19730                if (newPackage) {
19731                    mPendingBroadcasts.put(userId, packageName, components);
19732                }
19733                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
19734                    // Schedule a message
19735                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
19736                }
19737            }
19738        }
19739
19740        long callingId = Binder.clearCallingIdentity();
19741        try {
19742            if (sendNow) {
19743                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
19744                sendPackageChangedBroadcast(packageName,
19745                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
19746            }
19747        } finally {
19748            Binder.restoreCallingIdentity(callingId);
19749        }
19750    }
19751
19752    @Override
19753    public void flushPackageRestrictionsAsUser(int userId) {
19754        if (!sUserManager.exists(userId)) {
19755            return;
19756        }
19757        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
19758                false /* checkShell */, "flushPackageRestrictions");
19759        synchronized (mPackages) {
19760            mSettings.writePackageRestrictionsLPr(userId);
19761            mDirtyUsers.remove(userId);
19762            if (mDirtyUsers.isEmpty()) {
19763                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
19764            }
19765        }
19766    }
19767
19768    private void sendPackageChangedBroadcast(String packageName,
19769            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
19770        if (DEBUG_INSTALL)
19771            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
19772                    + componentNames);
19773        Bundle extras = new Bundle(4);
19774        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
19775        String nameList[] = new String[componentNames.size()];
19776        componentNames.toArray(nameList);
19777        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
19778        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
19779        extras.putInt(Intent.EXTRA_UID, packageUid);
19780        // If this is not reporting a change of the overall package, then only send it
19781        // to registered receivers.  We don't want to launch a swath of apps for every
19782        // little component state change.
19783        final int flags = !componentNames.contains(packageName)
19784                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
19785        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
19786                new int[] {UserHandle.getUserId(packageUid)});
19787    }
19788
19789    @Override
19790    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
19791        if (!sUserManager.exists(userId)) return;
19792        final int uid = Binder.getCallingUid();
19793        final int permission = mContext.checkCallingOrSelfPermission(
19794                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19795        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19796        enforceCrossUserPermission(uid, userId,
19797                true /* requireFullPermission */, true /* checkShell */, "stop package");
19798        // writer
19799        synchronized (mPackages) {
19800            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
19801                    allowedByPermission, uid, userId)) {
19802                scheduleWritePackageRestrictionsLocked(userId);
19803            }
19804        }
19805    }
19806
19807    @Override
19808    public String getInstallerPackageName(String packageName) {
19809        // reader
19810        synchronized (mPackages) {
19811            return mSettings.getInstallerPackageNameLPr(packageName);
19812        }
19813    }
19814
19815    public boolean isOrphaned(String packageName) {
19816        // reader
19817        synchronized (mPackages) {
19818            return mSettings.isOrphaned(packageName);
19819        }
19820    }
19821
19822    @Override
19823    public int getApplicationEnabledSetting(String packageName, int userId) {
19824        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19825        int uid = Binder.getCallingUid();
19826        enforceCrossUserPermission(uid, userId,
19827                false /* requireFullPermission */, false /* checkShell */, "get enabled");
19828        // reader
19829        synchronized (mPackages) {
19830            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
19831        }
19832    }
19833
19834    @Override
19835    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
19836        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19837        int uid = Binder.getCallingUid();
19838        enforceCrossUserPermission(uid, userId,
19839                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
19840        // reader
19841        synchronized (mPackages) {
19842            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
19843        }
19844    }
19845
19846    @Override
19847    public void enterSafeMode() {
19848        enforceSystemOrRoot("Only the system can request entering safe mode");
19849
19850        if (!mSystemReady) {
19851            mSafeMode = true;
19852        }
19853    }
19854
19855    @Override
19856    public void systemReady() {
19857        mSystemReady = true;
19858
19859        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
19860        // disabled after already being started.
19861        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
19862                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
19863
19864        // Read the compatibilty setting when the system is ready.
19865        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
19866                mContext.getContentResolver(),
19867                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
19868        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
19869        if (DEBUG_SETTINGS) {
19870            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
19871        }
19872
19873        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
19874
19875        synchronized (mPackages) {
19876            // Verify that all of the preferred activity components actually
19877            // exist.  It is possible for applications to be updated and at
19878            // that point remove a previously declared activity component that
19879            // had been set as a preferred activity.  We try to clean this up
19880            // the next time we encounter that preferred activity, but it is
19881            // possible for the user flow to never be able to return to that
19882            // situation so here we do a sanity check to make sure we haven't
19883            // left any junk around.
19884            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
19885            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19886                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19887                removed.clear();
19888                for (PreferredActivity pa : pir.filterSet()) {
19889                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
19890                        removed.add(pa);
19891                    }
19892                }
19893                if (removed.size() > 0) {
19894                    for (int r=0; r<removed.size(); r++) {
19895                        PreferredActivity pa = removed.get(r);
19896                        Slog.w(TAG, "Removing dangling preferred activity: "
19897                                + pa.mPref.mComponent);
19898                        pir.removeFilter(pa);
19899                    }
19900                    mSettings.writePackageRestrictionsLPr(
19901                            mSettings.mPreferredActivities.keyAt(i));
19902                }
19903            }
19904
19905            for (int userId : UserManagerService.getInstance().getUserIds()) {
19906                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
19907                    grantPermissionsUserIds = ArrayUtils.appendInt(
19908                            grantPermissionsUserIds, userId);
19909                }
19910            }
19911        }
19912        sUserManager.systemReady();
19913
19914        // If we upgraded grant all default permissions before kicking off.
19915        for (int userId : grantPermissionsUserIds) {
19916            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
19917        }
19918
19919        // If we did not grant default permissions, we preload from this the
19920        // default permission exceptions lazily to ensure we don't hit the
19921        // disk on a new user creation.
19922        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
19923            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
19924        }
19925
19926        // Kick off any messages waiting for system ready
19927        if (mPostSystemReadyMessages != null) {
19928            for (Message msg : mPostSystemReadyMessages) {
19929                msg.sendToTarget();
19930            }
19931            mPostSystemReadyMessages = null;
19932        }
19933
19934        // Watch for external volumes that come and go over time
19935        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19936        storage.registerListener(mStorageListener);
19937
19938        mInstallerService.systemReady();
19939        mPackageDexOptimizer.systemReady();
19940
19941        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
19942                StorageManagerInternal.class);
19943        StorageManagerInternal.addExternalStoragePolicy(
19944                new StorageManagerInternal.ExternalStorageMountPolicy() {
19945            @Override
19946            public int getMountMode(int uid, String packageName) {
19947                if (Process.isIsolated(uid)) {
19948                    return Zygote.MOUNT_EXTERNAL_NONE;
19949                }
19950                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
19951                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
19952                }
19953                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
19954                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
19955                }
19956                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
19957                    return Zygote.MOUNT_EXTERNAL_READ;
19958                }
19959                return Zygote.MOUNT_EXTERNAL_WRITE;
19960            }
19961
19962            @Override
19963            public boolean hasExternalStorage(int uid, String packageName) {
19964                return true;
19965            }
19966        });
19967
19968        // Now that we're mostly running, clean up stale users and apps
19969        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
19970        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
19971    }
19972
19973    @Override
19974    public boolean isSafeMode() {
19975        return mSafeMode;
19976    }
19977
19978    @Override
19979    public boolean hasSystemUidErrors() {
19980        return mHasSystemUidErrors;
19981    }
19982
19983    static String arrayToString(int[] array) {
19984        StringBuffer buf = new StringBuffer(128);
19985        buf.append('[');
19986        if (array != null) {
19987            for (int i=0; i<array.length; i++) {
19988                if (i > 0) buf.append(", ");
19989                buf.append(array[i]);
19990            }
19991        }
19992        buf.append(']');
19993        return buf.toString();
19994    }
19995
19996    static class DumpState {
19997        public static final int DUMP_LIBS = 1 << 0;
19998        public static final int DUMP_FEATURES = 1 << 1;
19999        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
20000        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
20001        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20002        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20003        public static final int DUMP_PERMISSIONS = 1 << 6;
20004        public static final int DUMP_PACKAGES = 1 << 7;
20005        public static final int DUMP_SHARED_USERS = 1 << 8;
20006        public static final int DUMP_MESSAGES = 1 << 9;
20007        public static final int DUMP_PROVIDERS = 1 << 10;
20008        public static final int DUMP_VERIFIERS = 1 << 11;
20009        public static final int DUMP_PREFERRED = 1 << 12;
20010        public static final int DUMP_PREFERRED_XML = 1 << 13;
20011        public static final int DUMP_KEYSETS = 1 << 14;
20012        public static final int DUMP_VERSION = 1 << 15;
20013        public static final int DUMP_INSTALLS = 1 << 16;
20014        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20015        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20016        public static final int DUMP_FROZEN = 1 << 19;
20017        public static final int DUMP_DEXOPT = 1 << 20;
20018        public static final int DUMP_COMPILER_STATS = 1 << 21;
20019
20020        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20021
20022        private int mTypes;
20023
20024        private int mOptions;
20025
20026        private boolean mTitlePrinted;
20027
20028        private SharedUserSetting mSharedUser;
20029
20030        public boolean isDumping(int type) {
20031            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20032                return true;
20033            }
20034
20035            return (mTypes & type) != 0;
20036        }
20037
20038        public void setDump(int type) {
20039            mTypes |= type;
20040        }
20041
20042        public boolean isOptionEnabled(int option) {
20043            return (mOptions & option) != 0;
20044        }
20045
20046        public void setOptionEnabled(int option) {
20047            mOptions |= option;
20048        }
20049
20050        public boolean onTitlePrinted() {
20051            final boolean printed = mTitlePrinted;
20052            mTitlePrinted = true;
20053            return printed;
20054        }
20055
20056        public boolean getTitlePrinted() {
20057            return mTitlePrinted;
20058        }
20059
20060        public void setTitlePrinted(boolean enabled) {
20061            mTitlePrinted = enabled;
20062        }
20063
20064        public SharedUserSetting getSharedUser() {
20065            return mSharedUser;
20066        }
20067
20068        public void setSharedUser(SharedUserSetting user) {
20069            mSharedUser = user;
20070        }
20071    }
20072
20073    @Override
20074    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20075            FileDescriptor err, String[] args, ShellCallback callback,
20076            ResultReceiver resultReceiver) {
20077        (new PackageManagerShellCommand(this)).exec(
20078                this, in, out, err, args, callback, resultReceiver);
20079    }
20080
20081    @Override
20082    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20083        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
20084                != PackageManager.PERMISSION_GRANTED) {
20085            pw.println("Permission Denial: can't dump ActivityManager from from pid="
20086                    + Binder.getCallingPid()
20087                    + ", uid=" + Binder.getCallingUid()
20088                    + " without permission "
20089                    + android.Manifest.permission.DUMP);
20090            return;
20091        }
20092
20093        DumpState dumpState = new DumpState();
20094        boolean fullPreferred = false;
20095        boolean checkin = false;
20096
20097        String packageName = null;
20098        ArraySet<String> permissionNames = null;
20099
20100        int opti = 0;
20101        while (opti < args.length) {
20102            String opt = args[opti];
20103            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20104                break;
20105            }
20106            opti++;
20107
20108            if ("-a".equals(opt)) {
20109                // Right now we only know how to print all.
20110            } else if ("-h".equals(opt)) {
20111                pw.println("Package manager dump options:");
20112                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20113                pw.println("    --checkin: dump for a checkin");
20114                pw.println("    -f: print details of intent filters");
20115                pw.println("    -h: print this help");
20116                pw.println("  cmd may be one of:");
20117                pw.println("    l[ibraries]: list known shared libraries");
20118                pw.println("    f[eatures]: list device features");
20119                pw.println("    k[eysets]: print known keysets");
20120                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20121                pw.println("    perm[issions]: dump permissions");
20122                pw.println("    permission [name ...]: dump declaration and use of given permission");
20123                pw.println("    pref[erred]: print preferred package settings");
20124                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20125                pw.println("    prov[iders]: dump content providers");
20126                pw.println("    p[ackages]: dump installed packages");
20127                pw.println("    s[hared-users]: dump shared user IDs");
20128                pw.println("    m[essages]: print collected runtime messages");
20129                pw.println("    v[erifiers]: print package verifier info");
20130                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20131                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20132                pw.println("    version: print database version info");
20133                pw.println("    write: write current settings now");
20134                pw.println("    installs: details about install sessions");
20135                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20136                pw.println("    dexopt: dump dexopt state");
20137                pw.println("    compiler-stats: dump compiler statistics");
20138                pw.println("    <package.name>: info about given package");
20139                return;
20140            } else if ("--checkin".equals(opt)) {
20141                checkin = true;
20142            } else if ("-f".equals(opt)) {
20143                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20144            } else {
20145                pw.println("Unknown argument: " + opt + "; use -h for help");
20146            }
20147        }
20148
20149        // Is the caller requesting to dump a particular piece of data?
20150        if (opti < args.length) {
20151            String cmd = args[opti];
20152            opti++;
20153            // Is this a package name?
20154            if ("android".equals(cmd) || cmd.contains(".")) {
20155                packageName = cmd;
20156                // When dumping a single package, we always dump all of its
20157                // filter information since the amount of data will be reasonable.
20158                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20159            } else if ("check-permission".equals(cmd)) {
20160                if (opti >= args.length) {
20161                    pw.println("Error: check-permission missing permission argument");
20162                    return;
20163                }
20164                String perm = args[opti];
20165                opti++;
20166                if (opti >= args.length) {
20167                    pw.println("Error: check-permission missing package argument");
20168                    return;
20169                }
20170
20171                String pkg = args[opti];
20172                opti++;
20173                int user = UserHandle.getUserId(Binder.getCallingUid());
20174                if (opti < args.length) {
20175                    try {
20176                        user = Integer.parseInt(args[opti]);
20177                    } catch (NumberFormatException e) {
20178                        pw.println("Error: check-permission user argument is not a number: "
20179                                + args[opti]);
20180                        return;
20181                    }
20182                }
20183
20184                // Normalize package name to handle renamed packages and static libs
20185                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20186
20187                pw.println(checkPermission(perm, pkg, user));
20188                return;
20189            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20190                dumpState.setDump(DumpState.DUMP_LIBS);
20191            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20192                dumpState.setDump(DumpState.DUMP_FEATURES);
20193            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20194                if (opti >= args.length) {
20195                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20196                            | DumpState.DUMP_SERVICE_RESOLVERS
20197                            | DumpState.DUMP_RECEIVER_RESOLVERS
20198                            | DumpState.DUMP_CONTENT_RESOLVERS);
20199                } else {
20200                    while (opti < args.length) {
20201                        String name = args[opti];
20202                        if ("a".equals(name) || "activity".equals(name)) {
20203                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20204                        } else if ("s".equals(name) || "service".equals(name)) {
20205                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20206                        } else if ("r".equals(name) || "receiver".equals(name)) {
20207                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20208                        } else if ("c".equals(name) || "content".equals(name)) {
20209                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20210                        } else {
20211                            pw.println("Error: unknown resolver table type: " + name);
20212                            return;
20213                        }
20214                        opti++;
20215                    }
20216                }
20217            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20218                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20219            } else if ("permission".equals(cmd)) {
20220                if (opti >= args.length) {
20221                    pw.println("Error: permission requires permission name");
20222                    return;
20223                }
20224                permissionNames = new ArraySet<>();
20225                while (opti < args.length) {
20226                    permissionNames.add(args[opti]);
20227                    opti++;
20228                }
20229                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20230                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20231            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20232                dumpState.setDump(DumpState.DUMP_PREFERRED);
20233            } else if ("preferred-xml".equals(cmd)) {
20234                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20235                if (opti < args.length && "--full".equals(args[opti])) {
20236                    fullPreferred = true;
20237                    opti++;
20238                }
20239            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20240                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20241            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20242                dumpState.setDump(DumpState.DUMP_PACKAGES);
20243            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20244                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20245            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20246                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20247            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20248                dumpState.setDump(DumpState.DUMP_MESSAGES);
20249            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20250                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20251            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20252                    || "intent-filter-verifiers".equals(cmd)) {
20253                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20254            } else if ("version".equals(cmd)) {
20255                dumpState.setDump(DumpState.DUMP_VERSION);
20256            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20257                dumpState.setDump(DumpState.DUMP_KEYSETS);
20258            } else if ("installs".equals(cmd)) {
20259                dumpState.setDump(DumpState.DUMP_INSTALLS);
20260            } else if ("frozen".equals(cmd)) {
20261                dumpState.setDump(DumpState.DUMP_FROZEN);
20262            } else if ("dexopt".equals(cmd)) {
20263                dumpState.setDump(DumpState.DUMP_DEXOPT);
20264            } else if ("compiler-stats".equals(cmd)) {
20265                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20266            } else if ("write".equals(cmd)) {
20267                synchronized (mPackages) {
20268                    mSettings.writeLPr();
20269                    pw.println("Settings written.");
20270                    return;
20271                }
20272            }
20273        }
20274
20275        if (checkin) {
20276            pw.println("vers,1");
20277        }
20278
20279        // reader
20280        synchronized (mPackages) {
20281            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20282                if (!checkin) {
20283                    if (dumpState.onTitlePrinted())
20284                        pw.println();
20285                    pw.println("Database versions:");
20286                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20287                }
20288            }
20289
20290            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20291                if (!checkin) {
20292                    if (dumpState.onTitlePrinted())
20293                        pw.println();
20294                    pw.println("Verifiers:");
20295                    pw.print("  Required: ");
20296                    pw.print(mRequiredVerifierPackage);
20297                    pw.print(" (uid=");
20298                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20299                            UserHandle.USER_SYSTEM));
20300                    pw.println(")");
20301                } else if (mRequiredVerifierPackage != null) {
20302                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20303                    pw.print(",");
20304                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20305                            UserHandle.USER_SYSTEM));
20306                }
20307            }
20308
20309            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20310                    packageName == null) {
20311                if (mIntentFilterVerifierComponent != null) {
20312                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20313                    if (!checkin) {
20314                        if (dumpState.onTitlePrinted())
20315                            pw.println();
20316                        pw.println("Intent Filter Verifier:");
20317                        pw.print("  Using: ");
20318                        pw.print(verifierPackageName);
20319                        pw.print(" (uid=");
20320                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20321                                UserHandle.USER_SYSTEM));
20322                        pw.println(")");
20323                    } else if (verifierPackageName != null) {
20324                        pw.print("ifv,"); pw.print(verifierPackageName);
20325                        pw.print(",");
20326                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20327                                UserHandle.USER_SYSTEM));
20328                    }
20329                } else {
20330                    pw.println();
20331                    pw.println("No Intent Filter Verifier available!");
20332                }
20333            }
20334
20335            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20336                boolean printedHeader = false;
20337                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20338                while (it.hasNext()) {
20339                    String libName = it.next();
20340                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20341                    if (versionedLib == null) {
20342                        continue;
20343                    }
20344                    final int versionCount = versionedLib.size();
20345                    for (int i = 0; i < versionCount; i++) {
20346                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20347                        if (!checkin) {
20348                            if (!printedHeader) {
20349                                if (dumpState.onTitlePrinted())
20350                                    pw.println();
20351                                pw.println("Libraries:");
20352                                printedHeader = true;
20353                            }
20354                            pw.print("  ");
20355                        } else {
20356                            pw.print("lib,");
20357                        }
20358                        pw.print(libEntry.info.getName());
20359                        if (libEntry.info.isStatic()) {
20360                            pw.print(" version=" + libEntry.info.getVersion());
20361                        }
20362                        if (!checkin) {
20363                            pw.print(" -> ");
20364                        }
20365                        if (libEntry.path != null) {
20366                            pw.print(" (jar) ");
20367                            pw.print(libEntry.path);
20368                        } else {
20369                            pw.print(" (apk) ");
20370                            pw.print(libEntry.apk);
20371                        }
20372                        pw.println();
20373                    }
20374                }
20375            }
20376
20377            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20378                if (dumpState.onTitlePrinted())
20379                    pw.println();
20380                if (!checkin) {
20381                    pw.println("Features:");
20382                }
20383
20384                synchronized (mAvailableFeatures) {
20385                    for (FeatureInfo feat : mAvailableFeatures.values()) {
20386                        if (checkin) {
20387                            pw.print("feat,");
20388                            pw.print(feat.name);
20389                            pw.print(",");
20390                            pw.println(feat.version);
20391                        } else {
20392                            pw.print("  ");
20393                            pw.print(feat.name);
20394                            if (feat.version > 0) {
20395                                pw.print(" version=");
20396                                pw.print(feat.version);
20397                            }
20398                            pw.println();
20399                        }
20400                    }
20401                }
20402            }
20403
20404            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20405                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20406                        : "Activity Resolver Table:", "  ", packageName,
20407                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20408                    dumpState.setTitlePrinted(true);
20409                }
20410            }
20411            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20412                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20413                        : "Receiver Resolver Table:", "  ", packageName,
20414                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20415                    dumpState.setTitlePrinted(true);
20416                }
20417            }
20418            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20419                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20420                        : "Service Resolver Table:", "  ", packageName,
20421                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20422                    dumpState.setTitlePrinted(true);
20423                }
20424            }
20425            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20426                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20427                        : "Provider Resolver Table:", "  ", packageName,
20428                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20429                    dumpState.setTitlePrinted(true);
20430                }
20431            }
20432
20433            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20434                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20435                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20436                    int user = mSettings.mPreferredActivities.keyAt(i);
20437                    if (pir.dump(pw,
20438                            dumpState.getTitlePrinted()
20439                                ? "\nPreferred Activities User " + user + ":"
20440                                : "Preferred Activities User " + user + ":", "  ",
20441                            packageName, true, false)) {
20442                        dumpState.setTitlePrinted(true);
20443                    }
20444                }
20445            }
20446
20447            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20448                pw.flush();
20449                FileOutputStream fout = new FileOutputStream(fd);
20450                BufferedOutputStream str = new BufferedOutputStream(fout);
20451                XmlSerializer serializer = new FastXmlSerializer();
20452                try {
20453                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20454                    serializer.startDocument(null, true);
20455                    serializer.setFeature(
20456                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20457                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20458                    serializer.endDocument();
20459                    serializer.flush();
20460                } catch (IllegalArgumentException e) {
20461                    pw.println("Failed writing: " + e);
20462                } catch (IllegalStateException e) {
20463                    pw.println("Failed writing: " + e);
20464                } catch (IOException e) {
20465                    pw.println("Failed writing: " + e);
20466                }
20467            }
20468
20469            if (!checkin
20470                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20471                    && packageName == null) {
20472                pw.println();
20473                int count = mSettings.mPackages.size();
20474                if (count == 0) {
20475                    pw.println("No applications!");
20476                    pw.println();
20477                } else {
20478                    final String prefix = "  ";
20479                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20480                    if (allPackageSettings.size() == 0) {
20481                        pw.println("No domain preferred apps!");
20482                        pw.println();
20483                    } else {
20484                        pw.println("App verification status:");
20485                        pw.println();
20486                        count = 0;
20487                        for (PackageSetting ps : allPackageSettings) {
20488                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20489                            if (ivi == null || ivi.getPackageName() == null) continue;
20490                            pw.println(prefix + "Package: " + ivi.getPackageName());
20491                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20492                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20493                            pw.println();
20494                            count++;
20495                        }
20496                        if (count == 0) {
20497                            pw.println(prefix + "No app verification established.");
20498                            pw.println();
20499                        }
20500                        for (int userId : sUserManager.getUserIds()) {
20501                            pw.println("App linkages for user " + userId + ":");
20502                            pw.println();
20503                            count = 0;
20504                            for (PackageSetting ps : allPackageSettings) {
20505                                final long status = ps.getDomainVerificationStatusForUser(userId);
20506                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20507                                        && !DEBUG_DOMAIN_VERIFICATION) {
20508                                    continue;
20509                                }
20510                                pw.println(prefix + "Package: " + ps.name);
20511                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20512                                String statusStr = IntentFilterVerificationInfo.
20513                                        getStatusStringFromValue(status);
20514                                pw.println(prefix + "Status:  " + statusStr);
20515                                pw.println();
20516                                count++;
20517                            }
20518                            if (count == 0) {
20519                                pw.println(prefix + "No configured app linkages.");
20520                                pw.println();
20521                            }
20522                        }
20523                    }
20524                }
20525            }
20526
20527            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20528                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20529                if (packageName == null && permissionNames == null) {
20530                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
20531                        if (iperm == 0) {
20532                            if (dumpState.onTitlePrinted())
20533                                pw.println();
20534                            pw.println("AppOp Permissions:");
20535                        }
20536                        pw.print("  AppOp Permission ");
20537                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
20538                        pw.println(":");
20539                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
20540                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
20541                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
20542                        }
20543                    }
20544                }
20545            }
20546
20547            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20548                boolean printedSomething = false;
20549                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20550                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20551                        continue;
20552                    }
20553                    if (!printedSomething) {
20554                        if (dumpState.onTitlePrinted())
20555                            pw.println();
20556                        pw.println("Registered ContentProviders:");
20557                        printedSomething = true;
20558                    }
20559                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20560                    pw.print("    "); pw.println(p.toString());
20561                }
20562                printedSomething = false;
20563                for (Map.Entry<String, PackageParser.Provider> entry :
20564                        mProvidersByAuthority.entrySet()) {
20565                    PackageParser.Provider p = entry.getValue();
20566                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20567                        continue;
20568                    }
20569                    if (!printedSomething) {
20570                        if (dumpState.onTitlePrinted())
20571                            pw.println();
20572                        pw.println("ContentProvider Authorities:");
20573                        printedSomething = true;
20574                    }
20575                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20576                    pw.print("    "); pw.println(p.toString());
20577                    if (p.info != null && p.info.applicationInfo != null) {
20578                        final String appInfo = p.info.applicationInfo.toString();
20579                        pw.print("      applicationInfo="); pw.println(appInfo);
20580                    }
20581                }
20582            }
20583
20584            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20585                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20586            }
20587
20588            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20589                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20590            }
20591
20592            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20593                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20594            }
20595
20596            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20597                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20598            }
20599
20600            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
20601                // XXX should handle packageName != null by dumping only install data that
20602                // the given package is involved with.
20603                if (dumpState.onTitlePrinted()) pw.println();
20604                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
20605            }
20606
20607            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20608                // XXX should handle packageName != null by dumping only install data that
20609                // the given package is involved with.
20610                if (dumpState.onTitlePrinted()) pw.println();
20611
20612                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20613                ipw.println();
20614                ipw.println("Frozen packages:");
20615                ipw.increaseIndent();
20616                if (mFrozenPackages.size() == 0) {
20617                    ipw.println("(none)");
20618                } else {
20619                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20620                        ipw.println(mFrozenPackages.valueAt(i));
20621                    }
20622                }
20623                ipw.decreaseIndent();
20624            }
20625
20626            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20627                if (dumpState.onTitlePrinted()) pw.println();
20628                dumpDexoptStateLPr(pw, packageName);
20629            }
20630
20631            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20632                if (dumpState.onTitlePrinted()) pw.println();
20633                dumpCompilerStatsLPr(pw, packageName);
20634            }
20635
20636            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20637                if (dumpState.onTitlePrinted()) pw.println();
20638                mSettings.dumpReadMessagesLPr(pw, dumpState);
20639
20640                pw.println();
20641                pw.println("Package warning messages:");
20642                BufferedReader in = null;
20643                String line = null;
20644                try {
20645                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20646                    while ((line = in.readLine()) != null) {
20647                        if (line.contains("ignored: updated version")) continue;
20648                        pw.println(line);
20649                    }
20650                } catch (IOException ignored) {
20651                } finally {
20652                    IoUtils.closeQuietly(in);
20653                }
20654            }
20655
20656            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
20657                BufferedReader in = null;
20658                String line = null;
20659                try {
20660                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20661                    while ((line = in.readLine()) != null) {
20662                        if (line.contains("ignored: updated version")) continue;
20663                        pw.print("msg,");
20664                        pw.println(line);
20665                    }
20666                } catch (IOException ignored) {
20667                } finally {
20668                    IoUtils.closeQuietly(in);
20669                }
20670            }
20671        }
20672    }
20673
20674    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
20675        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20676        ipw.println();
20677        ipw.println("Dexopt state:");
20678        ipw.increaseIndent();
20679        Collection<PackageParser.Package> packages = null;
20680        if (packageName != null) {
20681            PackageParser.Package targetPackage = mPackages.get(packageName);
20682            if (targetPackage != null) {
20683                packages = Collections.singletonList(targetPackage);
20684            } else {
20685                ipw.println("Unable to find package: " + packageName);
20686                return;
20687            }
20688        } else {
20689            packages = mPackages.values();
20690        }
20691
20692        for (PackageParser.Package pkg : packages) {
20693            ipw.println("[" + pkg.packageName + "]");
20694            ipw.increaseIndent();
20695            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
20696            ipw.decreaseIndent();
20697        }
20698    }
20699
20700    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
20701        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20702        ipw.println();
20703        ipw.println("Compiler stats:");
20704        ipw.increaseIndent();
20705        Collection<PackageParser.Package> packages = null;
20706        if (packageName != null) {
20707            PackageParser.Package targetPackage = mPackages.get(packageName);
20708            if (targetPackage != null) {
20709                packages = Collections.singletonList(targetPackage);
20710            } else {
20711                ipw.println("Unable to find package: " + packageName);
20712                return;
20713            }
20714        } else {
20715            packages = mPackages.values();
20716        }
20717
20718        for (PackageParser.Package pkg : packages) {
20719            ipw.println("[" + pkg.packageName + "]");
20720            ipw.increaseIndent();
20721
20722            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
20723            if (stats == null) {
20724                ipw.println("(No recorded stats)");
20725            } else {
20726                stats.dump(ipw);
20727            }
20728            ipw.decreaseIndent();
20729        }
20730    }
20731
20732    private String dumpDomainString(String packageName) {
20733        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
20734                .getList();
20735        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
20736
20737        ArraySet<String> result = new ArraySet<>();
20738        if (iviList.size() > 0) {
20739            for (IntentFilterVerificationInfo ivi : iviList) {
20740                for (String host : ivi.getDomains()) {
20741                    result.add(host);
20742                }
20743            }
20744        }
20745        if (filters != null && filters.size() > 0) {
20746            for (IntentFilter filter : filters) {
20747                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
20748                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
20749                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
20750                    result.addAll(filter.getHostsList());
20751                }
20752            }
20753        }
20754
20755        StringBuilder sb = new StringBuilder(result.size() * 16);
20756        for (String domain : result) {
20757            if (sb.length() > 0) sb.append(" ");
20758            sb.append(domain);
20759        }
20760        return sb.toString();
20761    }
20762
20763    // ------- apps on sdcard specific code -------
20764    static final boolean DEBUG_SD_INSTALL = false;
20765
20766    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
20767
20768    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
20769
20770    private boolean mMediaMounted = false;
20771
20772    static String getEncryptKey() {
20773        try {
20774            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
20775                    SD_ENCRYPTION_KEYSTORE_NAME);
20776            if (sdEncKey == null) {
20777                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
20778                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
20779                if (sdEncKey == null) {
20780                    Slog.e(TAG, "Failed to create encryption keys");
20781                    return null;
20782                }
20783            }
20784            return sdEncKey;
20785        } catch (NoSuchAlgorithmException nsae) {
20786            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
20787            return null;
20788        } catch (IOException ioe) {
20789            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
20790            return null;
20791        }
20792    }
20793
20794    /*
20795     * Update media status on PackageManager.
20796     */
20797    @Override
20798    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
20799        int callingUid = Binder.getCallingUid();
20800        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
20801            throw new SecurityException("Media status can only be updated by the system");
20802        }
20803        // reader; this apparently protects mMediaMounted, but should probably
20804        // be a different lock in that case.
20805        synchronized (mPackages) {
20806            Log.i(TAG, "Updating external media status from "
20807                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
20808                    + (mediaStatus ? "mounted" : "unmounted"));
20809            if (DEBUG_SD_INSTALL)
20810                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
20811                        + ", mMediaMounted=" + mMediaMounted);
20812            if (mediaStatus == mMediaMounted) {
20813                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
20814                        : 0, -1);
20815                mHandler.sendMessage(msg);
20816                return;
20817            }
20818            mMediaMounted = mediaStatus;
20819        }
20820        // Queue up an async operation since the package installation may take a
20821        // little while.
20822        mHandler.post(new Runnable() {
20823            public void run() {
20824                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
20825            }
20826        });
20827    }
20828
20829    /**
20830     * Called by StorageManagerService when the initial ASECs to scan are available.
20831     * Should block until all the ASEC containers are finished being scanned.
20832     */
20833    public void scanAvailableAsecs() {
20834        updateExternalMediaStatusInner(true, false, false);
20835    }
20836
20837    /*
20838     * Collect information of applications on external media, map them against
20839     * existing containers and update information based on current mount status.
20840     * Please note that we always have to report status if reportStatus has been
20841     * set to true especially when unloading packages.
20842     */
20843    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
20844            boolean externalStorage) {
20845        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
20846        int[] uidArr = EmptyArray.INT;
20847
20848        final String[] list = PackageHelper.getSecureContainerList();
20849        if (ArrayUtils.isEmpty(list)) {
20850            Log.i(TAG, "No secure containers found");
20851        } else {
20852            // Process list of secure containers and categorize them
20853            // as active or stale based on their package internal state.
20854
20855            // reader
20856            synchronized (mPackages) {
20857                for (String cid : list) {
20858                    // Leave stages untouched for now; installer service owns them
20859                    if (PackageInstallerService.isStageName(cid)) continue;
20860
20861                    if (DEBUG_SD_INSTALL)
20862                        Log.i(TAG, "Processing container " + cid);
20863                    String pkgName = getAsecPackageName(cid);
20864                    if (pkgName == null) {
20865                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
20866                        continue;
20867                    }
20868                    if (DEBUG_SD_INSTALL)
20869                        Log.i(TAG, "Looking for pkg : " + pkgName);
20870
20871                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
20872                    if (ps == null) {
20873                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
20874                        continue;
20875                    }
20876
20877                    /*
20878                     * Skip packages that are not external if we're unmounting
20879                     * external storage.
20880                     */
20881                    if (externalStorage && !isMounted && !isExternal(ps)) {
20882                        continue;
20883                    }
20884
20885                    final AsecInstallArgs args = new AsecInstallArgs(cid,
20886                            getAppDexInstructionSets(ps), ps.isForwardLocked());
20887                    // The package status is changed only if the code path
20888                    // matches between settings and the container id.
20889                    if (ps.codePathString != null
20890                            && ps.codePathString.startsWith(args.getCodePath())) {
20891                        if (DEBUG_SD_INSTALL) {
20892                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
20893                                    + " at code path: " + ps.codePathString);
20894                        }
20895
20896                        // We do have a valid package installed on sdcard
20897                        processCids.put(args, ps.codePathString);
20898                        final int uid = ps.appId;
20899                        if (uid != -1) {
20900                            uidArr = ArrayUtils.appendInt(uidArr, uid);
20901                        }
20902                    } else {
20903                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
20904                                + ps.codePathString);
20905                    }
20906                }
20907            }
20908
20909            Arrays.sort(uidArr);
20910        }
20911
20912        // Process packages with valid entries.
20913        if (isMounted) {
20914            if (DEBUG_SD_INSTALL)
20915                Log.i(TAG, "Loading packages");
20916            loadMediaPackages(processCids, uidArr, externalStorage);
20917            startCleaningPackages();
20918            mInstallerService.onSecureContainersAvailable();
20919        } else {
20920            if (DEBUG_SD_INSTALL)
20921                Log.i(TAG, "Unloading packages");
20922            unloadMediaPackages(processCids, uidArr, reportStatus);
20923        }
20924    }
20925
20926    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20927            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
20928        final int size = infos.size();
20929        final String[] packageNames = new String[size];
20930        final int[] packageUids = new int[size];
20931        for (int i = 0; i < size; i++) {
20932            final ApplicationInfo info = infos.get(i);
20933            packageNames[i] = info.packageName;
20934            packageUids[i] = info.uid;
20935        }
20936        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
20937                finishedReceiver);
20938    }
20939
20940    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20941            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
20942        sendResourcesChangedBroadcast(mediaStatus, replacing,
20943                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
20944    }
20945
20946    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20947            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
20948        int size = pkgList.length;
20949        if (size > 0) {
20950            // Send broadcasts here
20951            Bundle extras = new Bundle();
20952            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
20953            if (uidArr != null) {
20954                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
20955            }
20956            if (replacing) {
20957                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
20958            }
20959            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
20960                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
20961            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
20962        }
20963    }
20964
20965   /*
20966     * Look at potentially valid container ids from processCids If package
20967     * information doesn't match the one on record or package scanning fails,
20968     * the cid is added to list of removeCids. We currently don't delete stale
20969     * containers.
20970     */
20971    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
20972            boolean externalStorage) {
20973        ArrayList<String> pkgList = new ArrayList<String>();
20974        Set<AsecInstallArgs> keys = processCids.keySet();
20975
20976        for (AsecInstallArgs args : keys) {
20977            String codePath = processCids.get(args);
20978            if (DEBUG_SD_INSTALL)
20979                Log.i(TAG, "Loading container : " + args.cid);
20980            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
20981            try {
20982                // Make sure there are no container errors first.
20983                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
20984                    Slog.e(TAG, "Failed to mount cid : " + args.cid
20985                            + " when installing from sdcard");
20986                    continue;
20987                }
20988                // Check code path here.
20989                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
20990                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
20991                            + " does not match one in settings " + codePath);
20992                    continue;
20993                }
20994                // Parse package
20995                int parseFlags = mDefParseFlags;
20996                if (args.isExternalAsec()) {
20997                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
20998                }
20999                if (args.isFwdLocked()) {
21000                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
21001                }
21002
21003                synchronized (mInstallLock) {
21004                    PackageParser.Package pkg = null;
21005                    try {
21006                        // Sadly we don't know the package name yet to freeze it
21007                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21008                                SCAN_IGNORE_FROZEN, 0, null);
21009                    } catch (PackageManagerException e) {
21010                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21011                    }
21012                    // Scan the package
21013                    if (pkg != null) {
21014                        /*
21015                         * TODO why is the lock being held? doPostInstall is
21016                         * called in other places without the lock. This needs
21017                         * to be straightened out.
21018                         */
21019                        // writer
21020                        synchronized (mPackages) {
21021                            retCode = PackageManager.INSTALL_SUCCEEDED;
21022                            pkgList.add(pkg.packageName);
21023                            // Post process args
21024                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21025                                    pkg.applicationInfo.uid);
21026                        }
21027                    } else {
21028                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21029                    }
21030                }
21031
21032            } finally {
21033                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21034                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21035                }
21036            }
21037        }
21038        // writer
21039        synchronized (mPackages) {
21040            // If the platform SDK has changed since the last time we booted,
21041            // we need to re-grant app permission to catch any new ones that
21042            // appear. This is really a hack, and means that apps can in some
21043            // cases get permissions that the user didn't initially explicitly
21044            // allow... it would be nice to have some better way to handle
21045            // this situation.
21046            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21047                    : mSettings.getInternalVersion();
21048            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21049                    : StorageManager.UUID_PRIVATE_INTERNAL;
21050
21051            int updateFlags = UPDATE_PERMISSIONS_ALL;
21052            if (ver.sdkVersion != mSdkVersion) {
21053                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21054                        + mSdkVersion + "; regranting permissions for external");
21055                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21056            }
21057            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21058
21059            // Yay, everything is now upgraded
21060            ver.forceCurrent();
21061
21062            // can downgrade to reader
21063            // Persist settings
21064            mSettings.writeLPr();
21065        }
21066        // Send a broadcast to let everyone know we are done processing
21067        if (pkgList.size() > 0) {
21068            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21069        }
21070    }
21071
21072   /*
21073     * Utility method to unload a list of specified containers
21074     */
21075    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21076        // Just unmount all valid containers.
21077        for (AsecInstallArgs arg : cidArgs) {
21078            synchronized (mInstallLock) {
21079                arg.doPostDeleteLI(false);
21080           }
21081       }
21082   }
21083
21084    /*
21085     * Unload packages mounted on external media. This involves deleting package
21086     * data from internal structures, sending broadcasts about disabled packages,
21087     * gc'ing to free up references, unmounting all secure containers
21088     * corresponding to packages on external media, and posting a
21089     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21090     * that we always have to post this message if status has been requested no
21091     * matter what.
21092     */
21093    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21094            final boolean reportStatus) {
21095        if (DEBUG_SD_INSTALL)
21096            Log.i(TAG, "unloading media packages");
21097        ArrayList<String> pkgList = new ArrayList<String>();
21098        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21099        final Set<AsecInstallArgs> keys = processCids.keySet();
21100        for (AsecInstallArgs args : keys) {
21101            String pkgName = args.getPackageName();
21102            if (DEBUG_SD_INSTALL)
21103                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21104            // Delete package internally
21105            PackageRemovedInfo outInfo = new PackageRemovedInfo();
21106            synchronized (mInstallLock) {
21107                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21108                final boolean res;
21109                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21110                        "unloadMediaPackages")) {
21111                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21112                            null);
21113                }
21114                if (res) {
21115                    pkgList.add(pkgName);
21116                } else {
21117                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21118                    failedList.add(args);
21119                }
21120            }
21121        }
21122
21123        // reader
21124        synchronized (mPackages) {
21125            // We didn't update the settings after removing each package;
21126            // write them now for all packages.
21127            mSettings.writeLPr();
21128        }
21129
21130        // We have to absolutely send UPDATED_MEDIA_STATUS only
21131        // after confirming that all the receivers processed the ordered
21132        // broadcast when packages get disabled, force a gc to clean things up.
21133        // and unload all the containers.
21134        if (pkgList.size() > 0) {
21135            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21136                    new IIntentReceiver.Stub() {
21137                public void performReceive(Intent intent, int resultCode, String data,
21138                        Bundle extras, boolean ordered, boolean sticky,
21139                        int sendingUser) throws RemoteException {
21140                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21141                            reportStatus ? 1 : 0, 1, keys);
21142                    mHandler.sendMessage(msg);
21143                }
21144            });
21145        } else {
21146            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
21147                    keys);
21148            mHandler.sendMessage(msg);
21149        }
21150    }
21151
21152    private void loadPrivatePackages(final VolumeInfo vol) {
21153        mHandler.post(new Runnable() {
21154            @Override
21155            public void run() {
21156                loadPrivatePackagesInner(vol);
21157            }
21158        });
21159    }
21160
21161    private void loadPrivatePackagesInner(VolumeInfo vol) {
21162        final String volumeUuid = vol.fsUuid;
21163        if (TextUtils.isEmpty(volumeUuid)) {
21164            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21165            return;
21166        }
21167
21168        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21169        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21170        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21171
21172        final VersionInfo ver;
21173        final List<PackageSetting> packages;
21174        synchronized (mPackages) {
21175            ver = mSettings.findOrCreateVersion(volumeUuid);
21176            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21177        }
21178
21179        for (PackageSetting ps : packages) {
21180            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21181            synchronized (mInstallLock) {
21182                final PackageParser.Package pkg;
21183                try {
21184                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21185                    loaded.add(pkg.applicationInfo);
21186
21187                } catch (PackageManagerException e) {
21188                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21189                }
21190
21191                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21192                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21193                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21194                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21195                }
21196            }
21197        }
21198
21199        // Reconcile app data for all started/unlocked users
21200        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21201        final UserManager um = mContext.getSystemService(UserManager.class);
21202        UserManagerInternal umInternal = getUserManagerInternal();
21203        for (UserInfo user : um.getUsers()) {
21204            final int flags;
21205            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21206                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21207            } else if (umInternal.isUserRunning(user.id)) {
21208                flags = StorageManager.FLAG_STORAGE_DE;
21209            } else {
21210                continue;
21211            }
21212
21213            try {
21214                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21215                synchronized (mInstallLock) {
21216                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21217                }
21218            } catch (IllegalStateException e) {
21219                // Device was probably ejected, and we'll process that event momentarily
21220                Slog.w(TAG, "Failed to prepare storage: " + e);
21221            }
21222        }
21223
21224        synchronized (mPackages) {
21225            int updateFlags = UPDATE_PERMISSIONS_ALL;
21226            if (ver.sdkVersion != mSdkVersion) {
21227                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21228                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21229                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21230            }
21231            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21232
21233            // Yay, everything is now upgraded
21234            ver.forceCurrent();
21235
21236            mSettings.writeLPr();
21237        }
21238
21239        for (PackageFreezer freezer : freezers) {
21240            freezer.close();
21241        }
21242
21243        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21244        sendResourcesChangedBroadcast(true, false, loaded, null);
21245    }
21246
21247    private void unloadPrivatePackages(final VolumeInfo vol) {
21248        mHandler.post(new Runnable() {
21249            @Override
21250            public void run() {
21251                unloadPrivatePackagesInner(vol);
21252            }
21253        });
21254    }
21255
21256    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21257        final String volumeUuid = vol.fsUuid;
21258        if (TextUtils.isEmpty(volumeUuid)) {
21259            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21260            return;
21261        }
21262
21263        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21264        synchronized (mInstallLock) {
21265        synchronized (mPackages) {
21266            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21267            for (PackageSetting ps : packages) {
21268                if (ps.pkg == null) continue;
21269
21270                final ApplicationInfo info = ps.pkg.applicationInfo;
21271                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21272                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
21273
21274                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21275                        "unloadPrivatePackagesInner")) {
21276                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21277                            false, null)) {
21278                        unloaded.add(info);
21279                    } else {
21280                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21281                    }
21282                }
21283
21284                // Try very hard to release any references to this package
21285                // so we don't risk the system server being killed due to
21286                // open FDs
21287                AttributeCache.instance().removePackage(ps.name);
21288            }
21289
21290            mSettings.writeLPr();
21291        }
21292        }
21293
21294        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21295        sendResourcesChangedBroadcast(false, false, unloaded, null);
21296
21297        // Try very hard to release any references to this path so we don't risk
21298        // the system server being killed due to open FDs
21299        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21300
21301        for (int i = 0; i < 3; i++) {
21302            System.gc();
21303            System.runFinalization();
21304        }
21305    }
21306
21307    /**
21308     * Examine all users present on given mounted volume, and destroy data
21309     * belonging to users that are no longer valid, or whose user ID has been
21310     * recycled.
21311     */
21312    private void reconcileUsers(String volumeUuid) {
21313        final List<File> files = new ArrayList<>();
21314        Collections.addAll(files, FileUtils
21315                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
21316        Collections.addAll(files, FileUtils
21317                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
21318        Collections.addAll(files, FileUtils
21319                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
21320        Collections.addAll(files, FileUtils
21321                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
21322        Collections.addAll(files, FileUtils
21323                .listFilesOrEmpty(Environment.getDataMiscCeDirectory()));
21324        for (File file : files) {
21325            if (!file.isDirectory()) continue;
21326
21327            final int userId;
21328            final UserInfo info;
21329            try {
21330                userId = Integer.parseInt(file.getName());
21331                info = sUserManager.getUserInfo(userId);
21332            } catch (NumberFormatException e) {
21333                Slog.w(TAG, "Invalid user directory " + file);
21334                continue;
21335            }
21336
21337            boolean destroyUser = false;
21338            if (info == null) {
21339                logCriticalInfo(Log.WARN, "Destroying user directory " + file
21340                        + " because no matching user was found");
21341                destroyUser = true;
21342            } else if (!mOnlyCore) {
21343                try {
21344                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
21345                } catch (IOException e) {
21346                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
21347                            + " because we failed to enforce serial number: " + e);
21348                    destroyUser = true;
21349                }
21350            }
21351
21352            if (destroyUser) {
21353                synchronized (mInstallLock) {
21354                    mUserDataPreparer.destroyUserDataLI(volumeUuid, userId,
21355                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
21356                }
21357            }
21358        }
21359    }
21360
21361    private void assertPackageKnown(String volumeUuid, String packageName)
21362            throws PackageManagerException {
21363        synchronized (mPackages) {
21364            // Normalize package name to handle renamed packages
21365            packageName = normalizePackageNameLPr(packageName);
21366
21367            final PackageSetting ps = mSettings.mPackages.get(packageName);
21368            if (ps == null) {
21369                throw new PackageManagerException("Package " + packageName + " is unknown");
21370            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21371                throw new PackageManagerException(
21372                        "Package " + packageName + " found on unknown volume " + volumeUuid
21373                                + "; expected volume " + ps.volumeUuid);
21374            }
21375        }
21376    }
21377
21378    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21379            throws PackageManagerException {
21380        synchronized (mPackages) {
21381            // Normalize package name to handle renamed packages
21382            packageName = normalizePackageNameLPr(packageName);
21383
21384            final PackageSetting ps = mSettings.mPackages.get(packageName);
21385            if (ps == null) {
21386                throw new PackageManagerException("Package " + packageName + " is unknown");
21387            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21388                throw new PackageManagerException(
21389                        "Package " + packageName + " found on unknown volume " + volumeUuid
21390                                + "; expected volume " + ps.volumeUuid);
21391            } else if (!ps.getInstalled(userId)) {
21392                throw new PackageManagerException(
21393                        "Package " + packageName + " not installed for user " + userId);
21394            }
21395        }
21396    }
21397
21398    private List<String> collectAbsoluteCodePaths() {
21399        synchronized (mPackages) {
21400            List<String> codePaths = new ArrayList<>();
21401            final int packageCount = mSettings.mPackages.size();
21402            for (int i = 0; i < packageCount; i++) {
21403                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21404                codePaths.add(ps.codePath.getAbsolutePath());
21405            }
21406            return codePaths;
21407        }
21408    }
21409
21410    /**
21411     * Examine all apps present on given mounted volume, and destroy apps that
21412     * aren't expected, either due to uninstallation or reinstallation on
21413     * another volume.
21414     */
21415    private void reconcileApps(String volumeUuid) {
21416        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21417        List<File> filesToDelete = null;
21418
21419        final File[] files = FileUtils.listFilesOrEmpty(
21420                Environment.getDataAppDirectory(volumeUuid));
21421        for (File file : files) {
21422            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21423                    && !PackageInstallerService.isStageName(file.getName());
21424            if (!isPackage) {
21425                // Ignore entries which are not packages
21426                continue;
21427            }
21428
21429            String absolutePath = file.getAbsolutePath();
21430
21431            boolean pathValid = false;
21432            final int absoluteCodePathCount = absoluteCodePaths.size();
21433            for (int i = 0; i < absoluteCodePathCount; i++) {
21434                String absoluteCodePath = absoluteCodePaths.get(i);
21435                if (absolutePath.startsWith(absoluteCodePath)) {
21436                    pathValid = true;
21437                    break;
21438                }
21439            }
21440
21441            if (!pathValid) {
21442                if (filesToDelete == null) {
21443                    filesToDelete = new ArrayList<>();
21444                }
21445                filesToDelete.add(file);
21446            }
21447        }
21448
21449        if (filesToDelete != null) {
21450            final int fileToDeleteCount = filesToDelete.size();
21451            for (int i = 0; i < fileToDeleteCount; i++) {
21452                File fileToDelete = filesToDelete.get(i);
21453                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21454                synchronized (mInstallLock) {
21455                    removeCodePathLI(fileToDelete);
21456                }
21457            }
21458        }
21459    }
21460
21461    /**
21462     * Reconcile all app data for the given user.
21463     * <p>
21464     * Verifies that directories exist and that ownership and labeling is
21465     * correct for all installed apps on all mounted volumes.
21466     */
21467    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21468        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21469        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21470            final String volumeUuid = vol.getFsUuid();
21471            synchronized (mInstallLock) {
21472                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21473            }
21474        }
21475    }
21476
21477    /**
21478     * Reconcile all app data on given mounted volume.
21479     * <p>
21480     * Destroys app data that isn't expected, either due to uninstallation or
21481     * reinstallation on another volume.
21482     * <p>
21483     * Verifies that directories exist and that ownership and labeling is
21484     * correct for all installed apps.
21485     */
21486    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21487            boolean migrateAppData) {
21488        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21489                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21490
21491        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21492        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21493
21494        // First look for stale data that doesn't belong, and check if things
21495        // have changed since we did our last restorecon
21496        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21497            if (StorageManager.isFileEncryptedNativeOrEmulated()
21498                    && !StorageManager.isUserKeyUnlocked(userId)) {
21499                throw new RuntimeException(
21500                        "Yikes, someone asked us to reconcile CE storage while " + userId
21501                                + " was still locked; this would have caused massive data loss!");
21502            }
21503
21504            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21505            for (File file : files) {
21506                final String packageName = file.getName();
21507                try {
21508                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21509                } catch (PackageManagerException e) {
21510                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21511                    try {
21512                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21513                                StorageManager.FLAG_STORAGE_CE, 0);
21514                    } catch (InstallerException e2) {
21515                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21516                    }
21517                }
21518            }
21519        }
21520        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21521            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21522            for (File file : files) {
21523                final String packageName = file.getName();
21524                try {
21525                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21526                } catch (PackageManagerException e) {
21527                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21528                    try {
21529                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21530                                StorageManager.FLAG_STORAGE_DE, 0);
21531                    } catch (InstallerException e2) {
21532                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21533                    }
21534                }
21535            }
21536        }
21537
21538        // Ensure that data directories are ready to roll for all packages
21539        // installed for this volume and user
21540        final List<PackageSetting> packages;
21541        synchronized (mPackages) {
21542            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21543        }
21544        int preparedCount = 0;
21545        for (PackageSetting ps : packages) {
21546            final String packageName = ps.name;
21547            if (ps.pkg == null) {
21548                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21549                // TODO: might be due to legacy ASEC apps; we should circle back
21550                // and reconcile again once they're scanned
21551                continue;
21552            }
21553
21554            if (ps.getInstalled(userId)) {
21555                prepareAppDataLIF(ps.pkg, userId, flags);
21556
21557                if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) {
21558                    // We may have just shuffled around app data directories, so
21559                    // prepare them one more time
21560                    prepareAppDataLIF(ps.pkg, userId, flags);
21561                }
21562
21563                preparedCount++;
21564            }
21565        }
21566
21567        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21568    }
21569
21570    /**
21571     * Prepare app data for the given app just after it was installed or
21572     * upgraded. This method carefully only touches users that it's installed
21573     * for, and it forces a restorecon to handle any seinfo changes.
21574     * <p>
21575     * Verifies that directories exist and that ownership and labeling is
21576     * correct for all installed apps. If there is an ownership mismatch, it
21577     * will try recovering system apps by wiping data; third-party app data is
21578     * left intact.
21579     * <p>
21580     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21581     */
21582    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21583        final PackageSetting ps;
21584        synchronized (mPackages) {
21585            ps = mSettings.mPackages.get(pkg.packageName);
21586            mSettings.writeKernelMappingLPr(ps);
21587        }
21588
21589        final UserManager um = mContext.getSystemService(UserManager.class);
21590        UserManagerInternal umInternal = getUserManagerInternal();
21591        for (UserInfo user : um.getUsers()) {
21592            final int flags;
21593            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21594                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21595            } else if (umInternal.isUserRunning(user.id)) {
21596                flags = StorageManager.FLAG_STORAGE_DE;
21597            } else {
21598                continue;
21599            }
21600
21601            if (ps.getInstalled(user.id)) {
21602                // TODO: when user data is locked, mark that we're still dirty
21603                prepareAppDataLIF(pkg, user.id, flags);
21604            }
21605        }
21606    }
21607
21608    /**
21609     * Prepare app data for the given app.
21610     * <p>
21611     * Verifies that directories exist and that ownership and labeling is
21612     * correct for all installed apps. If there is an ownership mismatch, this
21613     * will try recovering system apps by wiping data; third-party app data is
21614     * left intact.
21615     */
21616    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21617        if (pkg == null) {
21618            Slog.wtf(TAG, "Package was null!", new Throwable());
21619            return;
21620        }
21621        prepareAppDataLeafLIF(pkg, userId, flags);
21622        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21623        for (int i = 0; i < childCount; i++) {
21624            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21625        }
21626    }
21627
21628    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21629        if (DEBUG_APP_DATA) {
21630            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21631                    + Integer.toHexString(flags));
21632        }
21633
21634        final String volumeUuid = pkg.volumeUuid;
21635        final String packageName = pkg.packageName;
21636        final ApplicationInfo app = pkg.applicationInfo;
21637        final int appId = UserHandle.getAppId(app.uid);
21638
21639        Preconditions.checkNotNull(app.seinfo);
21640
21641        long ceDataInode = -1;
21642        try {
21643            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21644                    appId, app.seinfo, app.targetSdkVersion);
21645        } catch (InstallerException e) {
21646            if (app.isSystemApp()) {
21647                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21648                        + ", but trying to recover: " + e);
21649                destroyAppDataLeafLIF(pkg, userId, flags);
21650                try {
21651                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21652                            appId, app.seinfo, app.targetSdkVersion);
21653                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21654                } catch (InstallerException e2) {
21655                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21656                }
21657            } else {
21658                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21659            }
21660        }
21661
21662        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21663            // TODO: mark this structure as dirty so we persist it!
21664            synchronized (mPackages) {
21665                final PackageSetting ps = mSettings.mPackages.get(packageName);
21666                if (ps != null) {
21667                    ps.setCeDataInode(ceDataInode, userId);
21668                }
21669            }
21670        }
21671
21672        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21673    }
21674
21675    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21676        if (pkg == null) {
21677            Slog.wtf(TAG, "Package was null!", new Throwable());
21678            return;
21679        }
21680        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21681        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21682        for (int i = 0; i < childCount; i++) {
21683            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21684        }
21685    }
21686
21687    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21688        final String volumeUuid = pkg.volumeUuid;
21689        final String packageName = pkg.packageName;
21690        final ApplicationInfo app = pkg.applicationInfo;
21691
21692        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21693            // Create a native library symlink only if we have native libraries
21694            // and if the native libraries are 32 bit libraries. We do not provide
21695            // this symlink for 64 bit libraries.
21696            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21697                final String nativeLibPath = app.nativeLibraryDir;
21698                try {
21699                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21700                            nativeLibPath, userId);
21701                } catch (InstallerException e) {
21702                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21703                }
21704            }
21705        }
21706    }
21707
21708    /**
21709     * For system apps on non-FBE devices, this method migrates any existing
21710     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21711     * requested by the app.
21712     */
21713    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21714        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
21715                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21716            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21717                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21718            try {
21719                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21720                        storageTarget);
21721            } catch (InstallerException e) {
21722                logCriticalInfo(Log.WARN,
21723                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21724            }
21725            return true;
21726        } else {
21727            return false;
21728        }
21729    }
21730
21731    public PackageFreezer freezePackage(String packageName, String killReason) {
21732        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
21733    }
21734
21735    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
21736        return new PackageFreezer(packageName, userId, killReason);
21737    }
21738
21739    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
21740            String killReason) {
21741        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
21742    }
21743
21744    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
21745            String killReason) {
21746        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
21747            return new PackageFreezer();
21748        } else {
21749            return freezePackage(packageName, userId, killReason);
21750        }
21751    }
21752
21753    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
21754            String killReason) {
21755        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
21756    }
21757
21758    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
21759            String killReason) {
21760        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
21761            return new PackageFreezer();
21762        } else {
21763            return freezePackage(packageName, userId, killReason);
21764        }
21765    }
21766
21767    /**
21768     * Class that freezes and kills the given package upon creation, and
21769     * unfreezes it upon closing. This is typically used when doing surgery on
21770     * app code/data to prevent the app from running while you're working.
21771     */
21772    private class PackageFreezer implements AutoCloseable {
21773        private final String mPackageName;
21774        private final PackageFreezer[] mChildren;
21775
21776        private final boolean mWeFroze;
21777
21778        private final AtomicBoolean mClosed = new AtomicBoolean();
21779        private final CloseGuard mCloseGuard = CloseGuard.get();
21780
21781        /**
21782         * Create and return a stub freezer that doesn't actually do anything,
21783         * typically used when someone requested
21784         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
21785         * {@link PackageManager#DELETE_DONT_KILL_APP}.
21786         */
21787        public PackageFreezer() {
21788            mPackageName = null;
21789            mChildren = null;
21790            mWeFroze = false;
21791            mCloseGuard.open("close");
21792        }
21793
21794        public PackageFreezer(String packageName, int userId, String killReason) {
21795            synchronized (mPackages) {
21796                mPackageName = packageName;
21797                mWeFroze = mFrozenPackages.add(mPackageName);
21798
21799                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
21800                if (ps != null) {
21801                    killApplication(ps.name, ps.appId, userId, killReason);
21802                }
21803
21804                final PackageParser.Package p = mPackages.get(packageName);
21805                if (p != null && p.childPackages != null) {
21806                    final int N = p.childPackages.size();
21807                    mChildren = new PackageFreezer[N];
21808                    for (int i = 0; i < N; i++) {
21809                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
21810                                userId, killReason);
21811                    }
21812                } else {
21813                    mChildren = null;
21814                }
21815            }
21816            mCloseGuard.open("close");
21817        }
21818
21819        @Override
21820        protected void finalize() throws Throwable {
21821            try {
21822                mCloseGuard.warnIfOpen();
21823                close();
21824            } finally {
21825                super.finalize();
21826            }
21827        }
21828
21829        @Override
21830        public void close() {
21831            mCloseGuard.close();
21832            if (mClosed.compareAndSet(false, true)) {
21833                synchronized (mPackages) {
21834                    if (mWeFroze) {
21835                        mFrozenPackages.remove(mPackageName);
21836                    }
21837
21838                    if (mChildren != null) {
21839                        for (PackageFreezer freezer : mChildren) {
21840                            freezer.close();
21841                        }
21842                    }
21843                }
21844            }
21845        }
21846    }
21847
21848    /**
21849     * Verify that given package is currently frozen.
21850     */
21851    private void checkPackageFrozen(String packageName) {
21852        synchronized (mPackages) {
21853            if (!mFrozenPackages.contains(packageName)) {
21854                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
21855            }
21856        }
21857    }
21858
21859    @Override
21860    public int movePackage(final String packageName, final String volumeUuid) {
21861        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
21862
21863        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
21864        final int moveId = mNextMoveId.getAndIncrement();
21865        mHandler.post(new Runnable() {
21866            @Override
21867            public void run() {
21868                try {
21869                    movePackageInternal(packageName, volumeUuid, moveId, user);
21870                } catch (PackageManagerException e) {
21871                    Slog.w(TAG, "Failed to move " + packageName, e);
21872                    mMoveCallbacks.notifyStatusChanged(moveId,
21873                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
21874                }
21875            }
21876        });
21877        return moveId;
21878    }
21879
21880    private void movePackageInternal(final String packageName, final String volumeUuid,
21881            final int moveId, UserHandle user) throws PackageManagerException {
21882        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21883        final PackageManager pm = mContext.getPackageManager();
21884
21885        final boolean currentAsec;
21886        final String currentVolumeUuid;
21887        final File codeFile;
21888        final String installerPackageName;
21889        final String packageAbiOverride;
21890        final int appId;
21891        final String seinfo;
21892        final String label;
21893        final int targetSdkVersion;
21894        final PackageFreezer freezer;
21895        final int[] installedUserIds;
21896
21897        // reader
21898        synchronized (mPackages) {
21899            final PackageParser.Package pkg = mPackages.get(packageName);
21900            final PackageSetting ps = mSettings.mPackages.get(packageName);
21901            if (pkg == null || ps == null) {
21902                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
21903            }
21904
21905            if (pkg.applicationInfo.isSystemApp()) {
21906                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
21907                        "Cannot move system application");
21908            }
21909
21910            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
21911            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
21912                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
21913            if (isInternalStorage && !allow3rdPartyOnInternal) {
21914                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
21915                        "3rd party apps are not allowed on internal storage");
21916            }
21917
21918            if (pkg.applicationInfo.isExternalAsec()) {
21919                currentAsec = true;
21920                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
21921            } else if (pkg.applicationInfo.isForwardLocked()) {
21922                currentAsec = true;
21923                currentVolumeUuid = "forward_locked";
21924            } else {
21925                currentAsec = false;
21926                currentVolumeUuid = ps.volumeUuid;
21927
21928                final File probe = new File(pkg.codePath);
21929                final File probeOat = new File(probe, "oat");
21930                if (!probe.isDirectory() || !probeOat.isDirectory()) {
21931                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21932                            "Move only supported for modern cluster style installs");
21933                }
21934            }
21935
21936            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
21937                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21938                        "Package already moved to " + volumeUuid);
21939            }
21940            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
21941                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
21942                        "Device admin cannot be moved");
21943            }
21944
21945            if (mFrozenPackages.contains(packageName)) {
21946                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
21947                        "Failed to move already frozen package");
21948            }
21949
21950            codeFile = new File(pkg.codePath);
21951            installerPackageName = ps.installerPackageName;
21952            packageAbiOverride = ps.cpuAbiOverrideString;
21953            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
21954            seinfo = pkg.applicationInfo.seinfo;
21955            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
21956            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
21957            freezer = freezePackage(packageName, "movePackageInternal");
21958            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
21959        }
21960
21961        final Bundle extras = new Bundle();
21962        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
21963        extras.putString(Intent.EXTRA_TITLE, label);
21964        mMoveCallbacks.notifyCreated(moveId, extras);
21965
21966        int installFlags;
21967        final boolean moveCompleteApp;
21968        final File measurePath;
21969
21970        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
21971            installFlags = INSTALL_INTERNAL;
21972            moveCompleteApp = !currentAsec;
21973            measurePath = Environment.getDataAppDirectory(volumeUuid);
21974        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
21975            installFlags = INSTALL_EXTERNAL;
21976            moveCompleteApp = false;
21977            measurePath = storage.getPrimaryPhysicalVolume().getPath();
21978        } else {
21979            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
21980            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
21981                    || !volume.isMountedWritable()) {
21982                freezer.close();
21983                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21984                        "Move location not mounted private volume");
21985            }
21986
21987            Preconditions.checkState(!currentAsec);
21988
21989            installFlags = INSTALL_INTERNAL;
21990            moveCompleteApp = true;
21991            measurePath = Environment.getDataAppDirectory(volumeUuid);
21992        }
21993
21994        final PackageStats stats = new PackageStats(null, -1);
21995        synchronized (mInstaller) {
21996            for (int userId : installedUserIds) {
21997                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
21998                    freezer.close();
21999                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22000                            "Failed to measure package size");
22001                }
22002            }
22003        }
22004
22005        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22006                + stats.dataSize);
22007
22008        final long startFreeBytes = measurePath.getFreeSpace();
22009        final long sizeBytes;
22010        if (moveCompleteApp) {
22011            sizeBytes = stats.codeSize + stats.dataSize;
22012        } else {
22013            sizeBytes = stats.codeSize;
22014        }
22015
22016        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22017            freezer.close();
22018            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22019                    "Not enough free space to move");
22020        }
22021
22022        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22023
22024        final CountDownLatch installedLatch = new CountDownLatch(1);
22025        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22026            @Override
22027            public void onUserActionRequired(Intent intent) throws RemoteException {
22028                throw new IllegalStateException();
22029            }
22030
22031            @Override
22032            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22033                    Bundle extras) throws RemoteException {
22034                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22035                        + PackageManager.installStatusToString(returnCode, msg));
22036
22037                installedLatch.countDown();
22038                freezer.close();
22039
22040                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22041                switch (status) {
22042                    case PackageInstaller.STATUS_SUCCESS:
22043                        mMoveCallbacks.notifyStatusChanged(moveId,
22044                                PackageManager.MOVE_SUCCEEDED);
22045                        break;
22046                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22047                        mMoveCallbacks.notifyStatusChanged(moveId,
22048                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22049                        break;
22050                    default:
22051                        mMoveCallbacks.notifyStatusChanged(moveId,
22052                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22053                        break;
22054                }
22055            }
22056        };
22057
22058        final MoveInfo move;
22059        if (moveCompleteApp) {
22060            // Kick off a thread to report progress estimates
22061            new Thread() {
22062                @Override
22063                public void run() {
22064                    while (true) {
22065                        try {
22066                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22067                                break;
22068                            }
22069                        } catch (InterruptedException ignored) {
22070                        }
22071
22072                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
22073                        final int progress = 10 + (int) MathUtils.constrain(
22074                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22075                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22076                    }
22077                }
22078            }.start();
22079
22080            final String dataAppName = codeFile.getName();
22081            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22082                    dataAppName, appId, seinfo, targetSdkVersion);
22083        } else {
22084            move = null;
22085        }
22086
22087        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22088
22089        final Message msg = mHandler.obtainMessage(INIT_COPY);
22090        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22091        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22092                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22093                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22094                PackageManager.INSTALL_REASON_UNKNOWN);
22095        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22096        msg.obj = params;
22097
22098        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22099                System.identityHashCode(msg.obj));
22100        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22101                System.identityHashCode(msg.obj));
22102
22103        mHandler.sendMessage(msg);
22104    }
22105
22106    @Override
22107    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22108        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22109
22110        final int realMoveId = mNextMoveId.getAndIncrement();
22111        final Bundle extras = new Bundle();
22112        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22113        mMoveCallbacks.notifyCreated(realMoveId, extras);
22114
22115        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22116            @Override
22117            public void onCreated(int moveId, Bundle extras) {
22118                // Ignored
22119            }
22120
22121            @Override
22122            public void onStatusChanged(int moveId, int status, long estMillis) {
22123                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22124            }
22125        };
22126
22127        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22128        storage.setPrimaryStorageUuid(volumeUuid, callback);
22129        return realMoveId;
22130    }
22131
22132    @Override
22133    public int getMoveStatus(int moveId) {
22134        mContext.enforceCallingOrSelfPermission(
22135                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22136        return mMoveCallbacks.mLastStatus.get(moveId);
22137    }
22138
22139    @Override
22140    public void registerMoveCallback(IPackageMoveObserver callback) {
22141        mContext.enforceCallingOrSelfPermission(
22142                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22143        mMoveCallbacks.register(callback);
22144    }
22145
22146    @Override
22147    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22148        mContext.enforceCallingOrSelfPermission(
22149                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22150        mMoveCallbacks.unregister(callback);
22151    }
22152
22153    @Override
22154    public boolean setInstallLocation(int loc) {
22155        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22156                null);
22157        if (getInstallLocation() == loc) {
22158            return true;
22159        }
22160        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22161                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22162            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22163                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22164            return true;
22165        }
22166        return false;
22167   }
22168
22169    @Override
22170    public int getInstallLocation() {
22171        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22172                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22173                PackageHelper.APP_INSTALL_AUTO);
22174    }
22175
22176    /** Called by UserManagerService */
22177    void cleanUpUser(UserManagerService userManager, int userHandle) {
22178        synchronized (mPackages) {
22179            mDirtyUsers.remove(userHandle);
22180            mUserNeedsBadging.delete(userHandle);
22181            mSettings.removeUserLPw(userHandle);
22182            mPendingBroadcasts.remove(userHandle);
22183            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22184            removeUnusedPackagesLPw(userManager, userHandle);
22185        }
22186    }
22187
22188    /**
22189     * We're removing userHandle and would like to remove any downloaded packages
22190     * that are no longer in use by any other user.
22191     * @param userHandle the user being removed
22192     */
22193    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22194        final boolean DEBUG_CLEAN_APKS = false;
22195        int [] users = userManager.getUserIds();
22196        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22197        while (psit.hasNext()) {
22198            PackageSetting ps = psit.next();
22199            if (ps.pkg == null) {
22200                continue;
22201            }
22202            final String packageName = ps.pkg.packageName;
22203            // Skip over if system app
22204            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22205                continue;
22206            }
22207            if (DEBUG_CLEAN_APKS) {
22208                Slog.i(TAG, "Checking package " + packageName);
22209            }
22210            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22211            if (keep) {
22212                if (DEBUG_CLEAN_APKS) {
22213                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22214                }
22215            } else {
22216                for (int i = 0; i < users.length; i++) {
22217                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22218                        keep = true;
22219                        if (DEBUG_CLEAN_APKS) {
22220                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22221                                    + users[i]);
22222                        }
22223                        break;
22224                    }
22225                }
22226            }
22227            if (!keep) {
22228                if (DEBUG_CLEAN_APKS) {
22229                    Slog.i(TAG, "  Removing package " + packageName);
22230                }
22231                mHandler.post(new Runnable() {
22232                    public void run() {
22233                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22234                                userHandle, 0);
22235                    } //end run
22236                });
22237            }
22238        }
22239    }
22240
22241    /** Called by UserManagerService */
22242    void createNewUser(int userId, String[] disallowedPackages) {
22243        synchronized (mInstallLock) {
22244            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22245        }
22246        synchronized (mPackages) {
22247            scheduleWritePackageRestrictionsLocked(userId);
22248            scheduleWritePackageListLocked(userId);
22249            applyFactoryDefaultBrowserLPw(userId);
22250            primeDomainVerificationsLPw(userId);
22251        }
22252    }
22253
22254    void onNewUserCreated(final int userId) {
22255        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22256        // If permission review for legacy apps is required, we represent
22257        // dagerous permissions for such apps as always granted runtime
22258        // permissions to keep per user flag state whether review is needed.
22259        // Hence, if a new user is added we have to propagate dangerous
22260        // permission grants for these legacy apps.
22261        if (mPermissionReviewRequired) {
22262            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
22263                    | UPDATE_PERMISSIONS_REPLACE_ALL);
22264        }
22265    }
22266
22267    @Override
22268    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22269        mContext.enforceCallingOrSelfPermission(
22270                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22271                "Only package verification agents can read the verifier device identity");
22272
22273        synchronized (mPackages) {
22274            return mSettings.getVerifierDeviceIdentityLPw();
22275        }
22276    }
22277
22278    @Override
22279    public void setPermissionEnforced(String permission, boolean enforced) {
22280        // TODO: Now that we no longer change GID for storage, this should to away.
22281        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22282                "setPermissionEnforced");
22283        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22284            synchronized (mPackages) {
22285                if (mSettings.mReadExternalStorageEnforced == null
22286                        || mSettings.mReadExternalStorageEnforced != enforced) {
22287                    mSettings.mReadExternalStorageEnforced = enforced;
22288                    mSettings.writeLPr();
22289                }
22290            }
22291            // kill any non-foreground processes so we restart them and
22292            // grant/revoke the GID.
22293            final IActivityManager am = ActivityManager.getService();
22294            if (am != null) {
22295                final long token = Binder.clearCallingIdentity();
22296                try {
22297                    am.killProcessesBelowForeground("setPermissionEnforcement");
22298                } catch (RemoteException e) {
22299                } finally {
22300                    Binder.restoreCallingIdentity(token);
22301                }
22302            }
22303        } else {
22304            throw new IllegalArgumentException("No selective enforcement for " + permission);
22305        }
22306    }
22307
22308    @Override
22309    @Deprecated
22310    public boolean isPermissionEnforced(String permission) {
22311        return true;
22312    }
22313
22314    @Override
22315    public boolean isStorageLow() {
22316        final long token = Binder.clearCallingIdentity();
22317        try {
22318            final DeviceStorageMonitorInternal
22319                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22320            if (dsm != null) {
22321                return dsm.isMemoryLow();
22322            } else {
22323                return false;
22324            }
22325        } finally {
22326            Binder.restoreCallingIdentity(token);
22327        }
22328    }
22329
22330    @Override
22331    public IPackageInstaller getPackageInstaller() {
22332        return mInstallerService;
22333    }
22334
22335    private boolean userNeedsBadging(int userId) {
22336        int index = mUserNeedsBadging.indexOfKey(userId);
22337        if (index < 0) {
22338            final UserInfo userInfo;
22339            final long token = Binder.clearCallingIdentity();
22340            try {
22341                userInfo = sUserManager.getUserInfo(userId);
22342            } finally {
22343                Binder.restoreCallingIdentity(token);
22344            }
22345            final boolean b;
22346            if (userInfo != null && userInfo.isManagedProfile()) {
22347                b = true;
22348            } else {
22349                b = false;
22350            }
22351            mUserNeedsBadging.put(userId, b);
22352            return b;
22353        }
22354        return mUserNeedsBadging.valueAt(index);
22355    }
22356
22357    @Override
22358    public KeySet getKeySetByAlias(String packageName, String alias) {
22359        if (packageName == null || alias == null) {
22360            return null;
22361        }
22362        synchronized(mPackages) {
22363            final PackageParser.Package pkg = mPackages.get(packageName);
22364            if (pkg == null) {
22365                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22366                throw new IllegalArgumentException("Unknown package: " + packageName);
22367            }
22368            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22369            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22370        }
22371    }
22372
22373    @Override
22374    public KeySet getSigningKeySet(String packageName) {
22375        if (packageName == null) {
22376            return null;
22377        }
22378        synchronized(mPackages) {
22379            final PackageParser.Package pkg = mPackages.get(packageName);
22380            if (pkg == null) {
22381                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22382                throw new IllegalArgumentException("Unknown package: " + packageName);
22383            }
22384            if (pkg.applicationInfo.uid != Binder.getCallingUid()
22385                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
22386                throw new SecurityException("May not access signing KeySet of other apps.");
22387            }
22388            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22389            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22390        }
22391    }
22392
22393    @Override
22394    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22395        if (packageName == null || ks == null) {
22396            return false;
22397        }
22398        synchronized(mPackages) {
22399            final PackageParser.Package pkg = mPackages.get(packageName);
22400            if (pkg == null) {
22401                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22402                throw new IllegalArgumentException("Unknown package: " + packageName);
22403            }
22404            IBinder ksh = ks.getToken();
22405            if (ksh instanceof KeySetHandle) {
22406                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22407                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22408            }
22409            return false;
22410        }
22411    }
22412
22413    @Override
22414    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22415        if (packageName == null || ks == null) {
22416            return false;
22417        }
22418        synchronized(mPackages) {
22419            final PackageParser.Package pkg = mPackages.get(packageName);
22420            if (pkg == null) {
22421                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22422                throw new IllegalArgumentException("Unknown package: " + packageName);
22423            }
22424            IBinder ksh = ks.getToken();
22425            if (ksh instanceof KeySetHandle) {
22426                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22427                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22428            }
22429            return false;
22430        }
22431    }
22432
22433    private void deletePackageIfUnusedLPr(final String packageName) {
22434        PackageSetting ps = mSettings.mPackages.get(packageName);
22435        if (ps == null) {
22436            return;
22437        }
22438        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22439            // TODO Implement atomic delete if package is unused
22440            // It is currently possible that the package will be deleted even if it is installed
22441            // after this method returns.
22442            mHandler.post(new Runnable() {
22443                public void run() {
22444                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22445                            0, PackageManager.DELETE_ALL_USERS);
22446                }
22447            });
22448        }
22449    }
22450
22451    /**
22452     * Check and throw if the given before/after packages would be considered a
22453     * downgrade.
22454     */
22455    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22456            throws PackageManagerException {
22457        if (after.versionCode < before.mVersionCode) {
22458            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22459                    "Update version code " + after.versionCode + " is older than current "
22460                    + before.mVersionCode);
22461        } else if (after.versionCode == before.mVersionCode) {
22462            if (after.baseRevisionCode < before.baseRevisionCode) {
22463                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22464                        "Update base revision code " + after.baseRevisionCode
22465                        + " is older than current " + before.baseRevisionCode);
22466            }
22467
22468            if (!ArrayUtils.isEmpty(after.splitNames)) {
22469                for (int i = 0; i < after.splitNames.length; i++) {
22470                    final String splitName = after.splitNames[i];
22471                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22472                    if (j != -1) {
22473                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22474                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22475                                    "Update split " + splitName + " revision code "
22476                                    + after.splitRevisionCodes[i] + " is older than current "
22477                                    + before.splitRevisionCodes[j]);
22478                        }
22479                    }
22480                }
22481            }
22482        }
22483    }
22484
22485    private static class MoveCallbacks extends Handler {
22486        private static final int MSG_CREATED = 1;
22487        private static final int MSG_STATUS_CHANGED = 2;
22488
22489        private final RemoteCallbackList<IPackageMoveObserver>
22490                mCallbacks = new RemoteCallbackList<>();
22491
22492        private final SparseIntArray mLastStatus = new SparseIntArray();
22493
22494        public MoveCallbacks(Looper looper) {
22495            super(looper);
22496        }
22497
22498        public void register(IPackageMoveObserver callback) {
22499            mCallbacks.register(callback);
22500        }
22501
22502        public void unregister(IPackageMoveObserver callback) {
22503            mCallbacks.unregister(callback);
22504        }
22505
22506        @Override
22507        public void handleMessage(Message msg) {
22508            final SomeArgs args = (SomeArgs) msg.obj;
22509            final int n = mCallbacks.beginBroadcast();
22510            for (int i = 0; i < n; i++) {
22511                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22512                try {
22513                    invokeCallback(callback, msg.what, args);
22514                } catch (RemoteException ignored) {
22515                }
22516            }
22517            mCallbacks.finishBroadcast();
22518            args.recycle();
22519        }
22520
22521        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22522                throws RemoteException {
22523            switch (what) {
22524                case MSG_CREATED: {
22525                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22526                    break;
22527                }
22528                case MSG_STATUS_CHANGED: {
22529                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22530                    break;
22531                }
22532            }
22533        }
22534
22535        private void notifyCreated(int moveId, Bundle extras) {
22536            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22537
22538            final SomeArgs args = SomeArgs.obtain();
22539            args.argi1 = moveId;
22540            args.arg2 = extras;
22541            obtainMessage(MSG_CREATED, args).sendToTarget();
22542        }
22543
22544        private void notifyStatusChanged(int moveId, int status) {
22545            notifyStatusChanged(moveId, status, -1);
22546        }
22547
22548        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22549            Slog.v(TAG, "Move " + moveId + " status " + status);
22550
22551            final SomeArgs args = SomeArgs.obtain();
22552            args.argi1 = moveId;
22553            args.argi2 = status;
22554            args.arg3 = estMillis;
22555            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22556
22557            synchronized (mLastStatus) {
22558                mLastStatus.put(moveId, status);
22559            }
22560        }
22561    }
22562
22563    private final static class OnPermissionChangeListeners extends Handler {
22564        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22565
22566        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22567                new RemoteCallbackList<>();
22568
22569        public OnPermissionChangeListeners(Looper looper) {
22570            super(looper);
22571        }
22572
22573        @Override
22574        public void handleMessage(Message msg) {
22575            switch (msg.what) {
22576                case MSG_ON_PERMISSIONS_CHANGED: {
22577                    final int uid = msg.arg1;
22578                    handleOnPermissionsChanged(uid);
22579                } break;
22580            }
22581        }
22582
22583        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22584            mPermissionListeners.register(listener);
22585
22586        }
22587
22588        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22589            mPermissionListeners.unregister(listener);
22590        }
22591
22592        public void onPermissionsChanged(int uid) {
22593            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22594                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22595            }
22596        }
22597
22598        private void handleOnPermissionsChanged(int uid) {
22599            final int count = mPermissionListeners.beginBroadcast();
22600            try {
22601                for (int i = 0; i < count; i++) {
22602                    IOnPermissionsChangeListener callback = mPermissionListeners
22603                            .getBroadcastItem(i);
22604                    try {
22605                        callback.onPermissionsChanged(uid);
22606                    } catch (RemoteException e) {
22607                        Log.e(TAG, "Permission listener is dead", e);
22608                    }
22609                }
22610            } finally {
22611                mPermissionListeners.finishBroadcast();
22612            }
22613        }
22614    }
22615
22616    private class PackageManagerInternalImpl extends PackageManagerInternal {
22617        @Override
22618        public void setLocationPackagesProvider(PackagesProvider provider) {
22619            synchronized (mPackages) {
22620                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
22621            }
22622        }
22623
22624        @Override
22625        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22626            synchronized (mPackages) {
22627                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
22628            }
22629        }
22630
22631        @Override
22632        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22633            synchronized (mPackages) {
22634                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
22635            }
22636        }
22637
22638        @Override
22639        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22640            synchronized (mPackages) {
22641                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
22642            }
22643        }
22644
22645        @Override
22646        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22647            synchronized (mPackages) {
22648                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
22649            }
22650        }
22651
22652        @Override
22653        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22654            synchronized (mPackages) {
22655                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
22656            }
22657        }
22658
22659        @Override
22660        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
22661            synchronized (mPackages) {
22662                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
22663                        packageName, userId);
22664            }
22665        }
22666
22667        @Override
22668        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
22669            synchronized (mPackages) {
22670                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
22671                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
22672                        packageName, userId);
22673            }
22674        }
22675
22676        @Override
22677        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
22678            synchronized (mPackages) {
22679                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
22680                        packageName, userId);
22681            }
22682        }
22683
22684        @Override
22685        public void setKeepUninstalledPackages(final List<String> packageList) {
22686            Preconditions.checkNotNull(packageList);
22687            List<String> removedFromList = null;
22688            synchronized (mPackages) {
22689                if (mKeepUninstalledPackages != null) {
22690                    final int packagesCount = mKeepUninstalledPackages.size();
22691                    for (int i = 0; i < packagesCount; i++) {
22692                        String oldPackage = mKeepUninstalledPackages.get(i);
22693                        if (packageList != null && packageList.contains(oldPackage)) {
22694                            continue;
22695                        }
22696                        if (removedFromList == null) {
22697                            removedFromList = new ArrayList<>();
22698                        }
22699                        removedFromList.add(oldPackage);
22700                    }
22701                }
22702                mKeepUninstalledPackages = new ArrayList<>(packageList);
22703                if (removedFromList != null) {
22704                    final int removedCount = removedFromList.size();
22705                    for (int i = 0; i < removedCount; i++) {
22706                        deletePackageIfUnusedLPr(removedFromList.get(i));
22707                    }
22708                }
22709            }
22710        }
22711
22712        @Override
22713        public boolean isPermissionsReviewRequired(String packageName, int userId) {
22714            synchronized (mPackages) {
22715                // If we do not support permission review, done.
22716                if (!mPermissionReviewRequired) {
22717                    return false;
22718                }
22719
22720                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
22721                if (packageSetting == null) {
22722                    return false;
22723                }
22724
22725                // Permission review applies only to apps not supporting the new permission model.
22726                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
22727                    return false;
22728                }
22729
22730                // Legacy apps have the permission and get user consent on launch.
22731                PermissionsState permissionsState = packageSetting.getPermissionsState();
22732                return permissionsState.isPermissionReviewRequired(userId);
22733            }
22734        }
22735
22736        @Override
22737        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
22738            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
22739        }
22740
22741        @Override
22742        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
22743                int userId) {
22744            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
22745        }
22746
22747        @Override
22748        public void setDeviceAndProfileOwnerPackages(
22749                int deviceOwnerUserId, String deviceOwnerPackage,
22750                SparseArray<String> profileOwnerPackages) {
22751            mProtectedPackages.setDeviceAndProfileOwnerPackages(
22752                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
22753        }
22754
22755        @Override
22756        public boolean isPackageDataProtected(int userId, String packageName) {
22757            return mProtectedPackages.isPackageDataProtected(userId, packageName);
22758        }
22759
22760        @Override
22761        public boolean isPackageEphemeral(int userId, String packageName) {
22762            synchronized (mPackages) {
22763                PackageParser.Package p = mPackages.get(packageName);
22764                return p != null ? p.applicationInfo.isInstantApp() : false;
22765            }
22766        }
22767
22768        @Override
22769        public boolean wasPackageEverLaunched(String packageName, int userId) {
22770            synchronized (mPackages) {
22771                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
22772            }
22773        }
22774
22775        @Override
22776        public void grantRuntimePermission(String packageName, String name, int userId,
22777                boolean overridePolicy) {
22778            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
22779                    overridePolicy);
22780        }
22781
22782        @Override
22783        public void revokeRuntimePermission(String packageName, String name, int userId,
22784                boolean overridePolicy) {
22785            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
22786                    overridePolicy);
22787        }
22788
22789        @Override
22790        public String getNameForUid(int uid) {
22791            return PackageManagerService.this.getNameForUid(uid);
22792        }
22793
22794        @Override
22795        public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
22796                Intent origIntent, String resolvedType, Intent launchIntent,
22797                String callingPackage, int userId) {
22798            PackageManagerService.this.requestEphemeralResolutionPhaseTwo(
22799                    responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId);
22800        }
22801
22802        @Override
22803        public void grantEphemeralAccess(int userId, Intent intent,
22804                int targetAppId, int ephemeralAppId) {
22805            synchronized (mPackages) {
22806                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
22807                        targetAppId, ephemeralAppId);
22808            }
22809        }
22810
22811        @Override
22812        public void pruneInstantApps() {
22813            synchronized (mPackages) {
22814                mInstantAppRegistry.pruneInstantAppsLPw();
22815            }
22816        }
22817
22818        @Override
22819        public String getSetupWizardPackageName() {
22820            return mSetupWizardPackage;
22821        }
22822
22823        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
22824            if (policy != null) {
22825                mExternalSourcesPolicy = policy;
22826            }
22827        }
22828
22829        @Override
22830        public List<PackageInfo> getOverlayPackages(int userId) {
22831            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
22832            synchronized (mPackages) {
22833                for (PackageParser.Package p : mPackages.values()) {
22834                    if (p.mOverlayTarget != null) {
22835                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
22836                        if (pkg != null) {
22837                            overlayPackages.add(pkg);
22838                        }
22839                    }
22840                }
22841            }
22842            return overlayPackages;
22843        }
22844
22845        @Override
22846        public List<String> getTargetPackageNames(int userId) {
22847            List<String> targetPackages = new ArrayList<>();
22848            synchronized (mPackages) {
22849                for (PackageParser.Package p : mPackages.values()) {
22850                    if (p.mOverlayTarget == null) {
22851                        targetPackages.add(p.packageName);
22852                    }
22853                }
22854            }
22855            return targetPackages;
22856        }
22857
22858
22859        @Override
22860        public boolean setEnabledOverlayPackages(int userId, String targetPackageName,
22861                List<String> overlayPackageNames) {
22862            // TODO: implement when we integrate OMS properly
22863            return false;
22864        }
22865    }
22866
22867    @Override
22868    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
22869        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
22870        synchronized (mPackages) {
22871            final long identity = Binder.clearCallingIdentity();
22872            try {
22873                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
22874                        packageNames, userId);
22875            } finally {
22876                Binder.restoreCallingIdentity(identity);
22877            }
22878        }
22879    }
22880
22881    @Override
22882    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
22883        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
22884        synchronized (mPackages) {
22885            final long identity = Binder.clearCallingIdentity();
22886            try {
22887                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
22888                        packageNames, userId);
22889            } finally {
22890                Binder.restoreCallingIdentity(identity);
22891            }
22892        }
22893    }
22894
22895    private static void enforceSystemOrPhoneCaller(String tag) {
22896        int callingUid = Binder.getCallingUid();
22897        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
22898            throw new SecurityException(
22899                    "Cannot call " + tag + " from UID " + callingUid);
22900        }
22901    }
22902
22903    boolean isHistoricalPackageUsageAvailable() {
22904        return mPackageUsage.isHistoricalPackageUsageAvailable();
22905    }
22906
22907    /**
22908     * Return a <b>copy</b> of the collection of packages known to the package manager.
22909     * @return A copy of the values of mPackages.
22910     */
22911    Collection<PackageParser.Package> getPackages() {
22912        synchronized (mPackages) {
22913            return new ArrayList<>(mPackages.values());
22914        }
22915    }
22916
22917    /**
22918     * Logs process start information (including base APK hash) to the security log.
22919     * @hide
22920     */
22921    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
22922            String apkFile, int pid) {
22923        if (!SecurityLog.isLoggingEnabled()) {
22924            return;
22925        }
22926        Bundle data = new Bundle();
22927        data.putLong("startTimestamp", System.currentTimeMillis());
22928        data.putString("processName", processName);
22929        data.putInt("uid", uid);
22930        data.putString("seinfo", seinfo);
22931        data.putString("apkFile", apkFile);
22932        data.putInt("pid", pid);
22933        Message msg = mProcessLoggingHandler.obtainMessage(
22934                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
22935        msg.setData(data);
22936        mProcessLoggingHandler.sendMessage(msg);
22937    }
22938
22939    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
22940        return mCompilerStats.getPackageStats(pkgName);
22941    }
22942
22943    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
22944        return getOrCreateCompilerPackageStats(pkg.packageName);
22945    }
22946
22947    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
22948        return mCompilerStats.getOrCreatePackageStats(pkgName);
22949    }
22950
22951    public void deleteCompilerPackageStats(String pkgName) {
22952        mCompilerStats.deletePackageStats(pkgName);
22953    }
22954
22955    @Override
22956    public int getInstallReason(String packageName, int userId) {
22957        enforceCrossUserPermission(Binder.getCallingUid(), userId,
22958                true /* requireFullPermission */, false /* checkShell */,
22959                "get install reason");
22960        synchronized (mPackages) {
22961            final PackageSetting ps = mSettings.mPackages.get(packageName);
22962            if (ps != null) {
22963                return ps.getInstallReason(userId);
22964            }
22965        }
22966        return PackageManager.INSTALL_REASON_UNKNOWN;
22967    }
22968
22969    @Override
22970    public boolean canRequestPackageInstalls(String packageName, int userId) {
22971        int callingUid = Binder.getCallingUid();
22972        int uid = getPackageUid(packageName, 0, userId);
22973        if (callingUid != uid && callingUid != Process.ROOT_UID
22974                && callingUid != Process.SYSTEM_UID) {
22975            throw new SecurityException(
22976                    "Caller uid " + callingUid + " does not own package " + packageName);
22977        }
22978        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
22979        if (info == null) {
22980            return false;
22981        }
22982        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
22983            throw new UnsupportedOperationException(
22984                    "Operation only supported on apps targeting Android O or higher");
22985        }
22986        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
22987        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
22988        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
22989            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
22990        }
22991        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
22992            return false;
22993        }
22994        if (mExternalSourcesPolicy != null) {
22995            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
22996            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
22997                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
22998            }
22999        }
23000        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
23001    }
23002}
23003