PackageManagerService.java revision 096d304ae3d85c1bfcda1a1d9cd4eb13d0815500
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    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
716
717    // If mac_permissions.xml was found for seinfo labeling.
718    boolean mFoundPolicyFile;
719
720    private final InstantAppRegistry mInstantAppRegistry;
721
722    public static final class SharedLibraryEntry {
723        public final String path;
724        public final String apk;
725        public final SharedLibraryInfo info;
726
727        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
728                String declaringPackageName, int declaringPackageVersionCode) {
729            path = _path;
730            apk = _apk;
731            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
732                    declaringPackageName, declaringPackageVersionCode), null);
733        }
734    }
735
736    // Currently known shared libraries.
737    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
738    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
739            new ArrayMap<>();
740
741    // All available activities, for your resolving pleasure.
742    final ActivityIntentResolver mActivities =
743            new ActivityIntentResolver();
744
745    // All available receivers, for your resolving pleasure.
746    final ActivityIntentResolver mReceivers =
747            new ActivityIntentResolver();
748
749    // All available services, for your resolving pleasure.
750    final ServiceIntentResolver mServices = new ServiceIntentResolver();
751
752    // All available providers, for your resolving pleasure.
753    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
754
755    // Mapping from provider base names (first directory in content URI codePath)
756    // to the provider information.
757    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
758            new ArrayMap<String, PackageParser.Provider>();
759
760    // Mapping from instrumentation class names to info about them.
761    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
762            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
763
764    // Mapping from permission names to info about them.
765    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
766            new ArrayMap<String, PackageParser.PermissionGroup>();
767
768    // Packages whose data we have transfered into another package, thus
769    // should no longer exist.
770    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
771
772    // Broadcast actions that are only available to the system.
773    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
774
775    /** List of packages waiting for verification. */
776    final SparseArray<PackageVerificationState> mPendingVerification
777            = new SparseArray<PackageVerificationState>();
778
779    /** Set of packages associated with each app op permission. */
780    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
781
782    final PackageInstallerService mInstallerService;
783
784    private final PackageDexOptimizer mPackageDexOptimizer;
785    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
786    // is used by other apps).
787    private final DexManager mDexManager;
788
789    private AtomicInteger mNextMoveId = new AtomicInteger();
790    private final MoveCallbacks mMoveCallbacks;
791
792    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
793
794    // Cache of users who need badging.
795    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
796
797    /** Token for keys in mPendingVerification. */
798    private int mPendingVerificationToken = 0;
799
800    volatile boolean mSystemReady;
801    volatile boolean mSafeMode;
802    volatile boolean mHasSystemUidErrors;
803
804    ApplicationInfo mAndroidApplication;
805    final ActivityInfo mResolveActivity = new ActivityInfo();
806    final ResolveInfo mResolveInfo = new ResolveInfo();
807    ComponentName mResolveComponentName;
808    PackageParser.Package mPlatformPackage;
809    ComponentName mCustomResolverComponentName;
810
811    boolean mResolverReplaced = false;
812
813    private final @Nullable ComponentName mIntentFilterVerifierComponent;
814    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
815
816    private int mIntentFilterVerificationToken = 0;
817
818    /** The service connection to the ephemeral resolver */
819    final EphemeralResolverConnection mEphemeralResolverConnection;
820
821    /** Component used to install ephemeral applications */
822    ComponentName mEphemeralInstallerComponent;
823    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
824    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
825
826    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
827            = new SparseArray<IntentFilterVerificationState>();
828
829    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
830
831    // List of packages names to keep cached, even if they are uninstalled for all users
832    private List<String> mKeepUninstalledPackages;
833
834    private UserManagerInternal mUserManagerInternal;
835    private final UserDataPreparer mUserDataPreparer;
836
837    private File mCacheDir;
838
839    private static class IFVerificationParams {
840        PackageParser.Package pkg;
841        boolean replacing;
842        int userId;
843        int verifierUid;
844
845        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
846                int _userId, int _verifierUid) {
847            pkg = _pkg;
848            replacing = _replacing;
849            userId = _userId;
850            replacing = _replacing;
851            verifierUid = _verifierUid;
852        }
853    }
854
855    private interface IntentFilterVerifier<T extends IntentFilter> {
856        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
857                                               T filter, String packageName);
858        void startVerifications(int userId);
859        void receiveVerificationResponse(int verificationId);
860    }
861
862    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
863        private Context mContext;
864        private ComponentName mIntentFilterVerifierComponent;
865        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
866
867        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
868            mContext = context;
869            mIntentFilterVerifierComponent = verifierComponent;
870        }
871
872        private String getDefaultScheme() {
873            return IntentFilter.SCHEME_HTTPS;
874        }
875
876        @Override
877        public void startVerifications(int userId) {
878            // Launch verifications requests
879            int count = mCurrentIntentFilterVerifications.size();
880            for (int n=0; n<count; n++) {
881                int verificationId = mCurrentIntentFilterVerifications.get(n);
882                final IntentFilterVerificationState ivs =
883                        mIntentFilterVerificationStates.get(verificationId);
884
885                String packageName = ivs.getPackageName();
886
887                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
888                final int filterCount = filters.size();
889                ArraySet<String> domainsSet = new ArraySet<>();
890                for (int m=0; m<filterCount; m++) {
891                    PackageParser.ActivityIntentInfo filter = filters.get(m);
892                    domainsSet.addAll(filter.getHostsList());
893                }
894                synchronized (mPackages) {
895                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
896                            packageName, domainsSet) != null) {
897                        scheduleWriteSettingsLocked();
898                    }
899                }
900                sendVerificationRequest(userId, verificationId, ivs);
901            }
902            mCurrentIntentFilterVerifications.clear();
903        }
904
905        private void sendVerificationRequest(int userId, int verificationId,
906                IntentFilterVerificationState ivs) {
907
908            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
909            verificationIntent.putExtra(
910                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
911                    verificationId);
912            verificationIntent.putExtra(
913                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
914                    getDefaultScheme());
915            verificationIntent.putExtra(
916                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
917                    ivs.getHostsString());
918            verificationIntent.putExtra(
919                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
920                    ivs.getPackageName());
921            verificationIntent.setComponent(mIntentFilterVerifierComponent);
922            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
923
924            UserHandle user = new UserHandle(userId);
925            mContext.sendBroadcastAsUser(verificationIntent, user);
926            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
927                    "Sending IntentFilter verification broadcast");
928        }
929
930        public void receiveVerificationResponse(int verificationId) {
931            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
932
933            final boolean verified = ivs.isVerified();
934
935            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
936            final int count = filters.size();
937            if (DEBUG_DOMAIN_VERIFICATION) {
938                Slog.i(TAG, "Received verification response " + verificationId
939                        + " for " + count + " filters, verified=" + verified);
940            }
941            for (int n=0; n<count; n++) {
942                PackageParser.ActivityIntentInfo filter = filters.get(n);
943                filter.setVerified(verified);
944
945                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
946                        + " verified with result:" + verified + " and hosts:"
947                        + ivs.getHostsString());
948            }
949
950            mIntentFilterVerificationStates.remove(verificationId);
951
952            final String packageName = ivs.getPackageName();
953            IntentFilterVerificationInfo ivi = null;
954
955            synchronized (mPackages) {
956                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
957            }
958            if (ivi == null) {
959                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
960                        + verificationId + " packageName:" + packageName);
961                return;
962            }
963            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
964                    "Updating IntentFilterVerificationInfo for package " + packageName
965                            +" verificationId:" + verificationId);
966
967            synchronized (mPackages) {
968                if (verified) {
969                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
970                } else {
971                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
972                }
973                scheduleWriteSettingsLocked();
974
975                final int userId = ivs.getUserId();
976                if (userId != UserHandle.USER_ALL) {
977                    final int userStatus =
978                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
979
980                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
981                    boolean needUpdate = false;
982
983                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
984                    // already been set by the User thru the Disambiguation dialog
985                    switch (userStatus) {
986                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
987                            if (verified) {
988                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
989                            } else {
990                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
991                            }
992                            needUpdate = true;
993                            break;
994
995                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
996                            if (verified) {
997                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
998                                needUpdate = true;
999                            }
1000                            break;
1001
1002                        default:
1003                            // Nothing to do
1004                    }
1005
1006                    if (needUpdate) {
1007                        mSettings.updateIntentFilterVerificationStatusLPw(
1008                                packageName, updatedStatus, userId);
1009                        scheduleWritePackageRestrictionsLocked(userId);
1010                    }
1011                }
1012            }
1013        }
1014
1015        @Override
1016        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1017                    ActivityIntentInfo filter, String packageName) {
1018            if (!hasValidDomains(filter)) {
1019                return false;
1020            }
1021            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1022            if (ivs == null) {
1023                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1024                        packageName);
1025            }
1026            if (DEBUG_DOMAIN_VERIFICATION) {
1027                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1028            }
1029            ivs.addFilter(filter);
1030            return true;
1031        }
1032
1033        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1034                int userId, int verificationId, String packageName) {
1035            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1036                    verifierUid, userId, packageName);
1037            ivs.setPendingState();
1038            synchronized (mPackages) {
1039                mIntentFilterVerificationStates.append(verificationId, ivs);
1040                mCurrentIntentFilterVerifications.add(verificationId);
1041            }
1042            return ivs;
1043        }
1044    }
1045
1046    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1047        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1048                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1049                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1050    }
1051
1052    // Set of pending broadcasts for aggregating enable/disable of components.
1053    static class PendingPackageBroadcasts {
1054        // for each user id, a map of <package name -> components within that package>
1055        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1056
1057        public PendingPackageBroadcasts() {
1058            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1059        }
1060
1061        public ArrayList<String> get(int userId, String packageName) {
1062            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1063            return packages.get(packageName);
1064        }
1065
1066        public void put(int userId, String packageName, ArrayList<String> components) {
1067            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1068            packages.put(packageName, components);
1069        }
1070
1071        public void remove(int userId, String packageName) {
1072            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1073            if (packages != null) {
1074                packages.remove(packageName);
1075            }
1076        }
1077
1078        public void remove(int userId) {
1079            mUidMap.remove(userId);
1080        }
1081
1082        public int userIdCount() {
1083            return mUidMap.size();
1084        }
1085
1086        public int userIdAt(int n) {
1087            return mUidMap.keyAt(n);
1088        }
1089
1090        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1091            return mUidMap.get(userId);
1092        }
1093
1094        public int size() {
1095            // total number of pending broadcast entries across all userIds
1096            int num = 0;
1097            for (int i = 0; i< mUidMap.size(); i++) {
1098                num += mUidMap.valueAt(i).size();
1099            }
1100            return num;
1101        }
1102
1103        public void clear() {
1104            mUidMap.clear();
1105        }
1106
1107        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1108            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1109            if (map == null) {
1110                map = new ArrayMap<String, ArrayList<String>>();
1111                mUidMap.put(userId, map);
1112            }
1113            return map;
1114        }
1115    }
1116    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1117
1118    // Service Connection to remote media container service to copy
1119    // package uri's from external media onto secure containers
1120    // or internal storage.
1121    private IMediaContainerService mContainerService = null;
1122
1123    static final int SEND_PENDING_BROADCAST = 1;
1124    static final int MCS_BOUND = 3;
1125    static final int END_COPY = 4;
1126    static final int INIT_COPY = 5;
1127    static final int MCS_UNBIND = 6;
1128    static final int START_CLEANING_PACKAGE = 7;
1129    static final int FIND_INSTALL_LOC = 8;
1130    static final int POST_INSTALL = 9;
1131    static final int MCS_RECONNECT = 10;
1132    static final int MCS_GIVE_UP = 11;
1133    static final int UPDATED_MEDIA_STATUS = 12;
1134    static final int WRITE_SETTINGS = 13;
1135    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1136    static final int PACKAGE_VERIFIED = 15;
1137    static final int CHECK_PENDING_VERIFICATION = 16;
1138    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1139    static final int INTENT_FILTER_VERIFIED = 18;
1140    static final int WRITE_PACKAGE_LIST = 19;
1141    static final int EPHEMERAL_RESOLUTION_PHASE_TWO = 20;
1142
1143    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1144
1145    // Delay time in millisecs
1146    static final int BROADCAST_DELAY = 10 * 1000;
1147
1148    static UserManagerService sUserManager;
1149
1150    // Stores a list of users whose package restrictions file needs to be updated
1151    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1152
1153    final private DefaultContainerConnection mDefContainerConn =
1154            new DefaultContainerConnection();
1155    class DefaultContainerConnection implements ServiceConnection {
1156        public void onServiceConnected(ComponentName name, IBinder service) {
1157            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1158            final IMediaContainerService imcs = IMediaContainerService.Stub
1159                    .asInterface(Binder.allowBlocking(service));
1160            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1161        }
1162
1163        public void onServiceDisconnected(ComponentName name) {
1164            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1165        }
1166    }
1167
1168    // Recordkeeping of restore-after-install operations that are currently in flight
1169    // between the Package Manager and the Backup Manager
1170    static class PostInstallData {
1171        public InstallArgs args;
1172        public PackageInstalledInfo res;
1173
1174        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1175            args = _a;
1176            res = _r;
1177        }
1178    }
1179
1180    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1181    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1182
1183    // XML tags for backup/restore of various bits of state
1184    private static final String TAG_PREFERRED_BACKUP = "pa";
1185    private static final String TAG_DEFAULT_APPS = "da";
1186    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1187
1188    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1189    private static final String TAG_ALL_GRANTS = "rt-grants";
1190    private static final String TAG_GRANT = "grant";
1191    private static final String ATTR_PACKAGE_NAME = "pkg";
1192
1193    private static final String TAG_PERMISSION = "perm";
1194    private static final String ATTR_PERMISSION_NAME = "name";
1195    private static final String ATTR_IS_GRANTED = "g";
1196    private static final String ATTR_USER_SET = "set";
1197    private static final String ATTR_USER_FIXED = "fixed";
1198    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1199
1200    // System/policy permission grants are not backed up
1201    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1202            FLAG_PERMISSION_POLICY_FIXED
1203            | FLAG_PERMISSION_SYSTEM_FIXED
1204            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1205
1206    // And we back up these user-adjusted states
1207    private static final int USER_RUNTIME_GRANT_MASK =
1208            FLAG_PERMISSION_USER_SET
1209            | FLAG_PERMISSION_USER_FIXED
1210            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1211
1212    final @Nullable String mRequiredVerifierPackage;
1213    final @NonNull String mRequiredInstallerPackage;
1214    final @NonNull String mRequiredUninstallerPackage;
1215    final @Nullable String mSetupWizardPackage;
1216    final @Nullable String mStorageManagerPackage;
1217    final @NonNull String mServicesSystemSharedLibraryPackageName;
1218    final @NonNull String mSharedSystemSharedLibraryPackageName;
1219
1220    final boolean mPermissionReviewRequired;
1221
1222    private final PackageUsage mPackageUsage = new PackageUsage();
1223    private final CompilerStats mCompilerStats = new CompilerStats();
1224
1225    class PackageHandler extends Handler {
1226        private boolean mBound = false;
1227        final ArrayList<HandlerParams> mPendingInstalls =
1228            new ArrayList<HandlerParams>();
1229
1230        private boolean connectToService() {
1231            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1232                    " DefaultContainerService");
1233            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1234            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1235            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1236                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1237                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1238                mBound = true;
1239                return true;
1240            }
1241            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1242            return false;
1243        }
1244
1245        private void disconnectService() {
1246            mContainerService = null;
1247            mBound = false;
1248            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1249            mContext.unbindService(mDefContainerConn);
1250            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1251        }
1252
1253        PackageHandler(Looper looper) {
1254            super(looper);
1255        }
1256
1257        public void handleMessage(Message msg) {
1258            try {
1259                doHandleMessage(msg);
1260            } finally {
1261                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1262            }
1263        }
1264
1265        void doHandleMessage(Message msg) {
1266            switch (msg.what) {
1267                case INIT_COPY: {
1268                    HandlerParams params = (HandlerParams) msg.obj;
1269                    int idx = mPendingInstalls.size();
1270                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1271                    // If a bind was already initiated we dont really
1272                    // need to do anything. The pending install
1273                    // will be processed later on.
1274                    if (!mBound) {
1275                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1276                                System.identityHashCode(mHandler));
1277                        // If this is the only one pending we might
1278                        // have to bind to the service again.
1279                        if (!connectToService()) {
1280                            Slog.e(TAG, "Failed to bind to media container service");
1281                            params.serviceError();
1282                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1283                                    System.identityHashCode(mHandler));
1284                            if (params.traceMethod != null) {
1285                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1286                                        params.traceCookie);
1287                            }
1288                            return;
1289                        } else {
1290                            // Once we bind to the service, the first
1291                            // pending request will be processed.
1292                            mPendingInstalls.add(idx, params);
1293                        }
1294                    } else {
1295                        mPendingInstalls.add(idx, params);
1296                        // Already bound to the service. Just make
1297                        // sure we trigger off processing the first request.
1298                        if (idx == 0) {
1299                            mHandler.sendEmptyMessage(MCS_BOUND);
1300                        }
1301                    }
1302                    break;
1303                }
1304                case MCS_BOUND: {
1305                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1306                    if (msg.obj != null) {
1307                        mContainerService = (IMediaContainerService) msg.obj;
1308                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1309                                System.identityHashCode(mHandler));
1310                    }
1311                    if (mContainerService == null) {
1312                        if (!mBound) {
1313                            // Something seriously wrong since we are not bound and we are not
1314                            // waiting for connection. Bail out.
1315                            Slog.e(TAG, "Cannot bind to media container service");
1316                            for (HandlerParams params : mPendingInstalls) {
1317                                // Indicate service bind error
1318                                params.serviceError();
1319                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1320                                        System.identityHashCode(params));
1321                                if (params.traceMethod != null) {
1322                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1323                                            params.traceMethod, params.traceCookie);
1324                                }
1325                                return;
1326                            }
1327                            mPendingInstalls.clear();
1328                        } else {
1329                            Slog.w(TAG, "Waiting to connect to media container service");
1330                        }
1331                    } else if (mPendingInstalls.size() > 0) {
1332                        HandlerParams params = mPendingInstalls.get(0);
1333                        if (params != null) {
1334                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1335                                    System.identityHashCode(params));
1336                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1337                            if (params.startCopy()) {
1338                                // We are done...  look for more work or to
1339                                // go idle.
1340                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1341                                        "Checking for more work or unbind...");
1342                                // Delete pending install
1343                                if (mPendingInstalls.size() > 0) {
1344                                    mPendingInstalls.remove(0);
1345                                }
1346                                if (mPendingInstalls.size() == 0) {
1347                                    if (mBound) {
1348                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1349                                                "Posting delayed MCS_UNBIND");
1350                                        removeMessages(MCS_UNBIND);
1351                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1352                                        // Unbind after a little delay, to avoid
1353                                        // continual thrashing.
1354                                        sendMessageDelayed(ubmsg, 10000);
1355                                    }
1356                                } else {
1357                                    // There are more pending requests in queue.
1358                                    // Just post MCS_BOUND message to trigger processing
1359                                    // of next pending install.
1360                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1361                                            "Posting MCS_BOUND for next work");
1362                                    mHandler.sendEmptyMessage(MCS_BOUND);
1363                                }
1364                            }
1365                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1366                        }
1367                    } else {
1368                        // Should never happen ideally.
1369                        Slog.w(TAG, "Empty queue");
1370                    }
1371                    break;
1372                }
1373                case MCS_RECONNECT: {
1374                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1375                    if (mPendingInstalls.size() > 0) {
1376                        if (mBound) {
1377                            disconnectService();
1378                        }
1379                        if (!connectToService()) {
1380                            Slog.e(TAG, "Failed to bind to media container service");
1381                            for (HandlerParams params : mPendingInstalls) {
1382                                // Indicate service bind error
1383                                params.serviceError();
1384                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1385                                        System.identityHashCode(params));
1386                            }
1387                            mPendingInstalls.clear();
1388                        }
1389                    }
1390                    break;
1391                }
1392                case MCS_UNBIND: {
1393                    // If there is no actual work left, then time to unbind.
1394                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1395
1396                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1397                        if (mBound) {
1398                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1399
1400                            disconnectService();
1401                        }
1402                    } else if (mPendingInstalls.size() > 0) {
1403                        // There are more pending requests in queue.
1404                        // Just post MCS_BOUND message to trigger processing
1405                        // of next pending install.
1406                        mHandler.sendEmptyMessage(MCS_BOUND);
1407                    }
1408
1409                    break;
1410                }
1411                case MCS_GIVE_UP: {
1412                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1413                    HandlerParams params = mPendingInstalls.remove(0);
1414                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1415                            System.identityHashCode(params));
1416                    break;
1417                }
1418                case SEND_PENDING_BROADCAST: {
1419                    String packages[];
1420                    ArrayList<String> components[];
1421                    int size = 0;
1422                    int uids[];
1423                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1424                    synchronized (mPackages) {
1425                        if (mPendingBroadcasts == null) {
1426                            return;
1427                        }
1428                        size = mPendingBroadcasts.size();
1429                        if (size <= 0) {
1430                            // Nothing to be done. Just return
1431                            return;
1432                        }
1433                        packages = new String[size];
1434                        components = new ArrayList[size];
1435                        uids = new int[size];
1436                        int i = 0;  // filling out the above arrays
1437
1438                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1439                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1440                            Iterator<Map.Entry<String, ArrayList<String>>> it
1441                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1442                                            .entrySet().iterator();
1443                            while (it.hasNext() && i < size) {
1444                                Map.Entry<String, ArrayList<String>> ent = it.next();
1445                                packages[i] = ent.getKey();
1446                                components[i] = ent.getValue();
1447                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1448                                uids[i] = (ps != null)
1449                                        ? UserHandle.getUid(packageUserId, ps.appId)
1450                                        : -1;
1451                                i++;
1452                            }
1453                        }
1454                        size = i;
1455                        mPendingBroadcasts.clear();
1456                    }
1457                    // Send broadcasts
1458                    for (int i = 0; i < size; i++) {
1459                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1460                    }
1461                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1462                    break;
1463                }
1464                case START_CLEANING_PACKAGE: {
1465                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1466                    final String packageName = (String)msg.obj;
1467                    final int userId = msg.arg1;
1468                    final boolean andCode = msg.arg2 != 0;
1469                    synchronized (mPackages) {
1470                        if (userId == UserHandle.USER_ALL) {
1471                            int[] users = sUserManager.getUserIds();
1472                            for (int user : users) {
1473                                mSettings.addPackageToCleanLPw(
1474                                        new PackageCleanItem(user, packageName, andCode));
1475                            }
1476                        } else {
1477                            mSettings.addPackageToCleanLPw(
1478                                    new PackageCleanItem(userId, packageName, andCode));
1479                        }
1480                    }
1481                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1482                    startCleaningPackages();
1483                } break;
1484                case POST_INSTALL: {
1485                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1486
1487                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1488                    final boolean didRestore = (msg.arg2 != 0);
1489                    mRunningInstalls.delete(msg.arg1);
1490
1491                    if (data != null) {
1492                        InstallArgs args = data.args;
1493                        PackageInstalledInfo parentRes = data.res;
1494
1495                        final boolean grantPermissions = (args.installFlags
1496                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1497                        final boolean killApp = (args.installFlags
1498                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1499                        final String[] grantedPermissions = args.installGrantPermissions;
1500
1501                        // Handle the parent package
1502                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1503                                grantedPermissions, didRestore, args.installerPackageName,
1504                                args.observer);
1505
1506                        // Handle the child packages
1507                        final int childCount = (parentRes.addedChildPackages != null)
1508                                ? parentRes.addedChildPackages.size() : 0;
1509                        for (int i = 0; i < childCount; i++) {
1510                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1511                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1512                                    grantedPermissions, false, args.installerPackageName,
1513                                    args.observer);
1514                        }
1515
1516                        // Log tracing if needed
1517                        if (args.traceMethod != null) {
1518                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1519                                    args.traceCookie);
1520                        }
1521                    } else {
1522                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1523                    }
1524
1525                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1526                } break;
1527                case UPDATED_MEDIA_STATUS: {
1528                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1529                    boolean reportStatus = msg.arg1 == 1;
1530                    boolean doGc = msg.arg2 == 1;
1531                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1532                    if (doGc) {
1533                        // Force a gc to clear up stale containers.
1534                        Runtime.getRuntime().gc();
1535                    }
1536                    if (msg.obj != null) {
1537                        @SuppressWarnings("unchecked")
1538                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1539                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1540                        // Unload containers
1541                        unloadAllContainers(args);
1542                    }
1543                    if (reportStatus) {
1544                        try {
1545                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1546                                    "Invoking StorageManagerService call back");
1547                            PackageHelper.getStorageManager().finishMediaUpdate();
1548                        } catch (RemoteException e) {
1549                            Log.e(TAG, "StorageManagerService not running?");
1550                        }
1551                    }
1552                } break;
1553                case WRITE_SETTINGS: {
1554                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1555                    synchronized (mPackages) {
1556                        removeMessages(WRITE_SETTINGS);
1557                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1558                        mSettings.writeLPr();
1559                        mDirtyUsers.clear();
1560                    }
1561                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1562                } break;
1563                case WRITE_PACKAGE_RESTRICTIONS: {
1564                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1565                    synchronized (mPackages) {
1566                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1567                        for (int userId : mDirtyUsers) {
1568                            mSettings.writePackageRestrictionsLPr(userId);
1569                        }
1570                        mDirtyUsers.clear();
1571                    }
1572                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1573                } break;
1574                case WRITE_PACKAGE_LIST: {
1575                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1576                    synchronized (mPackages) {
1577                        removeMessages(WRITE_PACKAGE_LIST);
1578                        mSettings.writePackageListLPr(msg.arg1);
1579                    }
1580                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1581                } break;
1582                case CHECK_PENDING_VERIFICATION: {
1583                    final int verificationId = msg.arg1;
1584                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1585
1586                    if ((state != null) && !state.timeoutExtended()) {
1587                        final InstallArgs args = state.getInstallArgs();
1588                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1589
1590                        Slog.i(TAG, "Verification timed out for " + originUri);
1591                        mPendingVerification.remove(verificationId);
1592
1593                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1594
1595                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1596                            Slog.i(TAG, "Continuing with installation of " + originUri);
1597                            state.setVerifierResponse(Binder.getCallingUid(),
1598                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1599                            broadcastPackageVerified(verificationId, originUri,
1600                                    PackageManager.VERIFICATION_ALLOW,
1601                                    state.getInstallArgs().getUser());
1602                            try {
1603                                ret = args.copyApk(mContainerService, true);
1604                            } catch (RemoteException e) {
1605                                Slog.e(TAG, "Could not contact the ContainerService");
1606                            }
1607                        } else {
1608                            broadcastPackageVerified(verificationId, originUri,
1609                                    PackageManager.VERIFICATION_REJECT,
1610                                    state.getInstallArgs().getUser());
1611                        }
1612
1613                        Trace.asyncTraceEnd(
1614                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1615
1616                        processPendingInstall(args, ret);
1617                        mHandler.sendEmptyMessage(MCS_UNBIND);
1618                    }
1619                    break;
1620                }
1621                case PACKAGE_VERIFIED: {
1622                    final int verificationId = msg.arg1;
1623
1624                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1625                    if (state == null) {
1626                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1627                        break;
1628                    }
1629
1630                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1631
1632                    state.setVerifierResponse(response.callerUid, response.code);
1633
1634                    if (state.isVerificationComplete()) {
1635                        mPendingVerification.remove(verificationId);
1636
1637                        final InstallArgs args = state.getInstallArgs();
1638                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1639
1640                        int ret;
1641                        if (state.isInstallAllowed()) {
1642                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1643                            broadcastPackageVerified(verificationId, originUri,
1644                                    response.code, state.getInstallArgs().getUser());
1645                            try {
1646                                ret = args.copyApk(mContainerService, true);
1647                            } catch (RemoteException e) {
1648                                Slog.e(TAG, "Could not contact the ContainerService");
1649                            }
1650                        } else {
1651                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1652                        }
1653
1654                        Trace.asyncTraceEnd(
1655                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1656
1657                        processPendingInstall(args, ret);
1658                        mHandler.sendEmptyMessage(MCS_UNBIND);
1659                    }
1660
1661                    break;
1662                }
1663                case START_INTENT_FILTER_VERIFICATIONS: {
1664                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1665                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1666                            params.replacing, params.pkg);
1667                    break;
1668                }
1669                case INTENT_FILTER_VERIFIED: {
1670                    final int verificationId = msg.arg1;
1671
1672                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1673                            verificationId);
1674                    if (state == null) {
1675                        Slog.w(TAG, "Invalid IntentFilter verification token "
1676                                + verificationId + " received");
1677                        break;
1678                    }
1679
1680                    final int userId = state.getUserId();
1681
1682                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1683                            "Processing IntentFilter verification with token:"
1684                            + verificationId + " and userId:" + userId);
1685
1686                    final IntentFilterVerificationResponse response =
1687                            (IntentFilterVerificationResponse) msg.obj;
1688
1689                    state.setVerifierResponse(response.callerUid, response.code);
1690
1691                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1692                            "IntentFilter verification with token:" + verificationId
1693                            + " and userId:" + userId
1694                            + " is settings verifier response with response code:"
1695                            + response.code);
1696
1697                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1698                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1699                                + response.getFailedDomainsString());
1700                    }
1701
1702                    if (state.isVerificationComplete()) {
1703                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1704                    } else {
1705                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1706                                "IntentFilter verification with token:" + verificationId
1707                                + " was not said to be complete");
1708                    }
1709
1710                    break;
1711                }
1712                case EPHEMERAL_RESOLUTION_PHASE_TWO: {
1713                    EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext,
1714                            mEphemeralResolverConnection,
1715                            (EphemeralRequest) msg.obj,
1716                            mEphemeralInstallerActivity,
1717                            mHandler);
1718                }
1719            }
1720        }
1721    }
1722
1723    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1724            boolean killApp, String[] grantedPermissions,
1725            boolean launchedForRestore, String installerPackage,
1726            IPackageInstallObserver2 installObserver) {
1727        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1728            // Send the removed broadcasts
1729            if (res.removedInfo != null) {
1730                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1731            }
1732
1733            // Now that we successfully installed the package, grant runtime
1734            // permissions if requested before broadcasting the install. Also
1735            // for legacy apps in permission review mode we clear the permission
1736            // review flag which is used to emulate runtime permissions for
1737            // legacy apps.
1738            if (grantPermissions) {
1739                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1740            }
1741
1742            final boolean update = res.removedInfo != null
1743                    && res.removedInfo.removedPackage != null;
1744
1745            // If this is the first time we have child packages for a disabled privileged
1746            // app that had no children, we grant requested runtime permissions to the new
1747            // children if the parent on the system image had them already granted.
1748            if (res.pkg.parentPackage != null) {
1749                synchronized (mPackages) {
1750                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1751                }
1752            }
1753
1754            synchronized (mPackages) {
1755                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1756            }
1757
1758            final String packageName = res.pkg.applicationInfo.packageName;
1759
1760            // Determine the set of users who are adding this package for
1761            // the first time vs. those who are seeing an update.
1762            int[] firstUsers = EMPTY_INT_ARRAY;
1763            int[] updateUsers = EMPTY_INT_ARRAY;
1764            if (res.origUsers == null || res.origUsers.length == 0) {
1765                firstUsers = res.newUsers;
1766            } else {
1767                for (int newUser : res.newUsers) {
1768                    boolean isNew = true;
1769                    for (int origUser : res.origUsers) {
1770                        if (origUser == newUser) {
1771                            isNew = false;
1772                            break;
1773                        }
1774                    }
1775                    if (isNew) {
1776                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1777                    } else {
1778                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1779                    }
1780                }
1781            }
1782
1783            // Send installed broadcasts if the install/update is not ephemeral
1784            // and the package is not a static shared lib.
1785            if (!isEphemeral(res.pkg) && res.pkg.staticSharedLibName == null) {
1786                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1787
1788                // Send added for users that see the package for the first time
1789                // sendPackageAddedForNewUsers also deals with system apps
1790                int appId = UserHandle.getAppId(res.uid);
1791                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1792                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1793
1794                // Send added for users that don't see the package for the first time
1795                Bundle extras = new Bundle(1);
1796                extras.putInt(Intent.EXTRA_UID, res.uid);
1797                if (update) {
1798                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1799                }
1800                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1801                        extras, 0 /*flags*/, null /*targetPackage*/,
1802                        null /*finishedReceiver*/, updateUsers);
1803
1804                // Send replaced for users that don't see the package for the first time
1805                if (update) {
1806                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1807                            packageName, extras, 0 /*flags*/,
1808                            null /*targetPackage*/, null /*finishedReceiver*/,
1809                            updateUsers);
1810                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1811                            null /*package*/, null /*extras*/, 0 /*flags*/,
1812                            packageName /*targetPackage*/,
1813                            null /*finishedReceiver*/, updateUsers);
1814                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1815                    // First-install and we did a restore, so we're responsible for the
1816                    // first-launch broadcast.
1817                    if (DEBUG_BACKUP) {
1818                        Slog.i(TAG, "Post-restore of " + packageName
1819                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1820                    }
1821                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1822                }
1823
1824                // Send broadcast package appeared if forward locked/external for all users
1825                // treat asec-hosted packages like removable media on upgrade
1826                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1827                    if (DEBUG_INSTALL) {
1828                        Slog.i(TAG, "upgrading pkg " + res.pkg
1829                                + " is ASEC-hosted -> AVAILABLE");
1830                    }
1831                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1832                    ArrayList<String> pkgList = new ArrayList<>(1);
1833                    pkgList.add(packageName);
1834                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1835                }
1836            }
1837
1838            // Work that needs to happen on first install within each user
1839            if (firstUsers != null && firstUsers.length > 0) {
1840                synchronized (mPackages) {
1841                    for (int userId : firstUsers) {
1842                        // If this app is a browser and it's newly-installed for some
1843                        // users, clear any default-browser state in those users. The
1844                        // app's nature doesn't depend on the user, so we can just check
1845                        // its browser nature in any user and generalize.
1846                        if (packageIsBrowser(packageName, userId)) {
1847                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1848                        }
1849
1850                        // We may also need to apply pending (restored) runtime
1851                        // permission grants within these users.
1852                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1853                    }
1854                }
1855            }
1856
1857            // Log current value of "unknown sources" setting
1858            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1859                    getUnknownSourcesSettings());
1860
1861            // Force a gc to clear up things
1862            Runtime.getRuntime().gc();
1863
1864            // Remove the replaced package's older resources safely now
1865            // We delete after a gc for applications  on sdcard.
1866            if (res.removedInfo != null && res.removedInfo.args != null) {
1867                synchronized (mInstallLock) {
1868                    res.removedInfo.args.doPostDeleteLI(true);
1869                }
1870            }
1871
1872            if (!isEphemeral(res.pkg)) {
1873                // Notify DexManager that the package was installed for new users.
1874                // The updated users should already be indexed and the package code paths
1875                // should not change.
1876                // Don't notify the manager for ephemeral apps as they are not expected to
1877                // survive long enough to benefit of background optimizations.
1878                for (int userId : firstUsers) {
1879                    PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
1880                    mDexManager.notifyPackageInstalled(info, userId);
1881                }
1882            }
1883        }
1884
1885        // If someone is watching installs - notify them
1886        if (installObserver != null) {
1887            try {
1888                Bundle extras = extrasForInstallResult(res);
1889                installObserver.onPackageInstalled(res.name, res.returnCode,
1890                        res.returnMsg, extras);
1891            } catch (RemoteException e) {
1892                Slog.i(TAG, "Observer no longer exists.");
1893            }
1894        }
1895    }
1896
1897    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1898            PackageParser.Package pkg) {
1899        if (pkg.parentPackage == null) {
1900            return;
1901        }
1902        if (pkg.requestedPermissions == null) {
1903            return;
1904        }
1905        final PackageSetting disabledSysParentPs = mSettings
1906                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1907        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1908                || !disabledSysParentPs.isPrivileged()
1909                || (disabledSysParentPs.childPackageNames != null
1910                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1911            return;
1912        }
1913        final int[] allUserIds = sUserManager.getUserIds();
1914        final int permCount = pkg.requestedPermissions.size();
1915        for (int i = 0; i < permCount; i++) {
1916            String permission = pkg.requestedPermissions.get(i);
1917            BasePermission bp = mSettings.mPermissions.get(permission);
1918            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1919                continue;
1920            }
1921            for (int userId : allUserIds) {
1922                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1923                        permission, userId)) {
1924                    grantRuntimePermission(pkg.packageName, permission, userId);
1925                }
1926            }
1927        }
1928    }
1929
1930    private StorageEventListener mStorageListener = new StorageEventListener() {
1931        @Override
1932        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1933            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1934                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1935                    final String volumeUuid = vol.getFsUuid();
1936
1937                    // Clean up any users or apps that were removed or recreated
1938                    // while this volume was missing
1939                    reconcileUsers(volumeUuid);
1940                    reconcileApps(volumeUuid);
1941
1942                    // Clean up any install sessions that expired or were
1943                    // cancelled while this volume was missing
1944                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1945
1946                    loadPrivatePackages(vol);
1947
1948                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1949                    unloadPrivatePackages(vol);
1950                }
1951            }
1952
1953            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1954                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1955                    updateExternalMediaStatus(true, false);
1956                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1957                    updateExternalMediaStatus(false, false);
1958                }
1959            }
1960        }
1961
1962        @Override
1963        public void onVolumeForgotten(String fsUuid) {
1964            if (TextUtils.isEmpty(fsUuid)) {
1965                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1966                return;
1967            }
1968
1969            // Remove any apps installed on the forgotten volume
1970            synchronized (mPackages) {
1971                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1972                for (PackageSetting ps : packages) {
1973                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1974                    deletePackageVersioned(new VersionedPackage(ps.name,
1975                            PackageManager.VERSION_CODE_HIGHEST),
1976                            new LegacyPackageDeleteObserver(null).getBinder(),
1977                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1978                    // Try very hard to release any references to this package
1979                    // so we don't risk the system server being killed due to
1980                    // open FDs
1981                    AttributeCache.instance().removePackage(ps.name);
1982                }
1983
1984                mSettings.onVolumeForgotten(fsUuid);
1985                mSettings.writeLPr();
1986            }
1987        }
1988    };
1989
1990    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1991            String[] grantedPermissions) {
1992        for (int userId : userIds) {
1993            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1994        }
1995    }
1996
1997    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1998            String[] grantedPermissions) {
1999        SettingBase sb = (SettingBase) pkg.mExtras;
2000        if (sb == null) {
2001            return;
2002        }
2003
2004        PermissionsState permissionsState = sb.getPermissionsState();
2005
2006        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2007                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2008
2009        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2010                >= Build.VERSION_CODES.M;
2011
2012        for (String permission : pkg.requestedPermissions) {
2013            final BasePermission bp;
2014            synchronized (mPackages) {
2015                bp = mSettings.mPermissions.get(permission);
2016            }
2017            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2018                    && (grantedPermissions == null
2019                           || ArrayUtils.contains(grantedPermissions, permission))) {
2020                final int flags = permissionsState.getPermissionFlags(permission, userId);
2021                if (supportsRuntimePermissions) {
2022                    // Installer cannot change immutable permissions.
2023                    if ((flags & immutableFlags) == 0) {
2024                        grantRuntimePermission(pkg.packageName, permission, userId);
2025                    }
2026                } else if (mPermissionReviewRequired) {
2027                    // In permission review mode we clear the review flag when we
2028                    // are asked to install the app with all permissions granted.
2029                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2030                        updatePermissionFlags(permission, pkg.packageName,
2031                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2032                    }
2033                }
2034            }
2035        }
2036    }
2037
2038    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2039        Bundle extras = null;
2040        switch (res.returnCode) {
2041            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2042                extras = new Bundle();
2043                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2044                        res.origPermission);
2045                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2046                        res.origPackage);
2047                break;
2048            }
2049            case PackageManager.INSTALL_SUCCEEDED: {
2050                extras = new Bundle();
2051                extras.putBoolean(Intent.EXTRA_REPLACING,
2052                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2053                break;
2054            }
2055        }
2056        return extras;
2057    }
2058
2059    void scheduleWriteSettingsLocked() {
2060        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2061            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2062        }
2063    }
2064
2065    void scheduleWritePackageListLocked(int userId) {
2066        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2067            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2068            msg.arg1 = userId;
2069            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2070        }
2071    }
2072
2073    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2074        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2075        scheduleWritePackageRestrictionsLocked(userId);
2076    }
2077
2078    void scheduleWritePackageRestrictionsLocked(int userId) {
2079        final int[] userIds = (userId == UserHandle.USER_ALL)
2080                ? sUserManager.getUserIds() : new int[]{userId};
2081        for (int nextUserId : userIds) {
2082            if (!sUserManager.exists(nextUserId)) return;
2083            mDirtyUsers.add(nextUserId);
2084            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2085                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2086            }
2087        }
2088    }
2089
2090    public static PackageManagerService main(Context context, Installer installer,
2091            boolean factoryTest, boolean onlyCore) {
2092        // Self-check for initial settings.
2093        PackageManagerServiceCompilerMapping.checkProperties();
2094
2095        PackageManagerService m = new PackageManagerService(context, installer,
2096                factoryTest, onlyCore);
2097        m.enableSystemUserPackages();
2098        ServiceManager.addService("package", m);
2099        return m;
2100    }
2101
2102    private void enableSystemUserPackages() {
2103        if (!UserManager.isSplitSystemUser()) {
2104            return;
2105        }
2106        // For system user, enable apps based on the following conditions:
2107        // - app is whitelisted or belong to one of these groups:
2108        //   -- system app which has no launcher icons
2109        //   -- system app which has INTERACT_ACROSS_USERS permission
2110        //   -- system IME app
2111        // - app is not in the blacklist
2112        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2113        Set<String> enableApps = new ArraySet<>();
2114        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2115                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2116                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2117        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2118        enableApps.addAll(wlApps);
2119        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2120                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2121        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2122        enableApps.removeAll(blApps);
2123        Log.i(TAG, "Applications installed for system user: " + enableApps);
2124        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2125                UserHandle.SYSTEM);
2126        final int allAppsSize = allAps.size();
2127        synchronized (mPackages) {
2128            for (int i = 0; i < allAppsSize; i++) {
2129                String pName = allAps.get(i);
2130                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2131                // Should not happen, but we shouldn't be failing if it does
2132                if (pkgSetting == null) {
2133                    continue;
2134                }
2135                boolean install = enableApps.contains(pName);
2136                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2137                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2138                            + " for system user");
2139                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2140                }
2141            }
2142        }
2143    }
2144
2145    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2146        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2147                Context.DISPLAY_SERVICE);
2148        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2149    }
2150
2151    /**
2152     * Requests that files preopted on a secondary system partition be copied to the data partition
2153     * if possible.  Note that the actual copying of the files is accomplished by init for security
2154     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2155     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2156     */
2157    private static void requestCopyPreoptedFiles() {
2158        final int WAIT_TIME_MS = 100;
2159        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2160        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2161            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2162            // We will wait for up to 100 seconds.
2163            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2164            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2165                try {
2166                    Thread.sleep(WAIT_TIME_MS);
2167                } catch (InterruptedException e) {
2168                    // Do nothing
2169                }
2170                if (SystemClock.uptimeMillis() > timeEnd) {
2171                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2172                    Slog.wtf(TAG, "cppreopt did not finish!");
2173                    break;
2174                }
2175            }
2176        }
2177    }
2178
2179    public PackageManagerService(Context context, Installer installer,
2180            boolean factoryTest, boolean onlyCore) {
2181        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2182        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2183                SystemClock.uptimeMillis());
2184
2185        if (mSdkVersion <= 0) {
2186            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2187        }
2188
2189        mContext = context;
2190
2191        mPermissionReviewRequired = context.getResources().getBoolean(
2192                R.bool.config_permissionReviewRequired);
2193
2194        mFactoryTest = factoryTest;
2195        mOnlyCore = onlyCore;
2196        mMetrics = new DisplayMetrics();
2197        mSettings = new Settings(mPackages);
2198        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2199                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2200        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2201                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2202        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2203                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2204        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2205                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2206        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2207                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2208        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2209                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2210
2211        String separateProcesses = SystemProperties.get("debug.separate_processes");
2212        if (separateProcesses != null && separateProcesses.length() > 0) {
2213            if ("*".equals(separateProcesses)) {
2214                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2215                mSeparateProcesses = null;
2216                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2217            } else {
2218                mDefParseFlags = 0;
2219                mSeparateProcesses = separateProcesses.split(",");
2220                Slog.w(TAG, "Running with debug.separate_processes: "
2221                        + separateProcesses);
2222            }
2223        } else {
2224            mDefParseFlags = 0;
2225            mSeparateProcesses = null;
2226        }
2227
2228        mInstaller = installer;
2229        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2230                "*dexopt*");
2231        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2232        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2233
2234        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2235                FgThread.get().getLooper());
2236
2237        getDefaultDisplayMetrics(context, mMetrics);
2238
2239        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2240        SystemConfig systemConfig = SystemConfig.getInstance();
2241        mGlobalGids = systemConfig.getGlobalGids();
2242        mSystemPermissions = systemConfig.getSystemPermissions();
2243        mAvailableFeatures = systemConfig.getAvailableFeatures();
2244        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2245
2246        mProtectedPackages = new ProtectedPackages(mContext);
2247
2248        synchronized (mInstallLock) {
2249        // writer
2250        synchronized (mPackages) {
2251            mHandlerThread = new ServiceThread(TAG,
2252                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2253            mHandlerThread.start();
2254            mHandler = new PackageHandler(mHandlerThread.getLooper());
2255            mProcessLoggingHandler = new ProcessLoggingHandler();
2256            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2257
2258            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2259            mInstantAppRegistry = new InstantAppRegistry(this);
2260
2261            File dataDir = Environment.getDataDirectory();
2262            mAppInstallDir = new File(dataDir, "app");
2263            mAppLib32InstallDir = new File(dataDir, "app-lib");
2264            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2265            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2266            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2267            mUserDataPreparer = new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore);
2268            sUserManager = new UserManagerService(context, this, mUserDataPreparer, mPackages);
2269
2270            // Propagate permission configuration in to package manager.
2271            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2272                    = systemConfig.getPermissions();
2273            for (int i=0; i<permConfig.size(); i++) {
2274                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2275                BasePermission bp = mSettings.mPermissions.get(perm.name);
2276                if (bp == null) {
2277                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2278                    mSettings.mPermissions.put(perm.name, bp);
2279                }
2280                if (perm.gids != null) {
2281                    bp.setGids(perm.gids, perm.perUser);
2282                }
2283            }
2284
2285            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2286            final int builtInLibCount = libConfig.size();
2287            for (int i = 0; i < builtInLibCount; i++) {
2288                String name = libConfig.keyAt(i);
2289                String path = libConfig.valueAt(i);
2290                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2291                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2292            }
2293
2294            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2295
2296            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2297            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2298            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2299
2300            // Clean up orphaned packages for which the code path doesn't exist
2301            // and they are an update to a system app - caused by bug/32321269
2302            final int packageSettingCount = mSettings.mPackages.size();
2303            for (int i = packageSettingCount - 1; i >= 0; i--) {
2304                PackageSetting ps = mSettings.mPackages.valueAt(i);
2305                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2306                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2307                    mSettings.mPackages.removeAt(i);
2308                    mSettings.enableSystemPackageLPw(ps.name);
2309                }
2310            }
2311
2312            if (mFirstBoot) {
2313                requestCopyPreoptedFiles();
2314            }
2315
2316            String customResolverActivity = Resources.getSystem().getString(
2317                    R.string.config_customResolverActivity);
2318            if (TextUtils.isEmpty(customResolverActivity)) {
2319                customResolverActivity = null;
2320            } else {
2321                mCustomResolverComponentName = ComponentName.unflattenFromString(
2322                        customResolverActivity);
2323            }
2324
2325            long startTime = SystemClock.uptimeMillis();
2326
2327            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2328                    startTime);
2329
2330            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2331            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2332
2333            if (bootClassPath == null) {
2334                Slog.w(TAG, "No BOOTCLASSPATH found!");
2335            }
2336
2337            if (systemServerClassPath == null) {
2338                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2339            }
2340
2341            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2342            final String[] dexCodeInstructionSets =
2343                    getDexCodeInstructionSets(
2344                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2345
2346            /**
2347             * Ensure all external libraries have had dexopt run on them.
2348             */
2349            if (mSharedLibraries.size() > 0) {
2350                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2351                // NOTE: For now, we're compiling these system "shared libraries"
2352                // (and framework jars) into all available architectures. It's possible
2353                // to compile them only when we come across an app that uses them (there's
2354                // already logic for that in scanPackageLI) but that adds some complexity.
2355                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2356                    final int libCount = mSharedLibraries.size();
2357                    for (int i = 0; i < libCount; i++) {
2358                        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
2359                        final int versionCount = versionedLib.size();
2360                        for (int j = 0; j < versionCount; j++) {
2361                            SharedLibraryEntry libEntry = versionedLib.valueAt(j);
2362                            final String libPath = libEntry.path != null
2363                                    ? libEntry.path : libEntry.apk;
2364                            if (libPath == null) {
2365                                continue;
2366                            }
2367                            try {
2368                                // Shared libraries do not have profiles so we perform a full
2369                                // AOT compilation (if needed).
2370                                int dexoptNeeded = DexFile.getDexOptNeeded(
2371                                        libPath, dexCodeInstructionSet,
2372                                        getCompilerFilterForReason(REASON_SHARED_APK),
2373                                        false /* newProfile */);
2374                                if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2375                                    mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*",
2376                                            dexCodeInstructionSet, dexoptNeeded, null,
2377                                            DEXOPT_PUBLIC,
2378                                            getCompilerFilterForReason(REASON_SHARED_APK),
2379                                            StorageManager.UUID_PRIVATE_INTERNAL,
2380                                            SKIP_SHARED_LIBRARY_CHECK);
2381                                }
2382                            } catch (FileNotFoundException e) {
2383                                Slog.w(TAG, "Library not found: " + libPath);
2384                            } catch (IOException | InstallerException e) {
2385                                Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? "
2386                                        + e.getMessage());
2387                            }
2388                        }
2389                    }
2390                }
2391                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2392            }
2393
2394            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2395
2396            final VersionInfo ver = mSettings.getInternalVersion();
2397            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2398
2399            // when upgrading from pre-M, promote system app permissions from install to runtime
2400            mPromoteSystemApps =
2401                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2402
2403            // When upgrading from pre-N, we need to handle package extraction like first boot,
2404            // as there is no profiling data available.
2405            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2406
2407            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2408
2409            // save off the names of pre-existing system packages prior to scanning; we don't
2410            // want to automatically grant runtime permissions for new system apps
2411            if (mPromoteSystemApps) {
2412                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2413                while (pkgSettingIter.hasNext()) {
2414                    PackageSetting ps = pkgSettingIter.next();
2415                    if (isSystemApp(ps)) {
2416                        mExistingSystemPackages.add(ps.name);
2417                    }
2418                }
2419            }
2420
2421            mCacheDir = preparePackageParserCache(mIsUpgrade);
2422
2423            // Set flag to monitor and not change apk file paths when
2424            // scanning install directories.
2425            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2426
2427            if (mIsUpgrade || mFirstBoot) {
2428                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2429            }
2430
2431            // Collect vendor overlay packages. (Do this before scanning any apps.)
2432            // For security and version matching reason, only consider
2433            // overlay packages if they reside in the right directory.
2434            String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY);
2435            if (overlayThemeDir.isEmpty()) {
2436                overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY);
2437            }
2438            if (!overlayThemeDir.isEmpty()) {
2439                scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags
2440                        | PackageParser.PARSE_IS_SYSTEM
2441                        | PackageParser.PARSE_IS_SYSTEM_DIR
2442                        | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2443            }
2444            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2445                    | PackageParser.PARSE_IS_SYSTEM
2446                    | PackageParser.PARSE_IS_SYSTEM_DIR
2447                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2448
2449            // Find base frameworks (resource packages without code).
2450            scanDirTracedLI(frameworkDir, mDefParseFlags
2451                    | PackageParser.PARSE_IS_SYSTEM
2452                    | PackageParser.PARSE_IS_SYSTEM_DIR
2453                    | PackageParser.PARSE_IS_PRIVILEGED,
2454                    scanFlags | SCAN_NO_DEX, 0);
2455
2456            // Collected privileged system packages.
2457            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2458            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2459                    | PackageParser.PARSE_IS_SYSTEM
2460                    | PackageParser.PARSE_IS_SYSTEM_DIR
2461                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2462
2463            // Collect ordinary system packages.
2464            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2465            scanDirTracedLI(systemAppDir, mDefParseFlags
2466                    | PackageParser.PARSE_IS_SYSTEM
2467                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2468
2469            // Collect all vendor packages.
2470            File vendorAppDir = new File("/vendor/app");
2471            try {
2472                vendorAppDir = vendorAppDir.getCanonicalFile();
2473            } catch (IOException e) {
2474                // failed to look up canonical path, continue with original one
2475            }
2476            scanDirTracedLI(vendorAppDir, mDefParseFlags
2477                    | PackageParser.PARSE_IS_SYSTEM
2478                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2479
2480            // Collect all OEM packages.
2481            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2482            scanDirTracedLI(oemAppDir, mDefParseFlags
2483                    | PackageParser.PARSE_IS_SYSTEM
2484                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2485
2486            // Prune any system packages that no longer exist.
2487            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2488            if (!mOnlyCore) {
2489                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2490                while (psit.hasNext()) {
2491                    PackageSetting ps = psit.next();
2492
2493                    /*
2494                     * If this is not a system app, it can't be a
2495                     * disable system app.
2496                     */
2497                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2498                        continue;
2499                    }
2500
2501                    /*
2502                     * If the package is scanned, it's not erased.
2503                     */
2504                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2505                    if (scannedPkg != null) {
2506                        /*
2507                         * If the system app is both scanned and in the
2508                         * disabled packages list, then it must have been
2509                         * added via OTA. Remove it from the currently
2510                         * scanned package so the previously user-installed
2511                         * application can be scanned.
2512                         */
2513                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2514                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2515                                    + ps.name + "; removing system app.  Last known codePath="
2516                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2517                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2518                                    + scannedPkg.mVersionCode);
2519                            removePackageLI(scannedPkg, true);
2520                            mExpectingBetter.put(ps.name, ps.codePath);
2521                        }
2522
2523                        continue;
2524                    }
2525
2526                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2527                        psit.remove();
2528                        logCriticalInfo(Log.WARN, "System package " + ps.name
2529                                + " no longer exists; it's data will be wiped");
2530                        // Actual deletion of code and data will be handled by later
2531                        // reconciliation step
2532                    } else {
2533                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2534                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2535                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2536                        }
2537                    }
2538                }
2539            }
2540
2541            //look for any incomplete package installations
2542            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2543            for (int i = 0; i < deletePkgsList.size(); i++) {
2544                // Actual deletion of code and data will be handled by later
2545                // reconciliation step
2546                final String packageName = deletePkgsList.get(i).name;
2547                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2548                synchronized (mPackages) {
2549                    mSettings.removePackageLPw(packageName);
2550                }
2551            }
2552
2553            //delete tmp files
2554            deleteTempPackageFiles();
2555
2556            // Remove any shared userIDs that have no associated packages
2557            mSettings.pruneSharedUsersLPw();
2558
2559            if (!mOnlyCore) {
2560                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2561                        SystemClock.uptimeMillis());
2562                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2563
2564                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2565                        | PackageParser.PARSE_FORWARD_LOCK,
2566                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2567
2568                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2569                        | PackageParser.PARSE_IS_EPHEMERAL,
2570                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2571
2572                /**
2573                 * Remove disable package settings for any updated system
2574                 * apps that were removed via an OTA. If they're not a
2575                 * previously-updated app, remove them completely.
2576                 * Otherwise, just revoke their system-level permissions.
2577                 */
2578                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2579                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2580                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2581
2582                    String msg;
2583                    if (deletedPkg == null) {
2584                        msg = "Updated system package " + deletedAppName
2585                                + " no longer exists; it's data will be wiped";
2586                        // Actual deletion of code and data will be handled by later
2587                        // reconciliation step
2588                    } else {
2589                        msg = "Updated system app + " + deletedAppName
2590                                + " no longer present; removing system privileges for "
2591                                + deletedAppName;
2592
2593                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2594
2595                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2596                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2597                    }
2598                    logCriticalInfo(Log.WARN, msg);
2599                }
2600
2601                /**
2602                 * Make sure all system apps that we expected to appear on
2603                 * the userdata partition actually showed up. If they never
2604                 * appeared, crawl back and revive the system version.
2605                 */
2606                for (int i = 0; i < mExpectingBetter.size(); i++) {
2607                    final String packageName = mExpectingBetter.keyAt(i);
2608                    if (!mPackages.containsKey(packageName)) {
2609                        final File scanFile = mExpectingBetter.valueAt(i);
2610
2611                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2612                                + " but never showed up; reverting to system");
2613
2614                        int reparseFlags = mDefParseFlags;
2615                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2616                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2617                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2618                                    | PackageParser.PARSE_IS_PRIVILEGED;
2619                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2620                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2621                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2622                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2623                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2624                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2625                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2626                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2627                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2628                        } else {
2629                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2630                            continue;
2631                        }
2632
2633                        mSettings.enableSystemPackageLPw(packageName);
2634
2635                        try {
2636                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2637                        } catch (PackageManagerException e) {
2638                            Slog.e(TAG, "Failed to parse original system package: "
2639                                    + e.getMessage());
2640                        }
2641                    }
2642                }
2643            }
2644            mExpectingBetter.clear();
2645
2646            // Resolve the storage manager.
2647            mStorageManagerPackage = getStorageManagerPackageName();
2648
2649            // Resolve protected action filters. Only the setup wizard is allowed to
2650            // have a high priority filter for these actions.
2651            mSetupWizardPackage = getSetupWizardPackageName();
2652            if (mProtectedFilters.size() > 0) {
2653                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2654                    Slog.i(TAG, "No setup wizard;"
2655                        + " All protected intents capped to priority 0");
2656                }
2657                for (ActivityIntentInfo filter : mProtectedFilters) {
2658                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2659                        if (DEBUG_FILTERS) {
2660                            Slog.i(TAG, "Found setup wizard;"
2661                                + " allow priority " + filter.getPriority() + ";"
2662                                + " package: " + filter.activity.info.packageName
2663                                + " activity: " + filter.activity.className
2664                                + " priority: " + filter.getPriority());
2665                        }
2666                        // skip setup wizard; allow it to keep the high priority filter
2667                        continue;
2668                    }
2669                    Slog.w(TAG, "Protected action; cap priority to 0;"
2670                            + " package: " + filter.activity.info.packageName
2671                            + " activity: " + filter.activity.className
2672                            + " origPrio: " + filter.getPriority());
2673                    filter.setPriority(0);
2674                }
2675            }
2676            mDeferProtectedFilters = false;
2677            mProtectedFilters.clear();
2678
2679            // Now that we know all of the shared libraries, update all clients to have
2680            // the correct library paths.
2681            updateAllSharedLibrariesLPw(null);
2682
2683            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2684                // NOTE: We ignore potential failures here during a system scan (like
2685                // the rest of the commands above) because there's precious little we
2686                // can do about it. A settings error is reported, though.
2687                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2688            }
2689
2690            // Now that we know all the packages we are keeping,
2691            // read and update their last usage times.
2692            mPackageUsage.read(mPackages);
2693            mCompilerStats.read();
2694
2695            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2696                    SystemClock.uptimeMillis());
2697            Slog.i(TAG, "Time to scan packages: "
2698                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2699                    + " seconds");
2700
2701            // If the platform SDK has changed since the last time we booted,
2702            // we need to re-grant app permission to catch any new ones that
2703            // appear.  This is really a hack, and means that apps can in some
2704            // cases get permissions that the user didn't initially explicitly
2705            // allow...  it would be nice to have some better way to handle
2706            // this situation.
2707            int updateFlags = UPDATE_PERMISSIONS_ALL;
2708            if (ver.sdkVersion != mSdkVersion) {
2709                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2710                        + mSdkVersion + "; regranting permissions for internal storage");
2711                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2712            }
2713            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2714            ver.sdkVersion = mSdkVersion;
2715
2716            // If this is the first boot or an update from pre-M, and it is a normal
2717            // boot, then we need to initialize the default preferred apps across
2718            // all defined users.
2719            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2720                for (UserInfo user : sUserManager.getUsers(true)) {
2721                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2722                    applyFactoryDefaultBrowserLPw(user.id);
2723                    primeDomainVerificationsLPw(user.id);
2724                }
2725            }
2726
2727            // Prepare storage for system user really early during boot,
2728            // since core system apps like SettingsProvider and SystemUI
2729            // can't wait for user to start
2730            final int storageFlags;
2731            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2732                storageFlags = StorageManager.FLAG_STORAGE_DE;
2733            } else {
2734                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2735            }
2736            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2737                    storageFlags, true /* migrateAppData */);
2738
2739            // If this is first boot after an OTA, and a normal boot, then
2740            // we need to clear code cache directories.
2741            // Note that we do *not* clear the application profiles. These remain valid
2742            // across OTAs and are used to drive profile verification (post OTA) and
2743            // profile compilation (without waiting to collect a fresh set of profiles).
2744            if (mIsUpgrade && !onlyCore) {
2745                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2746                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2747                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2748                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2749                        // No apps are running this early, so no need to freeze
2750                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2751                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2752                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2753                    }
2754                }
2755                ver.fingerprint = Build.FINGERPRINT;
2756            }
2757
2758            checkDefaultBrowser();
2759
2760            // clear only after permissions and other defaults have been updated
2761            mExistingSystemPackages.clear();
2762            mPromoteSystemApps = false;
2763
2764            // All the changes are done during package scanning.
2765            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2766
2767            // can downgrade to reader
2768            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2769            mSettings.writeLPr();
2770            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2771
2772            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2773            // early on (before the package manager declares itself as early) because other
2774            // components in the system server might ask for package contexts for these apps.
2775            //
2776            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2777            // (i.e, that the data partition is unavailable).
2778            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2779                long start = System.nanoTime();
2780                List<PackageParser.Package> coreApps = new ArrayList<>();
2781                for (PackageParser.Package pkg : mPackages.values()) {
2782                    if (pkg.coreApp) {
2783                        coreApps.add(pkg);
2784                    }
2785                }
2786
2787                int[] stats = performDexOptUpgrade(coreApps, false,
2788                        getCompilerFilterForReason(REASON_CORE_APP));
2789
2790                final int elapsedTimeSeconds =
2791                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2792                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2793
2794                if (DEBUG_DEXOPT) {
2795                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2796                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2797                }
2798
2799
2800                // TODO: Should we log these stats to tron too ?
2801                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2802                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2803                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2804                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2805            }
2806
2807            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2808                    SystemClock.uptimeMillis());
2809
2810            if (!mOnlyCore) {
2811                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2812                mRequiredInstallerPackage = getRequiredInstallerLPr();
2813                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2814                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2815                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2816                        mIntentFilterVerifierComponent);
2817                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2818                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2819                        SharedLibraryInfo.VERSION_UNDEFINED);
2820                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2821                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2822                        SharedLibraryInfo.VERSION_UNDEFINED);
2823            } else {
2824                mRequiredVerifierPackage = null;
2825                mRequiredInstallerPackage = null;
2826                mRequiredUninstallerPackage = null;
2827                mIntentFilterVerifierComponent = null;
2828                mIntentFilterVerifier = null;
2829                mServicesSystemSharedLibraryPackageName = null;
2830                mSharedSystemSharedLibraryPackageName = null;
2831            }
2832
2833            mInstallerService = new PackageInstallerService(context, this);
2834
2835            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2836            if (ephemeralResolverComponent != null) {
2837                if (DEBUG_EPHEMERAL) {
2838                    Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent);
2839                }
2840                mEphemeralResolverConnection =
2841                        new EphemeralResolverConnection(mContext, ephemeralResolverComponent);
2842            } else {
2843                mEphemeralResolverConnection = null;
2844            }
2845            mEphemeralInstallerComponent = getEphemeralInstallerLPr();
2846            if (mEphemeralInstallerComponent != null) {
2847                if (DEBUG_EPHEMERAL) {
2848                    Slog.i(TAG, "Ephemeral installer: " + mEphemeralInstallerComponent);
2849                }
2850                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2851            }
2852
2853            // Read and update the usage of dex files.
2854            // Do this at the end of PM init so that all the packages have their
2855            // data directory reconciled.
2856            // At this point we know the code paths of the packages, so we can validate
2857            // the disk file and build the internal cache.
2858            // The usage file is expected to be small so loading and verifying it
2859            // should take a fairly small time compare to the other activities (e.g. package
2860            // scanning).
2861            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2862            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
2863            for (int userId : currentUserIds) {
2864                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
2865            }
2866            mDexManager.load(userPackages);
2867        } // synchronized (mPackages)
2868        } // synchronized (mInstallLock)
2869
2870        // Now after opening every single application zip, make sure they
2871        // are all flushed.  Not really needed, but keeps things nice and
2872        // tidy.
2873        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2874        Runtime.getRuntime().gc();
2875        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2876
2877        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2878        FallbackCategoryProvider.loadFallbacks();
2879        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2880
2881        // The initial scanning above does many calls into installd while
2882        // holding the mPackages lock, but we're mostly interested in yelling
2883        // once we have a booted system.
2884        mInstaller.setWarnIfHeld(mPackages);
2885
2886        // Expose private service for system components to use.
2887        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2888        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2889    }
2890
2891    private static File preparePackageParserCache(boolean isUpgrade) {
2892        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
2893            return null;
2894        }
2895
2896        // Disable package parsing on eng builds to allow for faster incremental development.
2897        if ("eng".equals(Build.TYPE)) {
2898            return null;
2899        }
2900
2901        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
2902            Slog.i(TAG, "Disabling package parser cache due to system property.");
2903            return null;
2904        }
2905
2906        // The base directory for the package parser cache lives under /data/system/.
2907        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
2908                "package_cache");
2909        if (cacheBaseDir == null) {
2910            return null;
2911        }
2912
2913        // If this is a system upgrade scenario, delete the contents of the package cache dir.
2914        // This also serves to "GC" unused entries when the package cache version changes (which
2915        // can only happen during upgrades).
2916        if (isUpgrade) {
2917            FileUtils.deleteContents(cacheBaseDir);
2918        }
2919
2920
2921        // Return the versioned package cache directory. This is something like
2922        // "/data/system/package_cache/1"
2923        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2924
2925        // The following is a workaround to aid development on non-numbered userdebug
2926        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
2927        // the system partition is newer.
2928        //
2929        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
2930        // that starts with "eng." to signify that this is an engineering build and not
2931        // destined for release.
2932        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
2933            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
2934
2935            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
2936            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
2937            // in general and should not be used for production changes. In this specific case,
2938            // we know that they will work.
2939            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2940            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
2941                FileUtils.deleteContents(cacheBaseDir);
2942                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
2943            }
2944        }
2945
2946        return cacheDir;
2947    }
2948
2949    @Override
2950    public boolean isFirstBoot() {
2951        return mFirstBoot;
2952    }
2953
2954    @Override
2955    public boolean isOnlyCoreApps() {
2956        return mOnlyCore;
2957    }
2958
2959    @Override
2960    public boolean isUpgrade() {
2961        return mIsUpgrade;
2962    }
2963
2964    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2965        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2966
2967        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2968                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2969                UserHandle.USER_SYSTEM);
2970        if (matches.size() == 1) {
2971            return matches.get(0).getComponentInfo().packageName;
2972        } else if (matches.size() == 0) {
2973            Log.e(TAG, "There should probably be a verifier, but, none were found");
2974            return null;
2975        }
2976        throw new RuntimeException("There must be exactly one verifier; found " + matches);
2977    }
2978
2979    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
2980        synchronized (mPackages) {
2981            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
2982            if (libraryEntry == null) {
2983                throw new IllegalStateException("Missing required shared library:" + name);
2984            }
2985            return libraryEntry.apk;
2986        }
2987    }
2988
2989    private @NonNull String getRequiredInstallerLPr() {
2990        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2991        intent.addCategory(Intent.CATEGORY_DEFAULT);
2992        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2993
2994        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2995                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2996                UserHandle.USER_SYSTEM);
2997        if (matches.size() == 1) {
2998            ResolveInfo resolveInfo = matches.get(0);
2999            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3000                throw new RuntimeException("The installer must be a privileged app");
3001            }
3002            return matches.get(0).getComponentInfo().packageName;
3003        } else {
3004            throw new RuntimeException("There must be exactly one installer; found " + matches);
3005        }
3006    }
3007
3008    private @NonNull String getRequiredUninstallerLPr() {
3009        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3010        intent.addCategory(Intent.CATEGORY_DEFAULT);
3011        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3012
3013        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3014                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3015                UserHandle.USER_SYSTEM);
3016        if (resolveInfo == null ||
3017                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3018            throw new RuntimeException("There must be exactly one uninstaller; found "
3019                    + resolveInfo);
3020        }
3021        return resolveInfo.getComponentInfo().packageName;
3022    }
3023
3024    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3025        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3026
3027        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3028                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3029                UserHandle.USER_SYSTEM);
3030        ResolveInfo best = null;
3031        final int N = matches.size();
3032        for (int i = 0; i < N; i++) {
3033            final ResolveInfo cur = matches.get(i);
3034            final String packageName = cur.getComponentInfo().packageName;
3035            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3036                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3037                continue;
3038            }
3039
3040            if (best == null || cur.priority > best.priority) {
3041                best = cur;
3042            }
3043        }
3044
3045        if (best != null) {
3046            return best.getComponentInfo().getComponentName();
3047        } else {
3048            throw new RuntimeException("There must be at least one intent filter verifier");
3049        }
3050    }
3051
3052    private @Nullable ComponentName getEphemeralResolverLPr() {
3053        final String[] packageArray =
3054                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3055        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3056            if (DEBUG_EPHEMERAL) {
3057                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3058            }
3059            return null;
3060        }
3061
3062        final int resolveFlags =
3063                MATCH_DIRECT_BOOT_AWARE
3064                | MATCH_DIRECT_BOOT_UNAWARE
3065                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3066        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
3067        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3068                resolveFlags, UserHandle.USER_SYSTEM);
3069
3070        final int N = resolvers.size();
3071        if (N == 0) {
3072            if (DEBUG_EPHEMERAL) {
3073                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3074            }
3075            return null;
3076        }
3077
3078        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3079        for (int i = 0; i < N; i++) {
3080            final ResolveInfo info = resolvers.get(i);
3081
3082            if (info.serviceInfo == null) {
3083                continue;
3084            }
3085
3086            final String packageName = info.serviceInfo.packageName;
3087            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3088                if (DEBUG_EPHEMERAL) {
3089                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3090                            + " pkg: " + packageName + ", info:" + info);
3091                }
3092                continue;
3093            }
3094
3095            if (DEBUG_EPHEMERAL) {
3096                Slog.v(TAG, "Ephemeral resolver found;"
3097                        + " pkg: " + packageName + ", info:" + info);
3098            }
3099            return new ComponentName(packageName, info.serviceInfo.name);
3100        }
3101        if (DEBUG_EPHEMERAL) {
3102            Slog.v(TAG, "Ephemeral resolver NOT found");
3103        }
3104        return null;
3105    }
3106
3107    private @Nullable ComponentName getEphemeralInstallerLPr() {
3108        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3109        intent.addCategory(Intent.CATEGORY_DEFAULT);
3110        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3111
3112        final int resolveFlags =
3113                MATCH_DIRECT_BOOT_AWARE
3114                | MATCH_DIRECT_BOOT_UNAWARE
3115                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3116        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3117                resolveFlags, UserHandle.USER_SYSTEM);
3118        Iterator<ResolveInfo> iter = matches.iterator();
3119        while (iter.hasNext()) {
3120            final ResolveInfo rInfo = iter.next();
3121            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3122            if (ps != null) {
3123                final PermissionsState permissionsState = ps.getPermissionsState();
3124                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3125                    continue;
3126                }
3127            }
3128            iter.remove();
3129        }
3130        if (matches.size() == 0) {
3131            return null;
3132        } else if (matches.size() == 1) {
3133            return matches.get(0).getComponentInfo().getComponentName();
3134        } else {
3135            throw new RuntimeException(
3136                    "There must be at most one ephemeral installer; found " + matches);
3137        }
3138    }
3139
3140    private void primeDomainVerificationsLPw(int userId) {
3141        if (DEBUG_DOMAIN_VERIFICATION) {
3142            Slog.d(TAG, "Priming domain verifications in user " + userId);
3143        }
3144
3145        SystemConfig systemConfig = SystemConfig.getInstance();
3146        ArraySet<String> packages = systemConfig.getLinkedApps();
3147
3148        for (String packageName : packages) {
3149            PackageParser.Package pkg = mPackages.get(packageName);
3150            if (pkg != null) {
3151                if (!pkg.isSystemApp()) {
3152                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3153                    continue;
3154                }
3155
3156                ArraySet<String> domains = null;
3157                for (PackageParser.Activity a : pkg.activities) {
3158                    for (ActivityIntentInfo filter : a.intents) {
3159                        if (hasValidDomains(filter)) {
3160                            if (domains == null) {
3161                                domains = new ArraySet<String>();
3162                            }
3163                            domains.addAll(filter.getHostsList());
3164                        }
3165                    }
3166                }
3167
3168                if (domains != null && domains.size() > 0) {
3169                    if (DEBUG_DOMAIN_VERIFICATION) {
3170                        Slog.v(TAG, "      + " + packageName);
3171                    }
3172                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3173                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3174                    // and then 'always' in the per-user state actually used for intent resolution.
3175                    final IntentFilterVerificationInfo ivi;
3176                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3177                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3178                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3179                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3180                } else {
3181                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3182                            + "' does not handle web links");
3183                }
3184            } else {
3185                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3186            }
3187        }
3188
3189        scheduleWritePackageRestrictionsLocked(userId);
3190        scheduleWriteSettingsLocked();
3191    }
3192
3193    private void applyFactoryDefaultBrowserLPw(int userId) {
3194        // The default browser app's package name is stored in a string resource,
3195        // with a product-specific overlay used for vendor customization.
3196        String browserPkg = mContext.getResources().getString(
3197                com.android.internal.R.string.default_browser);
3198        if (!TextUtils.isEmpty(browserPkg)) {
3199            // non-empty string => required to be a known package
3200            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3201            if (ps == null) {
3202                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3203                browserPkg = null;
3204            } else {
3205                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3206            }
3207        }
3208
3209        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3210        // default.  If there's more than one, just leave everything alone.
3211        if (browserPkg == null) {
3212            calculateDefaultBrowserLPw(userId);
3213        }
3214    }
3215
3216    private void calculateDefaultBrowserLPw(int userId) {
3217        List<String> allBrowsers = resolveAllBrowserApps(userId);
3218        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3219        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3220    }
3221
3222    private List<String> resolveAllBrowserApps(int userId) {
3223        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3224        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3225                PackageManager.MATCH_ALL, userId);
3226
3227        final int count = list.size();
3228        List<String> result = new ArrayList<String>(count);
3229        for (int i=0; i<count; i++) {
3230            ResolveInfo info = list.get(i);
3231            if (info.activityInfo == null
3232                    || !info.handleAllWebDataURI
3233                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3234                    || result.contains(info.activityInfo.packageName)) {
3235                continue;
3236            }
3237            result.add(info.activityInfo.packageName);
3238        }
3239
3240        return result;
3241    }
3242
3243    private boolean packageIsBrowser(String packageName, int userId) {
3244        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3245                PackageManager.MATCH_ALL, userId);
3246        final int N = list.size();
3247        for (int i = 0; i < N; i++) {
3248            ResolveInfo info = list.get(i);
3249            if (packageName.equals(info.activityInfo.packageName)) {
3250                return true;
3251            }
3252        }
3253        return false;
3254    }
3255
3256    private void checkDefaultBrowser() {
3257        final int myUserId = UserHandle.myUserId();
3258        final String packageName = getDefaultBrowserPackageName(myUserId);
3259        if (packageName != null) {
3260            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3261            if (info == null) {
3262                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3263                synchronized (mPackages) {
3264                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3265                }
3266            }
3267        }
3268    }
3269
3270    @Override
3271    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3272            throws RemoteException {
3273        try {
3274            return super.onTransact(code, data, reply, flags);
3275        } catch (RuntimeException e) {
3276            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3277                Slog.wtf(TAG, "Package Manager Crash", e);
3278            }
3279            throw e;
3280        }
3281    }
3282
3283    static int[] appendInts(int[] cur, int[] add) {
3284        if (add == null) return cur;
3285        if (cur == null) return add;
3286        final int N = add.length;
3287        for (int i=0; i<N; i++) {
3288            cur = appendInt(cur, add[i]);
3289        }
3290        return cur;
3291    }
3292
3293    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3294        if (!sUserManager.exists(userId)) return null;
3295        if (ps == null) {
3296            return null;
3297        }
3298        final PackageParser.Package p = ps.pkg;
3299        if (p == null) {
3300            return null;
3301        }
3302        // Filter out ephemeral app metadata:
3303        //   * The system/shell/root can see metadata for any app
3304        //   * An installed app can see metadata for 1) other installed apps
3305        //     and 2) ephemeral apps that have explicitly interacted with it
3306        //   * Ephemeral apps can only see their own metadata
3307        //   * Holding a signature permission allows seeing instant apps
3308        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
3309        if (callingAppId != Process.SYSTEM_UID
3310                && callingAppId != Process.SHELL_UID
3311                && callingAppId != Process.ROOT_UID
3312                && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS,
3313                        Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) {
3314            final String ephemeralPackageName = getEphemeralPackageName(Binder.getCallingUid());
3315            if (ephemeralPackageName != null) {
3316                // ephemeral apps can only get information on themselves
3317                if (!ephemeralPackageName.equals(p.packageName)) {
3318                    return null;
3319                }
3320            } else {
3321                if (p.applicationInfo.isInstantApp()) {
3322                    // only get access to the ephemeral app if we've been granted access
3323                    if (!mInstantAppRegistry.isInstantAccessGranted(
3324                            userId, callingAppId, ps.appId)) {
3325                        return null;
3326                    }
3327                }
3328            }
3329        }
3330
3331        final PermissionsState permissionsState = ps.getPermissionsState();
3332
3333        // Compute GIDs only if requested
3334        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3335                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3336        // Compute granted permissions only if package has requested permissions
3337        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3338                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3339        final PackageUserState state = ps.readUserState(userId);
3340
3341        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3342                && ps.isSystem()) {
3343            flags |= MATCH_ANY_USER;
3344        }
3345
3346        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3347                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3348
3349        if (packageInfo == null) {
3350            return null;
3351        }
3352
3353        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3354                resolveExternalPackageNameLPr(p);
3355
3356        return packageInfo;
3357    }
3358
3359    @Override
3360    public void checkPackageStartable(String packageName, int userId) {
3361        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3362
3363        synchronized (mPackages) {
3364            final PackageSetting ps = mSettings.mPackages.get(packageName);
3365            if (ps == null) {
3366                throw new SecurityException("Package " + packageName + " was not found!");
3367            }
3368
3369            if (!ps.getInstalled(userId)) {
3370                throw new SecurityException(
3371                        "Package " + packageName + " was not installed for user " + userId + "!");
3372            }
3373
3374            if (mSafeMode && !ps.isSystem()) {
3375                throw new SecurityException("Package " + packageName + " not a system app!");
3376            }
3377
3378            if (mFrozenPackages.contains(packageName)) {
3379                throw new SecurityException("Package " + packageName + " is currently frozen!");
3380            }
3381
3382            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3383                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3384                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3385            }
3386        }
3387    }
3388
3389    @Override
3390    public boolean isPackageAvailable(String packageName, int userId) {
3391        if (!sUserManager.exists(userId)) return false;
3392        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3393                false /* requireFullPermission */, false /* checkShell */, "is package available");
3394        synchronized (mPackages) {
3395            PackageParser.Package p = mPackages.get(packageName);
3396            if (p != null) {
3397                final PackageSetting ps = (PackageSetting) p.mExtras;
3398                if (ps != null) {
3399                    final PackageUserState state = ps.readUserState(userId);
3400                    if (state != null) {
3401                        return PackageParser.isAvailable(state);
3402                    }
3403                }
3404            }
3405        }
3406        return false;
3407    }
3408
3409    @Override
3410    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3411        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3412                flags, userId);
3413    }
3414
3415    @Override
3416    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3417            int flags, int userId) {
3418        return getPackageInfoInternal(versionedPackage.getPackageName(),
3419                // TODO: We will change version code to long, so in the new API it is long
3420                (int) versionedPackage.getVersionCode(), flags, userId);
3421    }
3422
3423    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3424            int flags, int userId) {
3425        if (!sUserManager.exists(userId)) return null;
3426        flags = updateFlagsForPackage(flags, userId, packageName);
3427        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3428                false /* requireFullPermission */, false /* checkShell */, "get package info");
3429
3430        // reader
3431        synchronized (mPackages) {
3432            // Normalize package name to handle renamed packages and static libs
3433            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3434
3435            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3436            if (matchFactoryOnly) {
3437                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3438                if (ps != null) {
3439                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3440                        return null;
3441                    }
3442                    return generatePackageInfo(ps, flags, userId);
3443                }
3444            }
3445
3446            PackageParser.Package p = mPackages.get(packageName);
3447            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3448                return null;
3449            }
3450            if (DEBUG_PACKAGE_INFO)
3451                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3452            if (p != null) {
3453                if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
3454                        Binder.getCallingUid(), userId)) {
3455                    return null;
3456                }
3457                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3458            }
3459            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3460                final PackageSetting ps = mSettings.mPackages.get(packageName);
3461                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3462                    return null;
3463                }
3464                return generatePackageInfo(ps, flags, userId);
3465            }
3466        }
3467        return null;
3468    }
3469
3470
3471    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) {
3472        // System/shell/root get to see all static libs
3473        final int appId = UserHandle.getAppId(uid);
3474        if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3475                || appId == Process.ROOT_UID) {
3476            return false;
3477        }
3478
3479        // No package means no static lib as it is always on internal storage
3480        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3481            return false;
3482        }
3483
3484        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3485                ps.pkg.staticSharedLibVersion);
3486        if (libEntry == null) {
3487            return false;
3488        }
3489
3490        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3491        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3492        if (uidPackageNames == null) {
3493            return true;
3494        }
3495
3496        for (String uidPackageName : uidPackageNames) {
3497            if (ps.name.equals(uidPackageName)) {
3498                return false;
3499            }
3500            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3501            if (uidPs != null) {
3502                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3503                        libEntry.info.getName());
3504                if (index < 0) {
3505                    continue;
3506                }
3507                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3508                    return false;
3509                }
3510            }
3511        }
3512        return true;
3513    }
3514
3515    @Override
3516    public String[] currentToCanonicalPackageNames(String[] names) {
3517        String[] out = new String[names.length];
3518        // reader
3519        synchronized (mPackages) {
3520            for (int i=names.length-1; i>=0; i--) {
3521                PackageSetting ps = mSettings.mPackages.get(names[i]);
3522                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3523            }
3524        }
3525        return out;
3526    }
3527
3528    @Override
3529    public String[] canonicalToCurrentPackageNames(String[] names) {
3530        String[] out = new String[names.length];
3531        // reader
3532        synchronized (mPackages) {
3533            for (int i=names.length-1; i>=0; i--) {
3534                String cur = mSettings.getRenamedPackageLPr(names[i]);
3535                out[i] = cur != null ? cur : names[i];
3536            }
3537        }
3538        return out;
3539    }
3540
3541    @Override
3542    public int getPackageUid(String packageName, int flags, int userId) {
3543        if (!sUserManager.exists(userId)) return -1;
3544        flags = updateFlagsForPackage(flags, userId, packageName);
3545        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3546                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3547
3548        // reader
3549        synchronized (mPackages) {
3550            final PackageParser.Package p = mPackages.get(packageName);
3551            if (p != null && p.isMatch(flags)) {
3552                return UserHandle.getUid(userId, p.applicationInfo.uid);
3553            }
3554            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3555                final PackageSetting ps = mSettings.mPackages.get(packageName);
3556                if (ps != null && ps.isMatch(flags)) {
3557                    return UserHandle.getUid(userId, ps.appId);
3558                }
3559            }
3560        }
3561
3562        return -1;
3563    }
3564
3565    @Override
3566    public int[] getPackageGids(String packageName, int flags, int userId) {
3567        if (!sUserManager.exists(userId)) return null;
3568        flags = updateFlagsForPackage(flags, userId, packageName);
3569        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3570                false /* requireFullPermission */, false /* checkShell */,
3571                "getPackageGids");
3572
3573        // reader
3574        synchronized (mPackages) {
3575            final PackageParser.Package p = mPackages.get(packageName);
3576            if (p != null && p.isMatch(flags)) {
3577                PackageSetting ps = (PackageSetting) p.mExtras;
3578                // TODO: Shouldn't this be checking for package installed state for userId and
3579                // return null?
3580                return ps.getPermissionsState().computeGids(userId);
3581            }
3582            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3583                final PackageSetting ps = mSettings.mPackages.get(packageName);
3584                if (ps != null && ps.isMatch(flags)) {
3585                    return ps.getPermissionsState().computeGids(userId);
3586                }
3587            }
3588        }
3589
3590        return null;
3591    }
3592
3593    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3594        if (bp.perm != null) {
3595            return PackageParser.generatePermissionInfo(bp.perm, flags);
3596        }
3597        PermissionInfo pi = new PermissionInfo();
3598        pi.name = bp.name;
3599        pi.packageName = bp.sourcePackage;
3600        pi.nonLocalizedLabel = bp.name;
3601        pi.protectionLevel = bp.protectionLevel;
3602        return pi;
3603    }
3604
3605    @Override
3606    public PermissionInfo getPermissionInfo(String name, int flags) {
3607        // reader
3608        synchronized (mPackages) {
3609            final BasePermission p = mSettings.mPermissions.get(name);
3610            if (p != null) {
3611                return generatePermissionInfo(p, flags);
3612            }
3613            return null;
3614        }
3615    }
3616
3617    @Override
3618    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3619            int flags) {
3620        // reader
3621        synchronized (mPackages) {
3622            if (group != null && !mPermissionGroups.containsKey(group)) {
3623                // This is thrown as NameNotFoundException
3624                return null;
3625            }
3626
3627            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3628            for (BasePermission p : mSettings.mPermissions.values()) {
3629                if (group == null) {
3630                    if (p.perm == null || p.perm.info.group == null) {
3631                        out.add(generatePermissionInfo(p, flags));
3632                    }
3633                } else {
3634                    if (p.perm != null && group.equals(p.perm.info.group)) {
3635                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3636                    }
3637                }
3638            }
3639            return new ParceledListSlice<>(out);
3640        }
3641    }
3642
3643    @Override
3644    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3645        // reader
3646        synchronized (mPackages) {
3647            return PackageParser.generatePermissionGroupInfo(
3648                    mPermissionGroups.get(name), flags);
3649        }
3650    }
3651
3652    @Override
3653    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3654        // reader
3655        synchronized (mPackages) {
3656            final int N = mPermissionGroups.size();
3657            ArrayList<PermissionGroupInfo> out
3658                    = new ArrayList<PermissionGroupInfo>(N);
3659            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3660                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3661            }
3662            return new ParceledListSlice<>(out);
3663        }
3664    }
3665
3666    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3667            int uid, int userId) {
3668        if (!sUserManager.exists(userId)) return null;
3669        PackageSetting ps = mSettings.mPackages.get(packageName);
3670        if (ps != null) {
3671            if (filterSharedLibPackageLPr(ps, uid, userId)) {
3672                return null;
3673            }
3674            if (ps.pkg == null) {
3675                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3676                if (pInfo != null) {
3677                    return pInfo.applicationInfo;
3678                }
3679                return null;
3680            }
3681            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3682                    ps.readUserState(userId), userId);
3683            if (ai != null) {
3684                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
3685            }
3686            return ai;
3687        }
3688        return null;
3689    }
3690
3691    @Override
3692    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3693        if (!sUserManager.exists(userId)) return null;
3694        flags = updateFlagsForApplication(flags, userId, packageName);
3695        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3696                false /* requireFullPermission */, false /* checkShell */, "get application info");
3697
3698        // writer
3699        synchronized (mPackages) {
3700            // Normalize package name to handle renamed packages and static libs
3701            packageName = resolveInternalPackageNameLPr(packageName,
3702                    PackageManager.VERSION_CODE_HIGHEST);
3703
3704            PackageParser.Package p = mPackages.get(packageName);
3705            if (DEBUG_PACKAGE_INFO) Log.v(
3706                    TAG, "getApplicationInfo " + packageName
3707                    + ": " + p);
3708            if (p != null) {
3709                PackageSetting ps = mSettings.mPackages.get(packageName);
3710                if (ps == null) return null;
3711                if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
3712                    return null;
3713                }
3714                // Note: isEnabledLP() does not apply here - always return info
3715                ApplicationInfo ai = PackageParser.generateApplicationInfo(
3716                        p, flags, ps.readUserState(userId), userId);
3717                if (ai != null) {
3718                    ai.packageName = resolveExternalPackageNameLPr(p);
3719                }
3720                return ai;
3721            }
3722            if ("android".equals(packageName)||"system".equals(packageName)) {
3723                return mAndroidApplication;
3724            }
3725            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3726                // Already generates the external package name
3727                return generateApplicationInfoFromSettingsLPw(packageName,
3728                        Binder.getCallingUid(), flags, userId);
3729            }
3730        }
3731        return null;
3732    }
3733
3734    private String normalizePackageNameLPr(String packageName) {
3735        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
3736        return normalizedPackageName != null ? normalizedPackageName : packageName;
3737    }
3738
3739    @Override
3740    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3741            final IPackageDataObserver observer) {
3742        mContext.enforceCallingOrSelfPermission(
3743                android.Manifest.permission.CLEAR_APP_CACHE, null);
3744        // Queue up an async operation since clearing cache may take a little while.
3745        mHandler.post(new Runnable() {
3746            public void run() {
3747                mHandler.removeCallbacks(this);
3748                boolean success = true;
3749                synchronized (mInstallLock) {
3750                    try {
3751                        mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3752                    } catch (InstallerException e) {
3753                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3754                        success = false;
3755                    }
3756                }
3757                if (observer != null) {
3758                    try {
3759                        observer.onRemoveCompleted(null, success);
3760                    } catch (RemoteException e) {
3761                        Slog.w(TAG, "RemoveException when invoking call back");
3762                    }
3763                }
3764            }
3765        });
3766    }
3767
3768    @Override
3769    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3770            final IntentSender pi) {
3771        mContext.enforceCallingOrSelfPermission(
3772                android.Manifest.permission.CLEAR_APP_CACHE, null);
3773        // Queue up an async operation since clearing cache may take a little while.
3774        mHandler.post(new Runnable() {
3775            public void run() {
3776                mHandler.removeCallbacks(this);
3777                boolean success = true;
3778                synchronized (mInstallLock) {
3779                    try {
3780                        mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3781                    } catch (InstallerException e) {
3782                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3783                        success = false;
3784                    }
3785                }
3786                if(pi != null) {
3787                    try {
3788                        // Callback via pending intent
3789                        int code = success ? 1 : 0;
3790                        pi.sendIntent(null, code, null,
3791                                null, null);
3792                    } catch (SendIntentException e1) {
3793                        Slog.i(TAG, "Failed to send pending intent");
3794                    }
3795                }
3796            }
3797        });
3798    }
3799
3800    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3801        synchronized (mInstallLock) {
3802            try {
3803                mInstaller.freeCache(volumeUuid, freeStorageSize, 0);
3804            } catch (InstallerException e) {
3805                throw new IOException("Failed to free enough space", e);
3806            }
3807        }
3808    }
3809
3810    /**
3811     * Update given flags based on encryption status of current user.
3812     */
3813    private int updateFlags(int flags, int userId) {
3814        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3815                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3816            // Caller expressed an explicit opinion about what encryption
3817            // aware/unaware components they want to see, so fall through and
3818            // give them what they want
3819        } else {
3820            // Caller expressed no opinion, so match based on user state
3821            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3822                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3823            } else {
3824                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3825            }
3826        }
3827        return flags;
3828    }
3829
3830    private UserManagerInternal getUserManagerInternal() {
3831        if (mUserManagerInternal == null) {
3832            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3833        }
3834        return mUserManagerInternal;
3835    }
3836
3837    /**
3838     * Update given flags when being used to request {@link PackageInfo}.
3839     */
3840    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3841        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
3842        boolean triaged = true;
3843        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3844                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3845            // Caller is asking for component details, so they'd better be
3846            // asking for specific encryption matching behavior, or be triaged
3847            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3848                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3849                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3850                triaged = false;
3851            }
3852        }
3853        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3854                | PackageManager.MATCH_SYSTEM_ONLY
3855                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3856            triaged = false;
3857        }
3858        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
3859            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
3860                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
3861                    + Debug.getCallers(5));
3862        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
3863                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
3864            // If the caller wants all packages and has a restricted profile associated with it,
3865            // then match all users. This is to make sure that launchers that need to access work
3866            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
3867            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
3868            flags |= PackageManager.MATCH_ANY_USER;
3869        }
3870        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3871            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3872                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3873        }
3874        return updateFlags(flags, userId);
3875    }
3876
3877    /**
3878     * Update given flags when being used to request {@link ApplicationInfo}.
3879     */
3880    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3881        return updateFlagsForPackage(flags, userId, cookie);
3882    }
3883
3884    /**
3885     * Update given flags when being used to request {@link ComponentInfo}.
3886     */
3887    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3888        if (cookie instanceof Intent) {
3889            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3890                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3891            }
3892        }
3893
3894        boolean triaged = true;
3895        // Caller is asking for component details, so they'd better be
3896        // asking for specific encryption matching behavior, or be triaged
3897        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3898                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3899                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3900            triaged = false;
3901        }
3902        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3903            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3904                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3905        }
3906
3907        return updateFlags(flags, userId);
3908    }
3909
3910    /**
3911     * Update given intent when being used to request {@link ResolveInfo}.
3912     */
3913    private Intent updateIntentForResolve(Intent intent) {
3914        if (intent.getSelector() != null) {
3915            intent = intent.getSelector();
3916        }
3917        if (DEBUG_PREFERRED) {
3918            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3919        }
3920        return intent;
3921    }
3922
3923    /**
3924     * Update given flags when being used to request {@link ResolveInfo}.
3925     */
3926    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3927        // Safe mode means we shouldn't match any third-party components
3928        if (mSafeMode) {
3929            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3930        }
3931        final int callingUid = Binder.getCallingUid();
3932        if (callingUid == Process.SYSTEM_UID || callingUid == 0) {
3933            // The system sees all components
3934            flags |= PackageManager.MATCH_EPHEMERAL;
3935        } else if (getEphemeralPackageName(callingUid) != null) {
3936            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
3937            flags |= PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY;
3938            flags |= PackageManager.MATCH_EPHEMERAL;
3939        } else {
3940            // Otherwise, prevent leaking ephemeral components
3941            flags &= ~PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY;
3942            flags &= ~PackageManager.MATCH_EPHEMERAL;
3943        }
3944        return updateFlagsForComponent(flags, userId, cookie);
3945    }
3946
3947    @Override
3948    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3949        if (!sUserManager.exists(userId)) return null;
3950        flags = updateFlagsForComponent(flags, userId, component);
3951        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3952                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3953        synchronized (mPackages) {
3954            PackageParser.Activity a = mActivities.mActivities.get(component);
3955
3956            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3957            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3958                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3959                if (ps == null) return null;
3960                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3961                        userId);
3962            }
3963            if (mResolveComponentName.equals(component)) {
3964                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3965                        new PackageUserState(), userId);
3966            }
3967        }
3968        return null;
3969    }
3970
3971    @Override
3972    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3973            String resolvedType) {
3974        synchronized (mPackages) {
3975            if (component.equals(mResolveComponentName)) {
3976                // The resolver supports EVERYTHING!
3977                return true;
3978            }
3979            PackageParser.Activity a = mActivities.mActivities.get(component);
3980            if (a == null) {
3981                return false;
3982            }
3983            for (int i=0; i<a.intents.size(); i++) {
3984                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3985                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3986                    return true;
3987                }
3988            }
3989            return false;
3990        }
3991    }
3992
3993    @Override
3994    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3995        if (!sUserManager.exists(userId)) return null;
3996        flags = updateFlagsForComponent(flags, userId, component);
3997        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3998                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3999        synchronized (mPackages) {
4000            PackageParser.Activity a = mReceivers.mActivities.get(component);
4001            if (DEBUG_PACKAGE_INFO) Log.v(
4002                TAG, "getReceiverInfo " + component + ": " + a);
4003            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4004                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4005                if (ps == null) return null;
4006                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
4007                        userId);
4008            }
4009        }
4010        return null;
4011    }
4012
4013    @Override
4014    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) {
4015        if (!sUserManager.exists(userId)) return null;
4016        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4017
4018        flags = updateFlagsForPackage(flags, userId, null);
4019
4020        final boolean canSeeStaticLibraries =
4021                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4022                        == PERMISSION_GRANTED
4023                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4024                        == PERMISSION_GRANTED
4025                || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES)
4026                        == PERMISSION_GRANTED
4027                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4028                        == PERMISSION_GRANTED;
4029
4030        synchronized (mPackages) {
4031            List<SharedLibraryInfo> result = null;
4032
4033            final int libCount = mSharedLibraries.size();
4034            for (int i = 0; i < libCount; i++) {
4035                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4036                if (versionedLib == null) {
4037                    continue;
4038                }
4039
4040                final int versionCount = versionedLib.size();
4041                for (int j = 0; j < versionCount; j++) {
4042                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4043                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4044                        break;
4045                    }
4046                    final long identity = Binder.clearCallingIdentity();
4047                    try {
4048                        // TODO: We will change version code to long, so in the new API it is long
4049                        PackageInfo packageInfo = getPackageInfoVersioned(
4050                                libInfo.getDeclaringPackage(), flags, userId);
4051                        if (packageInfo == null) {
4052                            continue;
4053                        }
4054                    } finally {
4055                        Binder.restoreCallingIdentity(identity);
4056                    }
4057
4058                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4059                            libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(),
4060                            getPackagesUsingSharedLibraryLPr(libInfo, flags, userId));
4061
4062                    if (result == null) {
4063                        result = new ArrayList<>();
4064                    }
4065                    result.add(resLibInfo);
4066                }
4067            }
4068
4069            return result != null ? new ParceledListSlice<>(result) : null;
4070        }
4071    }
4072
4073    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4074            SharedLibraryInfo libInfo, int flags, int userId) {
4075        List<VersionedPackage> versionedPackages = null;
4076        final int packageCount = mSettings.mPackages.size();
4077        for (int i = 0; i < packageCount; i++) {
4078            PackageSetting ps = mSettings.mPackages.valueAt(i);
4079
4080            if (ps == null) {
4081                continue;
4082            }
4083
4084            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4085                continue;
4086            }
4087
4088            final String libName = libInfo.getName();
4089            if (libInfo.isStatic()) {
4090                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4091                if (libIdx < 0) {
4092                    continue;
4093                }
4094                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4095                    continue;
4096                }
4097                if (versionedPackages == null) {
4098                    versionedPackages = new ArrayList<>();
4099                }
4100                // If the dependent is a static shared lib, use the public package name
4101                String dependentPackageName = ps.name;
4102                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4103                    dependentPackageName = ps.pkg.manifestPackageName;
4104                }
4105                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4106            } else if (ps.pkg != null) {
4107                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4108                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4109                    if (versionedPackages == null) {
4110                        versionedPackages = new ArrayList<>();
4111                    }
4112                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4113                }
4114            }
4115        }
4116
4117        return versionedPackages;
4118    }
4119
4120    @Override
4121    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4122        if (!sUserManager.exists(userId)) return null;
4123        flags = updateFlagsForComponent(flags, userId, component);
4124        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4125                false /* requireFullPermission */, false /* checkShell */, "get service info");
4126        synchronized (mPackages) {
4127            PackageParser.Service s = mServices.mServices.get(component);
4128            if (DEBUG_PACKAGE_INFO) Log.v(
4129                TAG, "getServiceInfo " + component + ": " + s);
4130            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4131                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4132                if (ps == null) return null;
4133                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
4134                        userId);
4135            }
4136        }
4137        return null;
4138    }
4139
4140    @Override
4141    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4142        if (!sUserManager.exists(userId)) return null;
4143        flags = updateFlagsForComponent(flags, userId, component);
4144        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4145                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4146        synchronized (mPackages) {
4147            PackageParser.Provider p = mProviders.mProviders.get(component);
4148            if (DEBUG_PACKAGE_INFO) Log.v(
4149                TAG, "getProviderInfo " + component + ": " + p);
4150            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4151                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4152                if (ps == null) return null;
4153                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
4154                        userId);
4155            }
4156        }
4157        return null;
4158    }
4159
4160    @Override
4161    public String[] getSystemSharedLibraryNames() {
4162        synchronized (mPackages) {
4163            Set<String> libs = null;
4164            final int libCount = mSharedLibraries.size();
4165            for (int i = 0; i < libCount; i++) {
4166                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4167                if (versionedLib == null) {
4168                    continue;
4169                }
4170                final int versionCount = versionedLib.size();
4171                for (int j = 0; j < versionCount; j++) {
4172                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4173                    if (!libEntry.info.isStatic()) {
4174                        if (libs == null) {
4175                            libs = new ArraySet<>();
4176                        }
4177                        libs.add(libEntry.info.getName());
4178                        break;
4179                    }
4180                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4181                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4182                            UserHandle.getUserId(Binder.getCallingUid()))) {
4183                        if (libs == null) {
4184                            libs = new ArraySet<>();
4185                        }
4186                        libs.add(libEntry.info.getName());
4187                        break;
4188                    }
4189                }
4190            }
4191
4192            if (libs != null) {
4193                String[] libsArray = new String[libs.size()];
4194                libs.toArray(libsArray);
4195                return libsArray;
4196            }
4197
4198            return null;
4199        }
4200    }
4201
4202    @Override
4203    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4204        synchronized (mPackages) {
4205            return mServicesSystemSharedLibraryPackageName;
4206        }
4207    }
4208
4209    @Override
4210    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4211        synchronized (mPackages) {
4212            return mSharedSystemSharedLibraryPackageName;
4213        }
4214    }
4215
4216    @Override
4217    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4218        synchronized (mPackages) {
4219            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
4220
4221            final FeatureInfo fi = new FeatureInfo();
4222            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4223                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
4224            res.add(fi);
4225
4226            return new ParceledListSlice<>(res);
4227        }
4228    }
4229
4230    @Override
4231    public boolean hasSystemFeature(String name, int version) {
4232        synchronized (mPackages) {
4233            final FeatureInfo feat = mAvailableFeatures.get(name);
4234            if (feat == null) {
4235                return false;
4236            } else {
4237                return feat.version >= version;
4238            }
4239        }
4240    }
4241
4242    @Override
4243    public int checkPermission(String permName, String pkgName, int userId) {
4244        if (!sUserManager.exists(userId)) {
4245            return PackageManager.PERMISSION_DENIED;
4246        }
4247
4248        synchronized (mPackages) {
4249            final PackageParser.Package p = mPackages.get(pkgName);
4250            if (p != null && p.mExtras != null) {
4251                final PackageSetting ps = (PackageSetting) p.mExtras;
4252                final PermissionsState permissionsState = ps.getPermissionsState();
4253                if (permissionsState.hasPermission(permName, userId)) {
4254                    return PackageManager.PERMISSION_GRANTED;
4255                }
4256                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4257                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4258                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4259                    return PackageManager.PERMISSION_GRANTED;
4260                }
4261            }
4262        }
4263
4264        return PackageManager.PERMISSION_DENIED;
4265    }
4266
4267    @Override
4268    public int checkUidPermission(String permName, int uid) {
4269        final int userId = UserHandle.getUserId(uid);
4270
4271        if (!sUserManager.exists(userId)) {
4272            return PackageManager.PERMISSION_DENIED;
4273        }
4274
4275        synchronized (mPackages) {
4276            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4277            if (obj != null) {
4278                final SettingBase ps = (SettingBase) obj;
4279                final PermissionsState permissionsState = ps.getPermissionsState();
4280                if (permissionsState.hasPermission(permName, userId)) {
4281                    return PackageManager.PERMISSION_GRANTED;
4282                }
4283                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
4284                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
4285                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
4286                    return PackageManager.PERMISSION_GRANTED;
4287                }
4288            } else {
4289                ArraySet<String> perms = mSystemPermissions.get(uid);
4290                if (perms != null) {
4291                    if (perms.contains(permName)) {
4292                        return PackageManager.PERMISSION_GRANTED;
4293                    }
4294                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
4295                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
4296                        return PackageManager.PERMISSION_GRANTED;
4297                    }
4298                }
4299            }
4300        }
4301
4302        return PackageManager.PERMISSION_DENIED;
4303    }
4304
4305    @Override
4306    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
4307        if (UserHandle.getCallingUserId() != userId) {
4308            mContext.enforceCallingPermission(
4309                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4310                    "isPermissionRevokedByPolicy for user " + userId);
4311        }
4312
4313        if (checkPermission(permission, packageName, userId)
4314                == PackageManager.PERMISSION_GRANTED) {
4315            return false;
4316        }
4317
4318        final long identity = Binder.clearCallingIdentity();
4319        try {
4320            final int flags = getPermissionFlags(permission, packageName, userId);
4321            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
4322        } finally {
4323            Binder.restoreCallingIdentity(identity);
4324        }
4325    }
4326
4327    @Override
4328    public String getPermissionControllerPackageName() {
4329        synchronized (mPackages) {
4330            return mRequiredInstallerPackage;
4331        }
4332    }
4333
4334    /**
4335     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
4336     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
4337     * @param checkShell whether to prevent shell from access if there's a debugging restriction
4338     * @param message the message to log on security exception
4339     */
4340    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
4341            boolean checkShell, String message) {
4342        if (userId < 0) {
4343            throw new IllegalArgumentException("Invalid userId " + userId);
4344        }
4345        if (checkShell) {
4346            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
4347        }
4348        if (userId == UserHandle.getUserId(callingUid)) return;
4349        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4350            if (requireFullPermission) {
4351                mContext.enforceCallingOrSelfPermission(
4352                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4353            } else {
4354                try {
4355                    mContext.enforceCallingOrSelfPermission(
4356                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
4357                } catch (SecurityException se) {
4358                    mContext.enforceCallingOrSelfPermission(
4359                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
4360                }
4361            }
4362        }
4363    }
4364
4365    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
4366        if (callingUid == Process.SHELL_UID) {
4367            if (userHandle >= 0
4368                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
4369                throw new SecurityException("Shell does not have permission to access user "
4370                        + userHandle);
4371            } else if (userHandle < 0) {
4372                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
4373                        + Debug.getCallers(3));
4374            }
4375        }
4376    }
4377
4378    private BasePermission findPermissionTreeLP(String permName) {
4379        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
4380            if (permName.startsWith(bp.name) &&
4381                    permName.length() > bp.name.length() &&
4382                    permName.charAt(bp.name.length()) == '.') {
4383                return bp;
4384            }
4385        }
4386        return null;
4387    }
4388
4389    private BasePermission checkPermissionTreeLP(String permName) {
4390        if (permName != null) {
4391            BasePermission bp = findPermissionTreeLP(permName);
4392            if (bp != null) {
4393                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
4394                    return bp;
4395                }
4396                throw new SecurityException("Calling uid "
4397                        + Binder.getCallingUid()
4398                        + " is not allowed to add to permission tree "
4399                        + bp.name + " owned by uid " + bp.uid);
4400            }
4401        }
4402        throw new SecurityException("No permission tree found for " + permName);
4403    }
4404
4405    static boolean compareStrings(CharSequence s1, CharSequence s2) {
4406        if (s1 == null) {
4407            return s2 == null;
4408        }
4409        if (s2 == null) {
4410            return false;
4411        }
4412        if (s1.getClass() != s2.getClass()) {
4413            return false;
4414        }
4415        return s1.equals(s2);
4416    }
4417
4418    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
4419        if (pi1.icon != pi2.icon) return false;
4420        if (pi1.logo != pi2.logo) return false;
4421        if (pi1.protectionLevel != pi2.protectionLevel) return false;
4422        if (!compareStrings(pi1.name, pi2.name)) return false;
4423        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
4424        // We'll take care of setting this one.
4425        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
4426        // These are not currently stored in settings.
4427        //if (!compareStrings(pi1.group, pi2.group)) return false;
4428        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
4429        //if (pi1.labelRes != pi2.labelRes) return false;
4430        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
4431        return true;
4432    }
4433
4434    int permissionInfoFootprint(PermissionInfo info) {
4435        int size = info.name.length();
4436        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
4437        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
4438        return size;
4439    }
4440
4441    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
4442        int size = 0;
4443        for (BasePermission perm : mSettings.mPermissions.values()) {
4444            if (perm.uid == tree.uid) {
4445                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
4446            }
4447        }
4448        return size;
4449    }
4450
4451    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4452        // We calculate the max size of permissions defined by this uid and throw
4453        // if that plus the size of 'info' would exceed our stated maximum.
4454        if (tree.uid != Process.SYSTEM_UID) {
4455            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4456            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4457                throw new SecurityException("Permission tree size cap exceeded");
4458            }
4459        }
4460    }
4461
4462    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4463        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4464            throw new SecurityException("Label must be specified in permission");
4465        }
4466        BasePermission tree = checkPermissionTreeLP(info.name);
4467        BasePermission bp = mSettings.mPermissions.get(info.name);
4468        boolean added = bp == null;
4469        boolean changed = true;
4470        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4471        if (added) {
4472            enforcePermissionCapLocked(info, tree);
4473            bp = new BasePermission(info.name, tree.sourcePackage,
4474                    BasePermission.TYPE_DYNAMIC);
4475        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4476            throw new SecurityException(
4477                    "Not allowed to modify non-dynamic permission "
4478                    + info.name);
4479        } else {
4480            if (bp.protectionLevel == fixedLevel
4481                    && bp.perm.owner.equals(tree.perm.owner)
4482                    && bp.uid == tree.uid
4483                    && comparePermissionInfos(bp.perm.info, info)) {
4484                changed = false;
4485            }
4486        }
4487        bp.protectionLevel = fixedLevel;
4488        info = new PermissionInfo(info);
4489        info.protectionLevel = fixedLevel;
4490        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4491        bp.perm.info.packageName = tree.perm.info.packageName;
4492        bp.uid = tree.uid;
4493        if (added) {
4494            mSettings.mPermissions.put(info.name, bp);
4495        }
4496        if (changed) {
4497            if (!async) {
4498                mSettings.writeLPr();
4499            } else {
4500                scheduleWriteSettingsLocked();
4501            }
4502        }
4503        return added;
4504    }
4505
4506    @Override
4507    public boolean addPermission(PermissionInfo info) {
4508        synchronized (mPackages) {
4509            return addPermissionLocked(info, false);
4510        }
4511    }
4512
4513    @Override
4514    public boolean addPermissionAsync(PermissionInfo info) {
4515        synchronized (mPackages) {
4516            return addPermissionLocked(info, true);
4517        }
4518    }
4519
4520    @Override
4521    public void removePermission(String name) {
4522        synchronized (mPackages) {
4523            checkPermissionTreeLP(name);
4524            BasePermission bp = mSettings.mPermissions.get(name);
4525            if (bp != null) {
4526                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4527                    throw new SecurityException(
4528                            "Not allowed to modify non-dynamic permission "
4529                            + name);
4530                }
4531                mSettings.mPermissions.remove(name);
4532                mSettings.writeLPr();
4533            }
4534        }
4535    }
4536
4537    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4538            BasePermission bp) {
4539        int index = pkg.requestedPermissions.indexOf(bp.name);
4540        if (index == -1) {
4541            throw new SecurityException("Package " + pkg.packageName
4542                    + " has not requested permission " + bp.name);
4543        }
4544        if (!bp.isRuntime() && !bp.isDevelopment()) {
4545            throw new SecurityException("Permission " + bp.name
4546                    + " is not a changeable permission type");
4547        }
4548    }
4549
4550    @Override
4551    public void grantRuntimePermission(String packageName, String name, final int userId) {
4552        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4553    }
4554
4555    private void grantRuntimePermission(String packageName, String name, final int userId,
4556            boolean overridePolicy) {
4557        if (!sUserManager.exists(userId)) {
4558            Log.e(TAG, "No such user:" + userId);
4559            return;
4560        }
4561
4562        mContext.enforceCallingOrSelfPermission(
4563                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4564                "grantRuntimePermission");
4565
4566        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4567                true /* requireFullPermission */, true /* checkShell */,
4568                "grantRuntimePermission");
4569
4570        final int uid;
4571        final SettingBase sb;
4572
4573        synchronized (mPackages) {
4574            final PackageParser.Package pkg = mPackages.get(packageName);
4575            if (pkg == null) {
4576                throw new IllegalArgumentException("Unknown package: " + packageName);
4577            }
4578
4579            final BasePermission bp = mSettings.mPermissions.get(name);
4580            if (bp == null) {
4581                throw new IllegalArgumentException("Unknown permission: " + name);
4582            }
4583
4584            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4585
4586            // If a permission review is required for legacy apps we represent
4587            // their permissions as always granted runtime ones since we need
4588            // to keep the review required permission flag per user while an
4589            // install permission's state is shared across all users.
4590            if (mPermissionReviewRequired
4591                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4592                    && bp.isRuntime()) {
4593                return;
4594            }
4595
4596            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4597            sb = (SettingBase) pkg.mExtras;
4598            if (sb == null) {
4599                throw new IllegalArgumentException("Unknown package: " + packageName);
4600            }
4601
4602            final PermissionsState permissionsState = sb.getPermissionsState();
4603
4604            final int flags = permissionsState.getPermissionFlags(name, userId);
4605            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4606                throw new SecurityException("Cannot grant system fixed permission "
4607                        + name + " for package " + packageName);
4608            }
4609            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4610                throw new SecurityException("Cannot grant policy fixed permission "
4611                        + name + " for package " + packageName);
4612            }
4613
4614            if (bp.isDevelopment()) {
4615                // Development permissions must be handled specially, since they are not
4616                // normal runtime permissions.  For now they apply to all users.
4617                if (permissionsState.grantInstallPermission(bp) !=
4618                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4619                    scheduleWriteSettingsLocked();
4620                }
4621                return;
4622            }
4623
4624            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
4625                throw new SecurityException("Cannot grant non-ephemeral permission"
4626                        + name + " for package " + packageName);
4627            }
4628
4629            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4630                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4631                return;
4632            }
4633
4634            final int result = permissionsState.grantRuntimePermission(bp, userId);
4635            switch (result) {
4636                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4637                    return;
4638                }
4639
4640                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4641                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4642                    mHandler.post(new Runnable() {
4643                        @Override
4644                        public void run() {
4645                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4646                        }
4647                    });
4648                }
4649                break;
4650            }
4651
4652            if (bp.isRuntime()) {
4653                logPermissionGranted(mContext, name, packageName);
4654            }
4655
4656            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4657
4658            // Not critical if that is lost - app has to request again.
4659            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4660        }
4661
4662        // Only need to do this if user is initialized. Otherwise it's a new user
4663        // and there are no processes running as the user yet and there's no need
4664        // to make an expensive call to remount processes for the changed permissions.
4665        if (READ_EXTERNAL_STORAGE.equals(name)
4666                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4667            final long token = Binder.clearCallingIdentity();
4668            try {
4669                if (sUserManager.isInitialized(userId)) {
4670                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
4671                            StorageManagerInternal.class);
4672                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
4673                }
4674            } finally {
4675                Binder.restoreCallingIdentity(token);
4676            }
4677        }
4678    }
4679
4680    @Override
4681    public void revokeRuntimePermission(String packageName, String name, int userId) {
4682        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
4683    }
4684
4685    private void revokeRuntimePermission(String packageName, String name, int userId,
4686            boolean overridePolicy) {
4687        if (!sUserManager.exists(userId)) {
4688            Log.e(TAG, "No such user:" + userId);
4689            return;
4690        }
4691
4692        mContext.enforceCallingOrSelfPermission(
4693                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4694                "revokeRuntimePermission");
4695
4696        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4697                true /* requireFullPermission */, true /* checkShell */,
4698                "revokeRuntimePermission");
4699
4700        final int appId;
4701
4702        synchronized (mPackages) {
4703            final PackageParser.Package pkg = mPackages.get(packageName);
4704            if (pkg == null) {
4705                throw new IllegalArgumentException("Unknown package: " + packageName);
4706            }
4707
4708            final BasePermission bp = mSettings.mPermissions.get(name);
4709            if (bp == null) {
4710                throw new IllegalArgumentException("Unknown permission: " + name);
4711            }
4712
4713            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4714
4715            // If a permission review is required for legacy apps we represent
4716            // their permissions as always granted runtime ones since we need
4717            // to keep the review required permission flag per user while an
4718            // install permission's state is shared across all users.
4719            if (mPermissionReviewRequired
4720                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4721                    && bp.isRuntime()) {
4722                return;
4723            }
4724
4725            SettingBase sb = (SettingBase) pkg.mExtras;
4726            if (sb == null) {
4727                throw new IllegalArgumentException("Unknown package: " + packageName);
4728            }
4729
4730            final PermissionsState permissionsState = sb.getPermissionsState();
4731
4732            final int flags = permissionsState.getPermissionFlags(name, userId);
4733            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4734                throw new SecurityException("Cannot revoke system fixed permission "
4735                        + name + " for package " + packageName);
4736            }
4737            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
4738                throw new SecurityException("Cannot revoke policy fixed permission "
4739                        + name + " for package " + packageName);
4740            }
4741
4742            if (bp.isDevelopment()) {
4743                // Development permissions must be handled specially, since they are not
4744                // normal runtime permissions.  For now they apply to all users.
4745                if (permissionsState.revokeInstallPermission(bp) !=
4746                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4747                    scheduleWriteSettingsLocked();
4748                }
4749                return;
4750            }
4751
4752            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4753                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4754                return;
4755            }
4756
4757            if (bp.isRuntime()) {
4758                logPermissionRevoked(mContext, name, packageName);
4759            }
4760
4761            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4762
4763            // Critical, after this call app should never have the permission.
4764            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4765
4766            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4767        }
4768
4769        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4770    }
4771
4772    /**
4773     * Get the first event id for the permission.
4774     *
4775     * <p>There are four events for each permission: <ul>
4776     *     <li>Request permission: first id + 0</li>
4777     *     <li>Grant permission: first id + 1</li>
4778     *     <li>Request for permission denied: first id + 2</li>
4779     *     <li>Revoke permission: first id + 3</li>
4780     * </ul></p>
4781     *
4782     * @param name name of the permission
4783     *
4784     * @return The first event id for the permission
4785     */
4786    private static int getBaseEventId(@NonNull String name) {
4787        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
4788
4789        if (eventIdIndex == -1) {
4790            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
4791                    || "user".equals(Build.TYPE)) {
4792                Log.i(TAG, "Unknown permission " + name);
4793
4794                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
4795            } else {
4796                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
4797                //
4798                // Also update
4799                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
4800                // - metrics_constants.proto
4801                throw new IllegalStateException("Unknown permission " + name);
4802            }
4803        }
4804
4805        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
4806    }
4807
4808    /**
4809     * Log that a permission was revoked.
4810     *
4811     * @param context Context of the caller
4812     * @param name name of the permission
4813     * @param packageName package permission if for
4814     */
4815    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
4816            @NonNull String packageName) {
4817        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
4818    }
4819
4820    /**
4821     * Log that a permission request was granted.
4822     *
4823     * @param context Context of the caller
4824     * @param name name of the permission
4825     * @param packageName package permission if for
4826     */
4827    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
4828            @NonNull String packageName) {
4829        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
4830    }
4831
4832    @Override
4833    public void resetRuntimePermissions() {
4834        mContext.enforceCallingOrSelfPermission(
4835                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4836                "revokeRuntimePermission");
4837
4838        int callingUid = Binder.getCallingUid();
4839        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4840            mContext.enforceCallingOrSelfPermission(
4841                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4842                    "resetRuntimePermissions");
4843        }
4844
4845        synchronized (mPackages) {
4846            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4847            for (int userId : UserManagerService.getInstance().getUserIds()) {
4848                final int packageCount = mPackages.size();
4849                for (int i = 0; i < packageCount; i++) {
4850                    PackageParser.Package pkg = mPackages.valueAt(i);
4851                    if (!(pkg.mExtras instanceof PackageSetting)) {
4852                        continue;
4853                    }
4854                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4855                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4856                }
4857            }
4858        }
4859    }
4860
4861    @Override
4862    public int getPermissionFlags(String name, String packageName, int userId) {
4863        if (!sUserManager.exists(userId)) {
4864            return 0;
4865        }
4866
4867        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4868
4869        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4870                true /* requireFullPermission */, false /* checkShell */,
4871                "getPermissionFlags");
4872
4873        synchronized (mPackages) {
4874            final PackageParser.Package pkg = mPackages.get(packageName);
4875            if (pkg == null) {
4876                return 0;
4877            }
4878
4879            final BasePermission bp = mSettings.mPermissions.get(name);
4880            if (bp == null) {
4881                return 0;
4882            }
4883
4884            SettingBase sb = (SettingBase) pkg.mExtras;
4885            if (sb == null) {
4886                return 0;
4887            }
4888
4889            PermissionsState permissionsState = sb.getPermissionsState();
4890            return permissionsState.getPermissionFlags(name, userId);
4891        }
4892    }
4893
4894    @Override
4895    public void updatePermissionFlags(String name, String packageName, int flagMask,
4896            int flagValues, int userId) {
4897        if (!sUserManager.exists(userId)) {
4898            return;
4899        }
4900
4901        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4902
4903        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4904                true /* requireFullPermission */, true /* checkShell */,
4905                "updatePermissionFlags");
4906
4907        // Only the system can change these flags and nothing else.
4908        if (getCallingUid() != Process.SYSTEM_UID) {
4909            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4910            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4911            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4912            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4913            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4914        }
4915
4916        synchronized (mPackages) {
4917            final PackageParser.Package pkg = mPackages.get(packageName);
4918            if (pkg == null) {
4919                throw new IllegalArgumentException("Unknown package: " + packageName);
4920            }
4921
4922            final BasePermission bp = mSettings.mPermissions.get(name);
4923            if (bp == null) {
4924                throw new IllegalArgumentException("Unknown permission: " + name);
4925            }
4926
4927            SettingBase sb = (SettingBase) pkg.mExtras;
4928            if (sb == null) {
4929                throw new IllegalArgumentException("Unknown package: " + packageName);
4930            }
4931
4932            PermissionsState permissionsState = sb.getPermissionsState();
4933
4934            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4935
4936            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4937                // Install and runtime permissions are stored in different places,
4938                // so figure out what permission changed and persist the change.
4939                if (permissionsState.getInstallPermissionState(name) != null) {
4940                    scheduleWriteSettingsLocked();
4941                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4942                        || hadState) {
4943                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4944                }
4945            }
4946        }
4947    }
4948
4949    /**
4950     * Update the permission flags for all packages and runtime permissions of a user in order
4951     * to allow device or profile owner to remove POLICY_FIXED.
4952     */
4953    @Override
4954    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4955        if (!sUserManager.exists(userId)) {
4956            return;
4957        }
4958
4959        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4960
4961        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4962                true /* requireFullPermission */, true /* checkShell */,
4963                "updatePermissionFlagsForAllApps");
4964
4965        // Only the system can change system fixed flags.
4966        if (getCallingUid() != Process.SYSTEM_UID) {
4967            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4968            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4969        }
4970
4971        synchronized (mPackages) {
4972            boolean changed = false;
4973            final int packageCount = mPackages.size();
4974            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4975                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4976                SettingBase sb = (SettingBase) pkg.mExtras;
4977                if (sb == null) {
4978                    continue;
4979                }
4980                PermissionsState permissionsState = sb.getPermissionsState();
4981                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4982                        userId, flagMask, flagValues);
4983            }
4984            if (changed) {
4985                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4986            }
4987        }
4988    }
4989
4990    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4991        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4992                != PackageManager.PERMISSION_GRANTED
4993            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4994                != PackageManager.PERMISSION_GRANTED) {
4995            throw new SecurityException(message + " requires "
4996                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4997                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4998        }
4999    }
5000
5001    @Override
5002    public boolean shouldShowRequestPermissionRationale(String permissionName,
5003            String packageName, int userId) {
5004        if (UserHandle.getCallingUserId() != userId) {
5005            mContext.enforceCallingPermission(
5006                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5007                    "canShowRequestPermissionRationale for user " + userId);
5008        }
5009
5010        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5011        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5012            return false;
5013        }
5014
5015        if (checkPermission(permissionName, packageName, userId)
5016                == PackageManager.PERMISSION_GRANTED) {
5017            return false;
5018        }
5019
5020        final int flags;
5021
5022        final long identity = Binder.clearCallingIdentity();
5023        try {
5024            flags = getPermissionFlags(permissionName,
5025                    packageName, userId);
5026        } finally {
5027            Binder.restoreCallingIdentity(identity);
5028        }
5029
5030        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5031                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5032                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5033
5034        if ((flags & fixedFlags) != 0) {
5035            return false;
5036        }
5037
5038        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5039    }
5040
5041    @Override
5042    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5043        mContext.enforceCallingOrSelfPermission(
5044                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5045                "addOnPermissionsChangeListener");
5046
5047        synchronized (mPackages) {
5048            mOnPermissionChangeListeners.addListenerLocked(listener);
5049        }
5050    }
5051
5052    @Override
5053    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5054        synchronized (mPackages) {
5055            mOnPermissionChangeListeners.removeListenerLocked(listener);
5056        }
5057    }
5058
5059    @Override
5060    public boolean isProtectedBroadcast(String actionName) {
5061        synchronized (mPackages) {
5062            if (mProtectedBroadcasts.contains(actionName)) {
5063                return true;
5064            } else if (actionName != null) {
5065                // TODO: remove these terrible hacks
5066                if (actionName.startsWith("android.net.netmon.lingerExpired")
5067                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5068                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5069                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5070                    return true;
5071                }
5072            }
5073        }
5074        return false;
5075    }
5076
5077    @Override
5078    public int checkSignatures(String pkg1, String pkg2) {
5079        synchronized (mPackages) {
5080            final PackageParser.Package p1 = mPackages.get(pkg1);
5081            final PackageParser.Package p2 = mPackages.get(pkg2);
5082            if (p1 == null || p1.mExtras == null
5083                    || p2 == null || p2.mExtras == null) {
5084                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5085            }
5086            return compareSignatures(p1.mSignatures, p2.mSignatures);
5087        }
5088    }
5089
5090    @Override
5091    public int checkUidSignatures(int uid1, int uid2) {
5092        // Map to base uids.
5093        uid1 = UserHandle.getAppId(uid1);
5094        uid2 = UserHandle.getAppId(uid2);
5095        // reader
5096        synchronized (mPackages) {
5097            Signature[] s1;
5098            Signature[] s2;
5099            Object obj = mSettings.getUserIdLPr(uid1);
5100            if (obj != null) {
5101                if (obj instanceof SharedUserSetting) {
5102                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5103                } else if (obj instanceof PackageSetting) {
5104                    s1 = ((PackageSetting)obj).signatures.mSignatures;
5105                } else {
5106                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5107                }
5108            } else {
5109                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5110            }
5111            obj = mSettings.getUserIdLPr(uid2);
5112            if (obj != null) {
5113                if (obj instanceof SharedUserSetting) {
5114                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5115                } else if (obj instanceof PackageSetting) {
5116                    s2 = ((PackageSetting)obj).signatures.mSignatures;
5117                } else {
5118                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5119                }
5120            } else {
5121                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5122            }
5123            return compareSignatures(s1, s2);
5124        }
5125    }
5126
5127    /**
5128     * This method should typically only be used when granting or revoking
5129     * permissions, since the app may immediately restart after this call.
5130     * <p>
5131     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5132     * guard your work against the app being relaunched.
5133     */
5134    private void killUid(int appId, int userId, String reason) {
5135        final long identity = Binder.clearCallingIdentity();
5136        try {
5137            IActivityManager am = ActivityManager.getService();
5138            if (am != null) {
5139                try {
5140                    am.killUid(appId, userId, reason);
5141                } catch (RemoteException e) {
5142                    /* ignore - same process */
5143                }
5144            }
5145        } finally {
5146            Binder.restoreCallingIdentity(identity);
5147        }
5148    }
5149
5150    /**
5151     * Compares two sets of signatures. Returns:
5152     * <br />
5153     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5154     * <br />
5155     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5156     * <br />
5157     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5158     * <br />
5159     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5160     * <br />
5161     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5162     */
5163    static int compareSignatures(Signature[] s1, Signature[] s2) {
5164        if (s1 == null) {
5165            return s2 == null
5166                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5167                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5168        }
5169
5170        if (s2 == null) {
5171            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
5172        }
5173
5174        if (s1.length != s2.length) {
5175            return PackageManager.SIGNATURE_NO_MATCH;
5176        }
5177
5178        // Since both signature sets are of size 1, we can compare without HashSets.
5179        if (s1.length == 1) {
5180            return s1[0].equals(s2[0]) ?
5181                    PackageManager.SIGNATURE_MATCH :
5182                    PackageManager.SIGNATURE_NO_MATCH;
5183        }
5184
5185        ArraySet<Signature> set1 = new ArraySet<Signature>();
5186        for (Signature sig : s1) {
5187            set1.add(sig);
5188        }
5189        ArraySet<Signature> set2 = new ArraySet<Signature>();
5190        for (Signature sig : s2) {
5191            set2.add(sig);
5192        }
5193        // Make sure s2 contains all signatures in s1.
5194        if (set1.equals(set2)) {
5195            return PackageManager.SIGNATURE_MATCH;
5196        }
5197        return PackageManager.SIGNATURE_NO_MATCH;
5198    }
5199
5200    /**
5201     * If the database version for this type of package (internal storage or
5202     * external storage) is less than the version where package signatures
5203     * were updated, return true.
5204     */
5205    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5206        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5207        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5208    }
5209
5210    /**
5211     * Used for backward compatibility to make sure any packages with
5212     * certificate chains get upgraded to the new style. {@code existingSigs}
5213     * will be in the old format (since they were stored on disk from before the
5214     * system upgrade) and {@code scannedSigs} will be in the newer format.
5215     */
5216    private int compareSignaturesCompat(PackageSignatures existingSigs,
5217            PackageParser.Package scannedPkg) {
5218        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
5219            return PackageManager.SIGNATURE_NO_MATCH;
5220        }
5221
5222        ArraySet<Signature> existingSet = new ArraySet<Signature>();
5223        for (Signature sig : existingSigs.mSignatures) {
5224            existingSet.add(sig);
5225        }
5226        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
5227        for (Signature sig : scannedPkg.mSignatures) {
5228            try {
5229                Signature[] chainSignatures = sig.getChainSignatures();
5230                for (Signature chainSig : chainSignatures) {
5231                    scannedCompatSet.add(chainSig);
5232                }
5233            } catch (CertificateEncodingException e) {
5234                scannedCompatSet.add(sig);
5235            }
5236        }
5237        /*
5238         * Make sure the expanded scanned set contains all signatures in the
5239         * existing one.
5240         */
5241        if (scannedCompatSet.equals(existingSet)) {
5242            // Migrate the old signatures to the new scheme.
5243            existingSigs.assignSignatures(scannedPkg.mSignatures);
5244            // The new KeySets will be re-added later in the scanning process.
5245            synchronized (mPackages) {
5246                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
5247            }
5248            return PackageManager.SIGNATURE_MATCH;
5249        }
5250        return PackageManager.SIGNATURE_NO_MATCH;
5251    }
5252
5253    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5254        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5255        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5256    }
5257
5258    private int compareSignaturesRecover(PackageSignatures existingSigs,
5259            PackageParser.Package scannedPkg) {
5260        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
5261            return PackageManager.SIGNATURE_NO_MATCH;
5262        }
5263
5264        String msg = null;
5265        try {
5266            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
5267                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
5268                        + scannedPkg.packageName);
5269                return PackageManager.SIGNATURE_MATCH;
5270            }
5271        } catch (CertificateException e) {
5272            msg = e.getMessage();
5273        }
5274
5275        logCriticalInfo(Log.INFO,
5276                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
5277        return PackageManager.SIGNATURE_NO_MATCH;
5278    }
5279
5280    @Override
5281    public List<String> getAllPackages() {
5282        synchronized (mPackages) {
5283            return new ArrayList<String>(mPackages.keySet());
5284        }
5285    }
5286
5287    @Override
5288    public String[] getPackagesForUid(int uid) {
5289        final int userId = UserHandle.getUserId(uid);
5290        uid = UserHandle.getAppId(uid);
5291        // reader
5292        synchronized (mPackages) {
5293            Object obj = mSettings.getUserIdLPr(uid);
5294            if (obj instanceof SharedUserSetting) {
5295                final SharedUserSetting sus = (SharedUserSetting) obj;
5296                final int N = sus.packages.size();
5297                String[] res = new String[N];
5298                final Iterator<PackageSetting> it = sus.packages.iterator();
5299                int i = 0;
5300                while (it.hasNext()) {
5301                    PackageSetting ps = it.next();
5302                    if (ps.getInstalled(userId)) {
5303                        res[i++] = ps.name;
5304                    } else {
5305                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5306                    }
5307                }
5308                return res;
5309            } else if (obj instanceof PackageSetting) {
5310                final PackageSetting ps = (PackageSetting) obj;
5311                if (ps.getInstalled(userId)) {
5312                    return new String[]{ps.name};
5313                }
5314            }
5315        }
5316        return null;
5317    }
5318
5319    @Override
5320    public String getNameForUid(int uid) {
5321        // reader
5322        synchronized (mPackages) {
5323            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5324            if (obj instanceof SharedUserSetting) {
5325                final SharedUserSetting sus = (SharedUserSetting) obj;
5326                return sus.name + ":" + sus.userId;
5327            } else if (obj instanceof PackageSetting) {
5328                final PackageSetting ps = (PackageSetting) obj;
5329                return ps.name;
5330            }
5331        }
5332        return null;
5333    }
5334
5335    @Override
5336    public int getUidForSharedUser(String sharedUserName) {
5337        if(sharedUserName == null) {
5338            return -1;
5339        }
5340        // reader
5341        synchronized (mPackages) {
5342            SharedUserSetting suid;
5343            try {
5344                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5345                if (suid != null) {
5346                    return suid.userId;
5347                }
5348            } catch (PackageManagerException ignore) {
5349                // can't happen, but, still need to catch it
5350            }
5351            return -1;
5352        }
5353    }
5354
5355    @Override
5356    public int getFlagsForUid(int uid) {
5357        synchronized (mPackages) {
5358            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5359            if (obj instanceof SharedUserSetting) {
5360                final SharedUserSetting sus = (SharedUserSetting) obj;
5361                return sus.pkgFlags;
5362            } else if (obj instanceof PackageSetting) {
5363                final PackageSetting ps = (PackageSetting) obj;
5364                return ps.pkgFlags;
5365            }
5366        }
5367        return 0;
5368    }
5369
5370    @Override
5371    public int getPrivateFlagsForUid(int uid) {
5372        synchronized (mPackages) {
5373            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5374            if (obj instanceof SharedUserSetting) {
5375                final SharedUserSetting sus = (SharedUserSetting) obj;
5376                return sus.pkgPrivateFlags;
5377            } else if (obj instanceof PackageSetting) {
5378                final PackageSetting ps = (PackageSetting) obj;
5379                return ps.pkgPrivateFlags;
5380            }
5381        }
5382        return 0;
5383    }
5384
5385    @Override
5386    public boolean isUidPrivileged(int uid) {
5387        uid = UserHandle.getAppId(uid);
5388        // reader
5389        synchronized (mPackages) {
5390            Object obj = mSettings.getUserIdLPr(uid);
5391            if (obj instanceof SharedUserSetting) {
5392                final SharedUserSetting sus = (SharedUserSetting) obj;
5393                final Iterator<PackageSetting> it = sus.packages.iterator();
5394                while (it.hasNext()) {
5395                    if (it.next().isPrivileged()) {
5396                        return true;
5397                    }
5398                }
5399            } else if (obj instanceof PackageSetting) {
5400                final PackageSetting ps = (PackageSetting) obj;
5401                return ps.isPrivileged();
5402            }
5403        }
5404        return false;
5405    }
5406
5407    @Override
5408    public String[] getAppOpPermissionPackages(String permissionName) {
5409        synchronized (mPackages) {
5410            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
5411            if (pkgs == null) {
5412                return null;
5413            }
5414            return pkgs.toArray(new String[pkgs.size()]);
5415        }
5416    }
5417
5418    @Override
5419    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5420            int flags, int userId) {
5421        try {
5422            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5423
5424            if (!sUserManager.exists(userId)) return null;
5425            flags = updateFlagsForResolve(flags, userId, intent);
5426            enforceCrossUserPermission(Binder.getCallingUid(), userId,
5427                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5428
5429            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5430            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5431                    flags, userId);
5432            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5433
5434            final ResolveInfo bestChoice =
5435                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5436            return bestChoice;
5437        } finally {
5438            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5439        }
5440    }
5441
5442    @Override
5443    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5444        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5445            throw new SecurityException(
5446                    "findPersistentPreferredActivity can only be run by the system");
5447        }
5448        if (!sUserManager.exists(userId)) {
5449            return null;
5450        }
5451        intent = updateIntentForResolve(intent);
5452        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5453        final int flags = updateFlagsForResolve(0, userId, intent);
5454        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5455                userId);
5456        synchronized (mPackages) {
5457            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5458                    userId);
5459        }
5460    }
5461
5462    @Override
5463    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5464            IntentFilter filter, int match, ComponentName activity) {
5465        final int userId = UserHandle.getCallingUserId();
5466        if (DEBUG_PREFERRED) {
5467            Log.v(TAG, "setLastChosenActivity intent=" + intent
5468                + " resolvedType=" + resolvedType
5469                + " flags=" + flags
5470                + " filter=" + filter
5471                + " match=" + match
5472                + " activity=" + activity);
5473            filter.dump(new PrintStreamPrinter(System.out), "    ");
5474        }
5475        intent.setComponent(null);
5476        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5477                userId);
5478        // Find any earlier preferred or last chosen entries and nuke them
5479        findPreferredActivity(intent, resolvedType,
5480                flags, query, 0, false, true, false, userId);
5481        // Add the new activity as the last chosen for this filter
5482        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5483                "Setting last chosen");
5484    }
5485
5486    @Override
5487    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5488        final int userId = UserHandle.getCallingUserId();
5489        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5490        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5491                userId);
5492        return findPreferredActivity(intent, resolvedType, flags, query, 0,
5493                false, false, false, userId);
5494    }
5495
5496    private boolean isEphemeralDisabled() {
5497        // ephemeral apps have been disabled across the board
5498        if (DISABLE_EPHEMERAL_APPS) {
5499            return true;
5500        }
5501        // system isn't up yet; can't read settings, so, assume no ephemeral apps
5502        if (!mSystemReady) {
5503            return true;
5504        }
5505        // we can't get a content resolver until the system is ready; these checks must happen last
5506        final ContentResolver resolver = mContext.getContentResolver();
5507        if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) {
5508            return true;
5509        }
5510        return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0;
5511    }
5512
5513    private boolean isEphemeralAllowed(
5514            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
5515            boolean skipPackageCheck) {
5516        // Short circuit and return early if possible.
5517        if (isEphemeralDisabled()) {
5518            return false;
5519        }
5520        final int callingUser = UserHandle.getCallingUserId();
5521        if (callingUser != UserHandle.USER_SYSTEM) {
5522            return false;
5523        }
5524        if (mEphemeralResolverConnection == null) {
5525            return false;
5526        }
5527        if (mEphemeralInstallerComponent == null) {
5528            return false;
5529        }
5530        if (intent.getComponent() != null) {
5531            return false;
5532        }
5533        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
5534            return false;
5535        }
5536        if (!skipPackageCheck && intent.getPackage() != null) {
5537            return false;
5538        }
5539        final boolean isWebUri = hasWebURI(intent);
5540        if (!isWebUri || intent.getData().getHost() == null) {
5541            return false;
5542        }
5543        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
5544        synchronized (mPackages) {
5545            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
5546            for (int n = 0; n < count; n++) {
5547                ResolveInfo info = resolvedActivities.get(n);
5548                String packageName = info.activityInfo.packageName;
5549                PackageSetting ps = mSettings.mPackages.get(packageName);
5550                if (ps != null) {
5551                    // Try to get the status from User settings first
5552                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5553                    int status = (int) (packedStatus >> 32);
5554                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
5555                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5556                        if (DEBUG_EPHEMERAL) {
5557                            Slog.v(TAG, "DENY ephemeral apps;"
5558                                + " pkg: " + packageName + ", status: " + status);
5559                        }
5560                        return false;
5561                    }
5562                }
5563            }
5564        }
5565        // We've exhausted all ways to deny ephemeral application; let the system look for them.
5566        return true;
5567    }
5568
5569    private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
5570            Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage,
5571            int userId) {
5572        final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO,
5573                new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent,
5574                        callingPackage, userId));
5575        mHandler.sendMessage(msg);
5576    }
5577
5578    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5579            int flags, List<ResolveInfo> query, int userId) {
5580        if (query != null) {
5581            final int N = query.size();
5582            if (N == 1) {
5583                return query.get(0);
5584            } else if (N > 1) {
5585                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5586                // If there is more than one activity with the same priority,
5587                // then let the user decide between them.
5588                ResolveInfo r0 = query.get(0);
5589                ResolveInfo r1 = query.get(1);
5590                if (DEBUG_INTENT_MATCHING || debug) {
5591                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5592                            + r1.activityInfo.name + "=" + r1.priority);
5593                }
5594                // If the first activity has a higher priority, or a different
5595                // default, then it is always desirable to pick it.
5596                if (r0.priority != r1.priority
5597                        || r0.preferredOrder != r1.preferredOrder
5598                        || r0.isDefault != r1.isDefault) {
5599                    return query.get(0);
5600                }
5601                // If we have saved a preference for a preferred activity for
5602                // this Intent, use that.
5603                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5604                        flags, query, r0.priority, true, false, debug, userId);
5605                if (ri != null) {
5606                    return ri;
5607                }
5608                ri = new ResolveInfo(mResolveInfo);
5609                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5610                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5611                // If all of the options come from the same package, show the application's
5612                // label and icon instead of the generic resolver's.
5613                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5614                // and then throw away the ResolveInfo itself, meaning that the caller loses
5615                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5616                // a fallback for this case; we only set the target package's resources on
5617                // the ResolveInfo, not the ActivityInfo.
5618                final String intentPackage = intent.getPackage();
5619                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5620                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5621                    ri.resolvePackageName = intentPackage;
5622                    if (userNeedsBadging(userId)) {
5623                        ri.noResourceId = true;
5624                    } else {
5625                        ri.icon = appi.icon;
5626                    }
5627                    ri.iconResourceId = appi.icon;
5628                    ri.labelRes = appi.labelRes;
5629                }
5630                ri.activityInfo.applicationInfo = new ApplicationInfo(
5631                        ri.activityInfo.applicationInfo);
5632                if (userId != 0) {
5633                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5634                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5635                }
5636                // Make sure that the resolver is displayable in car mode
5637                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5638                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5639                return ri;
5640            }
5641        }
5642        return null;
5643    }
5644
5645    /**
5646     * Return true if the given list is not empty and all of its contents have
5647     * an activityInfo with the given package name.
5648     */
5649    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5650        if (ArrayUtils.isEmpty(list)) {
5651            return false;
5652        }
5653        for (int i = 0, N = list.size(); i < N; i++) {
5654            final ResolveInfo ri = list.get(i);
5655            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5656            if (ai == null || !packageName.equals(ai.packageName)) {
5657                return false;
5658            }
5659        }
5660        return true;
5661    }
5662
5663    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5664            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5665        final int N = query.size();
5666        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5667                .get(userId);
5668        // Get the list of persistent preferred activities that handle the intent
5669        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5670        List<PersistentPreferredActivity> pprefs = ppir != null
5671                ? ppir.queryIntent(intent, resolvedType,
5672                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5673                        (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
5674                        (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId)
5675                : null;
5676        if (pprefs != null && pprefs.size() > 0) {
5677            final int M = pprefs.size();
5678            for (int i=0; i<M; i++) {
5679                final PersistentPreferredActivity ppa = pprefs.get(i);
5680                if (DEBUG_PREFERRED || debug) {
5681                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5682                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5683                            + "\n  component=" + ppa.mComponent);
5684                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5685                }
5686                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5687                        flags | MATCH_DISABLED_COMPONENTS, userId);
5688                if (DEBUG_PREFERRED || debug) {
5689                    Slog.v(TAG, "Found persistent preferred activity:");
5690                    if (ai != null) {
5691                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5692                    } else {
5693                        Slog.v(TAG, "  null");
5694                    }
5695                }
5696                if (ai == null) {
5697                    // This previously registered persistent preferred activity
5698                    // component is no longer known. Ignore it and do NOT remove it.
5699                    continue;
5700                }
5701                for (int j=0; j<N; j++) {
5702                    final ResolveInfo ri = query.get(j);
5703                    if (!ri.activityInfo.applicationInfo.packageName
5704                            .equals(ai.applicationInfo.packageName)) {
5705                        continue;
5706                    }
5707                    if (!ri.activityInfo.name.equals(ai.name)) {
5708                        continue;
5709                    }
5710                    //  Found a persistent preference that can handle the intent.
5711                    if (DEBUG_PREFERRED || debug) {
5712                        Slog.v(TAG, "Returning persistent preferred activity: " +
5713                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5714                    }
5715                    return ri;
5716                }
5717            }
5718        }
5719        return null;
5720    }
5721
5722    // TODO: handle preferred activities missing while user has amnesia
5723    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5724            List<ResolveInfo> query, int priority, boolean always,
5725            boolean removeMatches, boolean debug, int userId) {
5726        if (!sUserManager.exists(userId)) return null;
5727        flags = updateFlagsForResolve(flags, userId, intent);
5728        intent = updateIntentForResolve(intent);
5729        // writer
5730        synchronized (mPackages) {
5731            // Try to find a matching persistent preferred activity.
5732            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5733                    debug, userId);
5734
5735            // If a persistent preferred activity matched, use it.
5736            if (pri != null) {
5737                return pri;
5738            }
5739
5740            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5741            // Get the list of preferred activities that handle the intent
5742            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5743            List<PreferredActivity> prefs = pir != null
5744                    ? pir.queryIntent(intent, resolvedType,
5745                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
5746                            (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
5747                            (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId)
5748                    : null;
5749            if (prefs != null && prefs.size() > 0) {
5750                boolean changed = false;
5751                try {
5752                    // First figure out how good the original match set is.
5753                    // We will only allow preferred activities that came
5754                    // from the same match quality.
5755                    int match = 0;
5756
5757                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5758
5759                    final int N = query.size();
5760                    for (int j=0; j<N; j++) {
5761                        final ResolveInfo ri = query.get(j);
5762                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5763                                + ": 0x" + Integer.toHexString(match));
5764                        if (ri.match > match) {
5765                            match = ri.match;
5766                        }
5767                    }
5768
5769                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5770                            + Integer.toHexString(match));
5771
5772                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5773                    final int M = prefs.size();
5774                    for (int i=0; i<M; i++) {
5775                        final PreferredActivity pa = prefs.get(i);
5776                        if (DEBUG_PREFERRED || debug) {
5777                            Slog.v(TAG, "Checking PreferredActivity ds="
5778                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5779                                    + "\n  component=" + pa.mPref.mComponent);
5780                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5781                        }
5782                        if (pa.mPref.mMatch != match) {
5783                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5784                                    + Integer.toHexString(pa.mPref.mMatch));
5785                            continue;
5786                        }
5787                        // If it's not an "always" type preferred activity and that's what we're
5788                        // looking for, skip it.
5789                        if (always && !pa.mPref.mAlways) {
5790                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5791                            continue;
5792                        }
5793                        final ActivityInfo ai = getActivityInfo(
5794                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5795                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5796                                userId);
5797                        if (DEBUG_PREFERRED || debug) {
5798                            Slog.v(TAG, "Found preferred activity:");
5799                            if (ai != null) {
5800                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5801                            } else {
5802                                Slog.v(TAG, "  null");
5803                            }
5804                        }
5805                        if (ai == null) {
5806                            // This previously registered preferred activity
5807                            // component is no longer known.  Most likely an update
5808                            // to the app was installed and in the new version this
5809                            // component no longer exists.  Clean it up by removing
5810                            // it from the preferred activities list, and skip it.
5811                            Slog.w(TAG, "Removing dangling preferred activity: "
5812                                    + pa.mPref.mComponent);
5813                            pir.removeFilter(pa);
5814                            changed = true;
5815                            continue;
5816                        }
5817                        for (int j=0; j<N; j++) {
5818                            final ResolveInfo ri = query.get(j);
5819                            if (!ri.activityInfo.applicationInfo.packageName
5820                                    .equals(ai.applicationInfo.packageName)) {
5821                                continue;
5822                            }
5823                            if (!ri.activityInfo.name.equals(ai.name)) {
5824                                continue;
5825                            }
5826
5827                            if (removeMatches) {
5828                                pir.removeFilter(pa);
5829                                changed = true;
5830                                if (DEBUG_PREFERRED) {
5831                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5832                                }
5833                                break;
5834                            }
5835
5836                            // Okay we found a previously set preferred or last chosen app.
5837                            // If the result set is different from when this
5838                            // was created, we need to clear it and re-ask the
5839                            // user their preference, if we're looking for an "always" type entry.
5840                            if (always && !pa.mPref.sameSet(query)) {
5841                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5842                                        + intent + " type " + resolvedType);
5843                                if (DEBUG_PREFERRED) {
5844                                    Slog.v(TAG, "Removing preferred activity since set changed "
5845                                            + pa.mPref.mComponent);
5846                                }
5847                                pir.removeFilter(pa);
5848                                // Re-add the filter as a "last chosen" entry (!always)
5849                                PreferredActivity lastChosen = new PreferredActivity(
5850                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5851                                pir.addFilter(lastChosen);
5852                                changed = true;
5853                                return null;
5854                            }
5855
5856                            // Yay! Either the set matched or we're looking for the last chosen
5857                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5858                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5859                            return ri;
5860                        }
5861                    }
5862                } finally {
5863                    if (changed) {
5864                        if (DEBUG_PREFERRED) {
5865                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5866                        }
5867                        scheduleWritePackageRestrictionsLocked(userId);
5868                    }
5869                }
5870            }
5871        }
5872        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5873        return null;
5874    }
5875
5876    /*
5877     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5878     */
5879    @Override
5880    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5881            int targetUserId) {
5882        mContext.enforceCallingOrSelfPermission(
5883                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5884        List<CrossProfileIntentFilter> matches =
5885                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5886        if (matches != null) {
5887            int size = matches.size();
5888            for (int i = 0; i < size; i++) {
5889                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5890            }
5891        }
5892        if (hasWebURI(intent)) {
5893            // cross-profile app linking works only towards the parent.
5894            final UserInfo parent = getProfileParent(sourceUserId);
5895            synchronized(mPackages) {
5896                int flags = updateFlagsForResolve(0, parent.id, intent);
5897                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5898                        intent, resolvedType, flags, sourceUserId, parent.id);
5899                return xpDomainInfo != null;
5900            }
5901        }
5902        return false;
5903    }
5904
5905    private UserInfo getProfileParent(int userId) {
5906        final long identity = Binder.clearCallingIdentity();
5907        try {
5908            return sUserManager.getProfileParent(userId);
5909        } finally {
5910            Binder.restoreCallingIdentity(identity);
5911        }
5912    }
5913
5914    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5915            String resolvedType, int userId) {
5916        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5917        if (resolver != null) {
5918            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/,
5919                    false /*visibleToEphemeral*/, false /*isInstant*/, userId);
5920        }
5921        return null;
5922    }
5923
5924    @Override
5925    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5926            String resolvedType, int flags, int userId) {
5927        try {
5928            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5929
5930            return new ParceledListSlice<>(
5931                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5932        } finally {
5933            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5934        }
5935    }
5936
5937    /**
5938     * Returns the package name of the calling Uid if it's an ephemeral app. If it isn't
5939     * ephemeral, returns {@code null}.
5940     */
5941    private String getEphemeralPackageName(int callingUid) {
5942        final int appId = UserHandle.getAppId(callingUid);
5943        synchronized (mPackages) {
5944            final Object obj = mSettings.getUserIdLPr(appId);
5945            if (obj instanceof PackageSetting) {
5946                final PackageSetting ps = (PackageSetting) obj;
5947                return ps.pkg.applicationInfo.isInstantApp() ? ps.pkg.packageName : null;
5948            }
5949        }
5950        return null;
5951    }
5952
5953    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5954            String resolvedType, int flags, int userId) {
5955        if (!sUserManager.exists(userId)) return Collections.emptyList();
5956        final String ephemeralPkgName = getEphemeralPackageName(Binder.getCallingUid());
5957        flags = updateFlagsForResolve(flags, userId, intent);
5958        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5959                false /* requireFullPermission */, false /* checkShell */,
5960                "query intent activities");
5961        ComponentName comp = intent.getComponent();
5962        if (comp == null) {
5963            if (intent.getSelector() != null) {
5964                intent = intent.getSelector();
5965                comp = intent.getComponent();
5966            }
5967        }
5968
5969        if (comp != null) {
5970            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5971            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5972            if (ai != null) {
5973                // When specifying an explicit component, we prevent the activity from being
5974                // used when either 1) the calling package is normal and the activity is within
5975                // an ephemeral application or 2) the calling package is ephemeral and the
5976                // activity is not visible to ephemeral applications.
5977                boolean matchEphemeral =
5978                        (flags & PackageManager.MATCH_EPHEMERAL) != 0;
5979                boolean ephemeralVisibleOnly =
5980                        (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
5981                boolean blockResolution =
5982                        (!matchEphemeral && ephemeralPkgName == null
5983                                && (ai.applicationInfo.privateFlags
5984                                        & ApplicationInfo.PRIVATE_FLAG_EPHEMERAL) != 0)
5985                        || (ephemeralVisibleOnly && ephemeralPkgName != null
5986                                && (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0);
5987                if (!blockResolution) {
5988                    final ResolveInfo ri = new ResolveInfo();
5989                    ri.activityInfo = ai;
5990                    list.add(ri);
5991                }
5992            }
5993            return list;
5994        }
5995
5996        // reader
5997        boolean sortResult = false;
5998        boolean addEphemeral = false;
5999        List<ResolveInfo> result;
6000        final String pkgName = intent.getPackage();
6001        synchronized (mPackages) {
6002            if (pkgName == null) {
6003                List<CrossProfileIntentFilter> matchingFilters =
6004                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6005                // Check for results that need to skip the current profile.
6006                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6007                        resolvedType, flags, userId);
6008                if (xpResolveInfo != null) {
6009                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6010                    xpResult.add(xpResolveInfo);
6011                    return filterForEphemeral(
6012                            filterIfNotSystemUser(xpResult, userId), ephemeralPkgName);
6013                }
6014
6015                // Check for results in the current profile.
6016                result = filterIfNotSystemUser(mActivities.queryIntent(
6017                        intent, resolvedType, flags, userId), userId);
6018                addEphemeral =
6019                        isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/);
6020
6021                // Check for cross profile results.
6022                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6023                xpResolveInfo = queryCrossProfileIntents(
6024                        matchingFilters, intent, resolvedType, flags, userId,
6025                        hasNonNegativePriorityResult);
6026                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6027                    boolean isVisibleToUser = filterIfNotSystemUser(
6028                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6029                    if (isVisibleToUser) {
6030                        result.add(xpResolveInfo);
6031                        sortResult = true;
6032                    }
6033                }
6034                if (hasWebURI(intent)) {
6035                    CrossProfileDomainInfo xpDomainInfo = null;
6036                    final UserInfo parent = getProfileParent(userId);
6037                    if (parent != null) {
6038                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6039                                flags, userId, parent.id);
6040                    }
6041                    if (xpDomainInfo != null) {
6042                        if (xpResolveInfo != null) {
6043                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6044                            // in the result.
6045                            result.remove(xpResolveInfo);
6046                        }
6047                        if (result.size() == 0 && !addEphemeral) {
6048                            // No result in current profile, but found candidate in parent user.
6049                            // And we are not going to add emphemeral app, so we can return the
6050                            // result straight away.
6051                            result.add(xpDomainInfo.resolveInfo);
6052                            return filterForEphemeral(result, ephemeralPkgName);
6053                        }
6054                    } else if (result.size() <= 1 && !addEphemeral) {
6055                        // No result in parent user and <= 1 result in current profile, and we
6056                        // are not going to add emphemeral app, so we can return the result without
6057                        // further processing.
6058                        return filterForEphemeral(result, ephemeralPkgName);
6059                    }
6060                    // We have more than one candidate (combining results from current and parent
6061                    // profile), so we need filtering and sorting.
6062                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6063                            intent, flags, result, xpDomainInfo, userId);
6064                    sortResult = true;
6065                }
6066            } else {
6067                final PackageParser.Package pkg = mPackages.get(pkgName);
6068                if (pkg != null) {
6069                    result = filterForEphemeral(filterIfNotSystemUser(
6070                            mActivities.queryIntentForPackage(
6071                                    intent, resolvedType, flags, pkg.activities, userId),
6072                            userId), ephemeralPkgName);
6073                } else {
6074                    // the caller wants to resolve for a particular package; however, there
6075                    // were no installed results, so, try to find an ephemeral result
6076                    addEphemeral = isEphemeralAllowed(
6077                            intent, null /*result*/, userId, true /*skipPackageCheck*/);
6078                    result = new ArrayList<ResolveInfo>();
6079                }
6080            }
6081        }
6082        if (addEphemeral) {
6083            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6084            final EphemeralRequest requestObject = new EphemeralRequest(
6085                    null /*responseObj*/, intent /*origIntent*/, resolvedType,
6086                    null /*launchIntent*/, null /*callingPackage*/, userId);
6087            final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne(
6088                    mContext, mEphemeralResolverConnection, requestObject);
6089            if (intentInfo != null) {
6090                if (DEBUG_EPHEMERAL) {
6091                    Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6092                }
6093                final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo);
6094                ephemeralInstaller.ephemeralResponse = intentInfo;
6095                // make sure this resolver is the default
6096                ephemeralInstaller.isDefault = true;
6097                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6098                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6099                // add a non-generic filter
6100                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
6101                ephemeralInstaller.filter.addDataPath(
6102                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6103                result.add(ephemeralInstaller);
6104            }
6105            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6106        }
6107        if (sortResult) {
6108            Collections.sort(result, mResolvePrioritySorter);
6109        }
6110        return filterForEphemeral(result, ephemeralPkgName);
6111    }
6112
6113    private static class CrossProfileDomainInfo {
6114        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6115        ResolveInfo resolveInfo;
6116        /* Best domain verification status of the activities found in the other profile */
6117        int bestDomainVerificationStatus;
6118    }
6119
6120    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6121            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6122        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6123                sourceUserId)) {
6124            return null;
6125        }
6126        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6127                resolvedType, flags, parentUserId);
6128
6129        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6130            return null;
6131        }
6132        CrossProfileDomainInfo result = null;
6133        int size = resultTargetUser.size();
6134        for (int i = 0; i < size; i++) {
6135            ResolveInfo riTargetUser = resultTargetUser.get(i);
6136            // Intent filter verification is only for filters that specify a host. So don't return
6137            // those that handle all web uris.
6138            if (riTargetUser.handleAllWebDataURI) {
6139                continue;
6140            }
6141            String packageName = riTargetUser.activityInfo.packageName;
6142            PackageSetting ps = mSettings.mPackages.get(packageName);
6143            if (ps == null) {
6144                continue;
6145            }
6146            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6147            int status = (int)(verificationState >> 32);
6148            if (result == null) {
6149                result = new CrossProfileDomainInfo();
6150                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6151                        sourceUserId, parentUserId);
6152                result.bestDomainVerificationStatus = status;
6153            } else {
6154                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6155                        result.bestDomainVerificationStatus);
6156            }
6157        }
6158        // Don't consider matches with status NEVER across profiles.
6159        if (result != null && result.bestDomainVerificationStatus
6160                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6161            return null;
6162        }
6163        return result;
6164    }
6165
6166    /**
6167     * Verification statuses are ordered from the worse to the best, except for
6168     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6169     */
6170    private int bestDomainVerificationStatus(int status1, int status2) {
6171        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6172            return status2;
6173        }
6174        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6175            return status1;
6176        }
6177        return (int) MathUtils.max(status1, status2);
6178    }
6179
6180    private boolean isUserEnabled(int userId) {
6181        long callingId = Binder.clearCallingIdentity();
6182        try {
6183            UserInfo userInfo = sUserManager.getUserInfo(userId);
6184            return userInfo != null && userInfo.isEnabled();
6185        } finally {
6186            Binder.restoreCallingIdentity(callingId);
6187        }
6188    }
6189
6190    /**
6191     * Filter out activities with systemUserOnly flag set, when current user is not System.
6192     *
6193     * @return filtered list
6194     */
6195    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6196        if (userId == UserHandle.USER_SYSTEM) {
6197            return resolveInfos;
6198        }
6199        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6200            ResolveInfo info = resolveInfos.get(i);
6201            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6202                resolveInfos.remove(i);
6203            }
6204        }
6205        return resolveInfos;
6206    }
6207
6208    /**
6209     * Filters out ephemeral activities.
6210     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6211     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6212     *
6213     * @param resolveInfos The pre-filtered list of resolved activities
6214     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6215     *          is performed.
6216     * @return A filtered list of resolved activities.
6217     */
6218    private List<ResolveInfo> filterForEphemeral(List<ResolveInfo> resolveInfos,
6219            String ephemeralPkgName) {
6220        if (ephemeralPkgName == null) {
6221            return resolveInfos;
6222        }
6223        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6224            ResolveInfo info = resolveInfos.get(i);
6225            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6226            // allow activities that are defined in the provided package
6227            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
6228                continue;
6229            }
6230            // allow activities that have been explicitly exposed to ephemeral apps
6231            if (!isEphemeralApp
6232                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) {
6233                continue;
6234            }
6235            resolveInfos.remove(i);
6236        }
6237        return resolveInfos;
6238    }
6239
6240    /**
6241     * @param resolveInfos list of resolve infos in descending priority order
6242     * @return if the list contains a resolve info with non-negative priority
6243     */
6244    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6245        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6246    }
6247
6248    private static boolean hasWebURI(Intent intent) {
6249        if (intent.getData() == null) {
6250            return false;
6251        }
6252        final String scheme = intent.getScheme();
6253        if (TextUtils.isEmpty(scheme)) {
6254            return false;
6255        }
6256        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
6257    }
6258
6259    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6260            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6261            int userId) {
6262        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6263
6264        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6265            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6266                    candidates.size());
6267        }
6268
6269        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
6270        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
6271        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
6272        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
6273        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
6274        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
6275
6276        synchronized (mPackages) {
6277            final int count = candidates.size();
6278            // First, try to use linked apps. Partition the candidates into four lists:
6279            // one for the final results, one for the "do not use ever", one for "undefined status"
6280            // and finally one for "browser app type".
6281            for (int n=0; n<count; n++) {
6282                ResolveInfo info = candidates.get(n);
6283                String packageName = info.activityInfo.packageName;
6284                PackageSetting ps = mSettings.mPackages.get(packageName);
6285                if (ps != null) {
6286                    // Add to the special match all list (Browser use case)
6287                    if (info.handleAllWebDataURI) {
6288                        matchAllList.add(info);
6289                        continue;
6290                    }
6291                    // Try to get the status from User settings first
6292                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6293                    int status = (int)(packedStatus >> 32);
6294                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
6295                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
6296                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6297                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
6298                                    + " : linkgen=" + linkGeneration);
6299                        }
6300                        // Use link-enabled generation as preferredOrder, i.e.
6301                        // prefer newly-enabled over earlier-enabled.
6302                        info.preferredOrder = linkGeneration;
6303                        alwaysList.add(info);
6304                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6305                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6306                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
6307                        }
6308                        neverList.add(info);
6309                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6310                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6311                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
6312                        }
6313                        alwaysAskList.add(info);
6314                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
6315                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
6316                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
6317                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
6318                        }
6319                        undefinedList.add(info);
6320                    }
6321                }
6322            }
6323
6324            // We'll want to include browser possibilities in a few cases
6325            boolean includeBrowser = false;
6326
6327            // First try to add the "always" resolution(s) for the current user, if any
6328            if (alwaysList.size() > 0) {
6329                result.addAll(alwaysList);
6330            } else {
6331                // Add all undefined apps as we want them to appear in the disambiguation dialog.
6332                result.addAll(undefinedList);
6333                // Maybe add one for the other profile.
6334                if (xpDomainInfo != null && (
6335                        xpDomainInfo.bestDomainVerificationStatus
6336                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
6337                    result.add(xpDomainInfo.resolveInfo);
6338                }
6339                includeBrowser = true;
6340            }
6341
6342            // The presence of any 'always ask' alternatives means we'll also offer browsers.
6343            // If there were 'always' entries their preferred order has been set, so we also
6344            // back that off to make the alternatives equivalent
6345            if (alwaysAskList.size() > 0) {
6346                for (ResolveInfo i : result) {
6347                    i.preferredOrder = 0;
6348                }
6349                result.addAll(alwaysAskList);
6350                includeBrowser = true;
6351            }
6352
6353            if (includeBrowser) {
6354                // Also add browsers (all of them or only the default one)
6355                if (DEBUG_DOMAIN_VERIFICATION) {
6356                    Slog.v(TAG, "   ...including browsers in candidate set");
6357                }
6358                if ((matchFlags & MATCH_ALL) != 0) {
6359                    result.addAll(matchAllList);
6360                } else {
6361                    // Browser/generic handling case.  If there's a default browser, go straight
6362                    // to that (but only if there is no other higher-priority match).
6363                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
6364                    int maxMatchPrio = 0;
6365                    ResolveInfo defaultBrowserMatch = null;
6366                    final int numCandidates = matchAllList.size();
6367                    for (int n = 0; n < numCandidates; n++) {
6368                        ResolveInfo info = matchAllList.get(n);
6369                        // track the highest overall match priority...
6370                        if (info.priority > maxMatchPrio) {
6371                            maxMatchPrio = info.priority;
6372                        }
6373                        // ...and the highest-priority default browser match
6374                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
6375                            if (defaultBrowserMatch == null
6376                                    || (defaultBrowserMatch.priority < info.priority)) {
6377                                if (debug) {
6378                                    Slog.v(TAG, "Considering default browser match " + info);
6379                                }
6380                                defaultBrowserMatch = info;
6381                            }
6382                        }
6383                    }
6384                    if (defaultBrowserMatch != null
6385                            && defaultBrowserMatch.priority >= maxMatchPrio
6386                            && !TextUtils.isEmpty(defaultBrowserPackageName))
6387                    {
6388                        if (debug) {
6389                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
6390                        }
6391                        result.add(defaultBrowserMatch);
6392                    } else {
6393                        result.addAll(matchAllList);
6394                    }
6395                }
6396
6397                // If there is nothing selected, add all candidates and remove the ones that the user
6398                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
6399                if (result.size() == 0) {
6400                    result.addAll(candidates);
6401                    result.removeAll(neverList);
6402                }
6403            }
6404        }
6405        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6406            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
6407                    result.size());
6408            for (ResolveInfo info : result) {
6409                Slog.v(TAG, "  + " + info.activityInfo);
6410            }
6411        }
6412        return result;
6413    }
6414
6415    // Returns a packed value as a long:
6416    //
6417    // high 'int'-sized word: link status: undefined/ask/never/always.
6418    // low 'int'-sized word: relative priority among 'always' results.
6419    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
6420        long result = ps.getDomainVerificationStatusForUser(userId);
6421        // if none available, get the master status
6422        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
6423            if (ps.getIntentFilterVerificationInfo() != null) {
6424                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
6425            }
6426        }
6427        return result;
6428    }
6429
6430    private ResolveInfo querySkipCurrentProfileIntents(
6431            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6432            int flags, int sourceUserId) {
6433        if (matchingFilters != null) {
6434            int size = matchingFilters.size();
6435            for (int i = 0; i < size; i ++) {
6436                CrossProfileIntentFilter filter = matchingFilters.get(i);
6437                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
6438                    // Checking if there are activities in the target user that can handle the
6439                    // intent.
6440                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6441                            resolvedType, flags, sourceUserId);
6442                    if (resolveInfo != null) {
6443                        return resolveInfo;
6444                    }
6445                }
6446            }
6447        }
6448        return null;
6449    }
6450
6451    // Return matching ResolveInfo in target user if any.
6452    private ResolveInfo queryCrossProfileIntents(
6453            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
6454            int flags, int sourceUserId, boolean matchInCurrentProfile) {
6455        if (matchingFilters != null) {
6456            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
6457            // match the same intent. For performance reasons, it is better not to
6458            // run queryIntent twice for the same userId
6459            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
6460            int size = matchingFilters.size();
6461            for (int i = 0; i < size; i++) {
6462                CrossProfileIntentFilter filter = matchingFilters.get(i);
6463                int targetUserId = filter.getTargetUserId();
6464                boolean skipCurrentProfile =
6465                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
6466                boolean skipCurrentProfileIfNoMatchFound =
6467                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
6468                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
6469                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
6470                    // Checking if there are activities in the target user that can handle the
6471                    // intent.
6472                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
6473                            resolvedType, flags, sourceUserId);
6474                    if (resolveInfo != null) return resolveInfo;
6475                    alreadyTriedUserIds.put(targetUserId, true);
6476                }
6477            }
6478        }
6479        return null;
6480    }
6481
6482    /**
6483     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
6484     * will forward the intent to the filter's target user.
6485     * Otherwise, returns null.
6486     */
6487    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
6488            String resolvedType, int flags, int sourceUserId) {
6489        int targetUserId = filter.getTargetUserId();
6490        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6491                resolvedType, flags, targetUserId);
6492        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
6493            // If all the matches in the target profile are suspended, return null.
6494            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
6495                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
6496                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
6497                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
6498                            targetUserId);
6499                }
6500            }
6501        }
6502        return null;
6503    }
6504
6505    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
6506            int sourceUserId, int targetUserId) {
6507        ResolveInfo forwardingResolveInfo = new ResolveInfo();
6508        long ident = Binder.clearCallingIdentity();
6509        boolean targetIsProfile;
6510        try {
6511            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
6512        } finally {
6513            Binder.restoreCallingIdentity(ident);
6514        }
6515        String className;
6516        if (targetIsProfile) {
6517            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
6518        } else {
6519            className = FORWARD_INTENT_TO_PARENT;
6520        }
6521        ComponentName forwardingActivityComponentName = new ComponentName(
6522                mAndroidApplication.packageName, className);
6523        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
6524                sourceUserId);
6525        if (!targetIsProfile) {
6526            forwardingActivityInfo.showUserIcon = targetUserId;
6527            forwardingResolveInfo.noResourceId = true;
6528        }
6529        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
6530        forwardingResolveInfo.priority = 0;
6531        forwardingResolveInfo.preferredOrder = 0;
6532        forwardingResolveInfo.match = 0;
6533        forwardingResolveInfo.isDefault = true;
6534        forwardingResolveInfo.filter = filter;
6535        forwardingResolveInfo.targetUserId = targetUserId;
6536        return forwardingResolveInfo;
6537    }
6538
6539    @Override
6540    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
6541            Intent[] specifics, String[] specificTypes, Intent intent,
6542            String resolvedType, int flags, int userId) {
6543        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
6544                specificTypes, intent, resolvedType, flags, userId));
6545    }
6546
6547    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
6548            Intent[] specifics, String[] specificTypes, Intent intent,
6549            String resolvedType, int flags, int userId) {
6550        if (!sUserManager.exists(userId)) return Collections.emptyList();
6551        flags = updateFlagsForResolve(flags, userId, intent);
6552        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6553                false /* requireFullPermission */, false /* checkShell */,
6554                "query intent activity options");
6555        final String resultsAction = intent.getAction();
6556
6557        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
6558                | PackageManager.GET_RESOLVED_FILTER, userId);
6559
6560        if (DEBUG_INTENT_MATCHING) {
6561            Log.v(TAG, "Query " + intent + ": " + results);
6562        }
6563
6564        int specificsPos = 0;
6565        int N;
6566
6567        // todo: note that the algorithm used here is O(N^2).  This
6568        // isn't a problem in our current environment, but if we start running
6569        // into situations where we have more than 5 or 10 matches then this
6570        // should probably be changed to something smarter...
6571
6572        // First we go through and resolve each of the specific items
6573        // that were supplied, taking care of removing any corresponding
6574        // duplicate items in the generic resolve list.
6575        if (specifics != null) {
6576            for (int i=0; i<specifics.length; i++) {
6577                final Intent sintent = specifics[i];
6578                if (sintent == null) {
6579                    continue;
6580                }
6581
6582                if (DEBUG_INTENT_MATCHING) {
6583                    Log.v(TAG, "Specific #" + i + ": " + sintent);
6584                }
6585
6586                String action = sintent.getAction();
6587                if (resultsAction != null && resultsAction.equals(action)) {
6588                    // If this action was explicitly requested, then don't
6589                    // remove things that have it.
6590                    action = null;
6591                }
6592
6593                ResolveInfo ri = null;
6594                ActivityInfo ai = null;
6595
6596                ComponentName comp = sintent.getComponent();
6597                if (comp == null) {
6598                    ri = resolveIntent(
6599                        sintent,
6600                        specificTypes != null ? specificTypes[i] : null,
6601                            flags, userId);
6602                    if (ri == null) {
6603                        continue;
6604                    }
6605                    if (ri == mResolveInfo) {
6606                        // ACK!  Must do something better with this.
6607                    }
6608                    ai = ri.activityInfo;
6609                    comp = new ComponentName(ai.applicationInfo.packageName,
6610                            ai.name);
6611                } else {
6612                    ai = getActivityInfo(comp, flags, userId);
6613                    if (ai == null) {
6614                        continue;
6615                    }
6616                }
6617
6618                // Look for any generic query activities that are duplicates
6619                // of this specific one, and remove them from the results.
6620                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
6621                N = results.size();
6622                int j;
6623                for (j=specificsPos; j<N; j++) {
6624                    ResolveInfo sri = results.get(j);
6625                    if ((sri.activityInfo.name.equals(comp.getClassName())
6626                            && sri.activityInfo.applicationInfo.packageName.equals(
6627                                    comp.getPackageName()))
6628                        || (action != null && sri.filter.matchAction(action))) {
6629                        results.remove(j);
6630                        if (DEBUG_INTENT_MATCHING) Log.v(
6631                            TAG, "Removing duplicate item from " + j
6632                            + " due to specific " + specificsPos);
6633                        if (ri == null) {
6634                            ri = sri;
6635                        }
6636                        j--;
6637                        N--;
6638                    }
6639                }
6640
6641                // Add this specific item to its proper place.
6642                if (ri == null) {
6643                    ri = new ResolveInfo();
6644                    ri.activityInfo = ai;
6645                }
6646                results.add(specificsPos, ri);
6647                ri.specificIndex = i;
6648                specificsPos++;
6649            }
6650        }
6651
6652        // Now we go through the remaining generic results and remove any
6653        // duplicate actions that are found here.
6654        N = results.size();
6655        for (int i=specificsPos; i<N-1; i++) {
6656            final ResolveInfo rii = results.get(i);
6657            if (rii.filter == null) {
6658                continue;
6659            }
6660
6661            // Iterate over all of the actions of this result's intent
6662            // filter...  typically this should be just one.
6663            final Iterator<String> it = rii.filter.actionsIterator();
6664            if (it == null) {
6665                continue;
6666            }
6667            while (it.hasNext()) {
6668                final String action = it.next();
6669                if (resultsAction != null && resultsAction.equals(action)) {
6670                    // If this action was explicitly requested, then don't
6671                    // remove things that have it.
6672                    continue;
6673                }
6674                for (int j=i+1; j<N; j++) {
6675                    final ResolveInfo rij = results.get(j);
6676                    if (rij.filter != null && rij.filter.hasAction(action)) {
6677                        results.remove(j);
6678                        if (DEBUG_INTENT_MATCHING) Log.v(
6679                            TAG, "Removing duplicate item from " + j
6680                            + " due to action " + action + " at " + i);
6681                        j--;
6682                        N--;
6683                    }
6684                }
6685            }
6686
6687            // If the caller didn't request filter information, drop it now
6688            // so we don't have to marshall/unmarshall it.
6689            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6690                rii.filter = null;
6691            }
6692        }
6693
6694        // Filter out the caller activity if so requested.
6695        if (caller != null) {
6696            N = results.size();
6697            for (int i=0; i<N; i++) {
6698                ActivityInfo ainfo = results.get(i).activityInfo;
6699                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6700                        && caller.getClassName().equals(ainfo.name)) {
6701                    results.remove(i);
6702                    break;
6703                }
6704            }
6705        }
6706
6707        // If the caller didn't request filter information,
6708        // drop them now so we don't have to
6709        // marshall/unmarshall it.
6710        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6711            N = results.size();
6712            for (int i=0; i<N; i++) {
6713                results.get(i).filter = null;
6714            }
6715        }
6716
6717        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6718        return results;
6719    }
6720
6721    @Override
6722    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6723            String resolvedType, int flags, int userId) {
6724        return new ParceledListSlice<>(
6725                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6726    }
6727
6728    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6729            String resolvedType, int flags, int userId) {
6730        if (!sUserManager.exists(userId)) return Collections.emptyList();
6731        flags = updateFlagsForResolve(flags, userId, intent);
6732        ComponentName comp = intent.getComponent();
6733        if (comp == null) {
6734            if (intent.getSelector() != null) {
6735                intent = intent.getSelector();
6736                comp = intent.getComponent();
6737            }
6738        }
6739        if (comp != null) {
6740            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6741            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6742            if (ai != null) {
6743                ResolveInfo ri = new ResolveInfo();
6744                ri.activityInfo = ai;
6745                list.add(ri);
6746            }
6747            return list;
6748        }
6749
6750        // reader
6751        synchronized (mPackages) {
6752            String pkgName = intent.getPackage();
6753            if (pkgName == null) {
6754                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6755            }
6756            final PackageParser.Package pkg = mPackages.get(pkgName);
6757            if (pkg != null) {
6758                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6759                        userId);
6760            }
6761            return Collections.emptyList();
6762        }
6763    }
6764
6765    @Override
6766    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6767        if (!sUserManager.exists(userId)) return null;
6768        flags = updateFlagsForResolve(flags, userId, intent);
6769        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6770        if (query != null) {
6771            if (query.size() >= 1) {
6772                // If there is more than one service with the same priority,
6773                // just arbitrarily pick the first one.
6774                return query.get(0);
6775            }
6776        }
6777        return null;
6778    }
6779
6780    @Override
6781    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6782            String resolvedType, int flags, int userId) {
6783        return new ParceledListSlice<>(
6784                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6785    }
6786
6787    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6788            String resolvedType, int flags, int userId) {
6789        if (!sUserManager.exists(userId)) return Collections.emptyList();
6790        flags = updateFlagsForResolve(flags, userId, intent);
6791        ComponentName comp = intent.getComponent();
6792        if (comp == null) {
6793            if (intent.getSelector() != null) {
6794                intent = intent.getSelector();
6795                comp = intent.getComponent();
6796            }
6797        }
6798        if (comp != null) {
6799            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6800            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6801            if (si != null) {
6802                final ResolveInfo ri = new ResolveInfo();
6803                ri.serviceInfo = si;
6804                list.add(ri);
6805            }
6806            return list;
6807        }
6808
6809        // reader
6810        synchronized (mPackages) {
6811            String pkgName = intent.getPackage();
6812            if (pkgName == null) {
6813                return mServices.queryIntent(intent, resolvedType, flags, userId);
6814            }
6815            final PackageParser.Package pkg = mPackages.get(pkgName);
6816            if (pkg != null) {
6817                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6818                        userId);
6819            }
6820            return Collections.emptyList();
6821        }
6822    }
6823
6824    @Override
6825    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6826            String resolvedType, int flags, int userId) {
6827        return new ParceledListSlice<>(
6828                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6829    }
6830
6831    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6832            Intent intent, String resolvedType, int flags, int userId) {
6833        if (!sUserManager.exists(userId)) return Collections.emptyList();
6834        flags = updateFlagsForResolve(flags, userId, intent);
6835        ComponentName comp = intent.getComponent();
6836        if (comp == null) {
6837            if (intent.getSelector() != null) {
6838                intent = intent.getSelector();
6839                comp = intent.getComponent();
6840            }
6841        }
6842        if (comp != null) {
6843            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6844            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6845            if (pi != null) {
6846                final ResolveInfo ri = new ResolveInfo();
6847                ri.providerInfo = pi;
6848                list.add(ri);
6849            }
6850            return list;
6851        }
6852
6853        // reader
6854        synchronized (mPackages) {
6855            String pkgName = intent.getPackage();
6856            if (pkgName == null) {
6857                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6858            }
6859            final PackageParser.Package pkg = mPackages.get(pkgName);
6860            if (pkg != null) {
6861                return mProviders.queryIntentForPackage(
6862                        intent, resolvedType, flags, pkg.providers, userId);
6863            }
6864            return Collections.emptyList();
6865        }
6866    }
6867
6868    @Override
6869    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6870        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6871        flags = updateFlagsForPackage(flags, userId, null);
6872        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6873        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6874                true /* requireFullPermission */, false /* checkShell */,
6875                "get installed packages");
6876
6877        // writer
6878        synchronized (mPackages) {
6879            ArrayList<PackageInfo> list;
6880            if (listUninstalled) {
6881                list = new ArrayList<>(mSettings.mPackages.size());
6882                for (PackageSetting ps : mSettings.mPackages.values()) {
6883                    if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
6884                        continue;
6885                    }
6886                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
6887                    if (pi != null) {
6888                        list.add(pi);
6889                    }
6890                }
6891            } else {
6892                list = new ArrayList<>(mPackages.size());
6893                for (PackageParser.Package p : mPackages.values()) {
6894                    if (filterSharedLibPackageLPr((PackageSetting) p.mExtras,
6895                            Binder.getCallingUid(), userId)) {
6896                        continue;
6897                    }
6898                    final PackageInfo pi = generatePackageInfo((PackageSetting)
6899                            p.mExtras, flags, userId);
6900                    if (pi != null) {
6901                        list.add(pi);
6902                    }
6903                }
6904            }
6905
6906            return new ParceledListSlice<>(list);
6907        }
6908    }
6909
6910    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6911            String[] permissions, boolean[] tmp, int flags, int userId) {
6912        int numMatch = 0;
6913        final PermissionsState permissionsState = ps.getPermissionsState();
6914        for (int i=0; i<permissions.length; i++) {
6915            final String permission = permissions[i];
6916            if (permissionsState.hasPermission(permission, userId)) {
6917                tmp[i] = true;
6918                numMatch++;
6919            } else {
6920                tmp[i] = false;
6921            }
6922        }
6923        if (numMatch == 0) {
6924            return;
6925        }
6926        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
6927
6928        // The above might return null in cases of uninstalled apps or install-state
6929        // skew across users/profiles.
6930        if (pi != null) {
6931            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6932                if (numMatch == permissions.length) {
6933                    pi.requestedPermissions = permissions;
6934                } else {
6935                    pi.requestedPermissions = new String[numMatch];
6936                    numMatch = 0;
6937                    for (int i=0; i<permissions.length; i++) {
6938                        if (tmp[i]) {
6939                            pi.requestedPermissions[numMatch] = permissions[i];
6940                            numMatch++;
6941                        }
6942                    }
6943                }
6944            }
6945            list.add(pi);
6946        }
6947    }
6948
6949    @Override
6950    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6951            String[] permissions, int flags, int userId) {
6952        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6953        flags = updateFlagsForPackage(flags, userId, permissions);
6954        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6955                true /* requireFullPermission */, false /* checkShell */,
6956                "get packages holding permissions");
6957        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6958
6959        // writer
6960        synchronized (mPackages) {
6961            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6962            boolean[] tmpBools = new boolean[permissions.length];
6963            if (listUninstalled) {
6964                for (PackageSetting ps : mSettings.mPackages.values()) {
6965                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6966                            userId);
6967                }
6968            } else {
6969                for (PackageParser.Package pkg : mPackages.values()) {
6970                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6971                    if (ps != null) {
6972                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6973                                userId);
6974                    }
6975                }
6976            }
6977
6978            return new ParceledListSlice<PackageInfo>(list);
6979        }
6980    }
6981
6982    @Override
6983    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6984        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6985        flags = updateFlagsForApplication(flags, userId, null);
6986        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
6987
6988        // writer
6989        synchronized (mPackages) {
6990            ArrayList<ApplicationInfo> list;
6991            if (listUninstalled) {
6992                list = new ArrayList<>(mSettings.mPackages.size());
6993                for (PackageSetting ps : mSettings.mPackages.values()) {
6994                    ApplicationInfo ai;
6995                    int effectiveFlags = flags;
6996                    if (ps.isSystem()) {
6997                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
6998                    }
6999                    if (ps.pkg != null) {
7000                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7001                            continue;
7002                        }
7003                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7004                                ps.readUserState(userId), userId);
7005                        if (ai != null) {
7006                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7007                        }
7008                    } else {
7009                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7010                        // and already converts to externally visible package name
7011                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7012                                Binder.getCallingUid(), effectiveFlags, userId);
7013                    }
7014                    if (ai != null) {
7015                        list.add(ai);
7016                    }
7017                }
7018            } else {
7019                list = new ArrayList<>(mPackages.size());
7020                for (PackageParser.Package p : mPackages.values()) {
7021                    if (p.mExtras != null) {
7022                        PackageSetting ps = (PackageSetting) p.mExtras;
7023                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) {
7024                            continue;
7025                        }
7026                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7027                                ps.readUserState(userId), userId);
7028                        if (ai != null) {
7029                            ai.packageName = resolveExternalPackageNameLPr(p);
7030                            list.add(ai);
7031                        }
7032                    }
7033                }
7034            }
7035
7036            return new ParceledListSlice<>(list);
7037        }
7038    }
7039
7040    @Override
7041    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
7042        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7043            return null;
7044        }
7045
7046        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7047                "getEphemeralApplications");
7048        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7049                true /* requireFullPermission */, false /* checkShell */,
7050                "getEphemeralApplications");
7051        synchronized (mPackages) {
7052            List<InstantAppInfo> instantApps = mInstantAppRegistry
7053                    .getInstantAppsLPr(userId);
7054            if (instantApps != null) {
7055                return new ParceledListSlice<>(instantApps);
7056            }
7057        }
7058        return null;
7059    }
7060
7061    @Override
7062    public boolean isInstantApp(String packageName, int userId) {
7063        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7064                true /* requireFullPermission */, false /* checkShell */,
7065                "isInstantApp");
7066        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7067            return false;
7068        }
7069
7070        if (!isCallerSameApp(packageName)) {
7071            return false;
7072        }
7073        synchronized (mPackages) {
7074            PackageParser.Package pkg = mPackages.get(packageName);
7075            if (pkg != null) {
7076                return pkg.applicationInfo.isInstantApp();
7077            }
7078        }
7079        return false;
7080    }
7081
7082    @Override
7083    public byte[] getInstantAppCookie(String packageName, int userId) {
7084        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7085            return null;
7086        }
7087
7088        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7089                true /* requireFullPermission */, false /* checkShell */,
7090                "getInstantAppCookie");
7091        if (!isCallerSameApp(packageName)) {
7092            return null;
7093        }
7094        synchronized (mPackages) {
7095            return mInstantAppRegistry.getInstantAppCookieLPw(
7096                    packageName, userId);
7097        }
7098    }
7099
7100    @Override
7101    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
7102        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7103            return true;
7104        }
7105
7106        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7107                true /* requireFullPermission */, true /* checkShell */,
7108                "setInstantAppCookie");
7109        if (!isCallerSameApp(packageName)) {
7110            return false;
7111        }
7112        synchronized (mPackages) {
7113            return mInstantAppRegistry.setInstantAppCookieLPw(
7114                    packageName, cookie, userId);
7115        }
7116    }
7117
7118    @Override
7119    public Bitmap getInstantAppIcon(String packageName, int userId) {
7120        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
7121            return null;
7122        }
7123
7124        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
7125                "getInstantAppIcon");
7126
7127        enforceCrossUserPermission(Binder.getCallingUid(), userId,
7128                true /* requireFullPermission */, false /* checkShell */,
7129                "getInstantAppIcon");
7130
7131        synchronized (mPackages) {
7132            return mInstantAppRegistry.getInstantAppIconLPw(
7133                    packageName, userId);
7134        }
7135    }
7136
7137    private boolean isCallerSameApp(String packageName) {
7138        PackageParser.Package pkg = mPackages.get(packageName);
7139        return pkg != null
7140                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
7141    }
7142
7143    @Override
7144    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
7145        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
7146    }
7147
7148    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
7149        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
7150
7151        // reader
7152        synchronized (mPackages) {
7153            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
7154            final int userId = UserHandle.getCallingUserId();
7155            while (i.hasNext()) {
7156                final PackageParser.Package p = i.next();
7157                if (p.applicationInfo == null) continue;
7158
7159                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
7160                        && !p.applicationInfo.isDirectBootAware();
7161                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
7162                        && p.applicationInfo.isDirectBootAware();
7163
7164                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
7165                        && (!mSafeMode || isSystemApp(p))
7166                        && (matchesUnaware || matchesAware)) {
7167                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
7168                    if (ps != null) {
7169                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7170                                ps.readUserState(userId), userId);
7171                        if (ai != null) {
7172                            finalList.add(ai);
7173                        }
7174                    }
7175                }
7176            }
7177        }
7178
7179        return finalList;
7180    }
7181
7182    @Override
7183    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
7184        if (!sUserManager.exists(userId)) return null;
7185        flags = updateFlagsForComponent(flags, userId, name);
7186        // reader
7187        synchronized (mPackages) {
7188            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
7189            PackageSetting ps = provider != null
7190                    ? mSettings.mPackages.get(provider.owner.packageName)
7191                    : null;
7192            return ps != null
7193                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
7194                    ? PackageParser.generateProviderInfo(provider, flags,
7195                            ps.readUserState(userId), userId)
7196                    : null;
7197        }
7198    }
7199
7200    /**
7201     * @deprecated
7202     */
7203    @Deprecated
7204    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
7205        // reader
7206        synchronized (mPackages) {
7207            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
7208                    .entrySet().iterator();
7209            final int userId = UserHandle.getCallingUserId();
7210            while (i.hasNext()) {
7211                Map.Entry<String, PackageParser.Provider> entry = i.next();
7212                PackageParser.Provider p = entry.getValue();
7213                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7214
7215                if (ps != null && p.syncable
7216                        && (!mSafeMode || (p.info.applicationInfo.flags
7217                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
7218                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
7219                            ps.readUserState(userId), userId);
7220                    if (info != null) {
7221                        outNames.add(entry.getKey());
7222                        outInfo.add(info);
7223                    }
7224                }
7225            }
7226        }
7227    }
7228
7229    @Override
7230    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
7231            int uid, int flags) {
7232        final int userId = processName != null ? UserHandle.getUserId(uid)
7233                : UserHandle.getCallingUserId();
7234        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7235        flags = updateFlagsForComponent(flags, userId, processName);
7236
7237        ArrayList<ProviderInfo> finalList = null;
7238        // reader
7239        synchronized (mPackages) {
7240            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
7241            while (i.hasNext()) {
7242                final PackageParser.Provider p = i.next();
7243                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
7244                if (ps != null && p.info.authority != null
7245                        && (processName == null
7246                                || (p.info.processName.equals(processName)
7247                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
7248                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
7249                    if (finalList == null) {
7250                        finalList = new ArrayList<ProviderInfo>(3);
7251                    }
7252                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
7253                            ps.readUserState(userId), userId);
7254                    if (info != null) {
7255                        finalList.add(info);
7256                    }
7257                }
7258            }
7259        }
7260
7261        if (finalList != null) {
7262            Collections.sort(finalList, mProviderInitOrderSorter);
7263            return new ParceledListSlice<ProviderInfo>(finalList);
7264        }
7265
7266        return ParceledListSlice.emptyList();
7267    }
7268
7269    @Override
7270    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
7271        // reader
7272        synchronized (mPackages) {
7273            final PackageParser.Instrumentation i = mInstrumentation.get(name);
7274            return PackageParser.generateInstrumentationInfo(i, flags);
7275        }
7276    }
7277
7278    @Override
7279    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
7280            String targetPackage, int flags) {
7281        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
7282    }
7283
7284    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
7285            int flags) {
7286        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
7287
7288        // reader
7289        synchronized (mPackages) {
7290            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
7291            while (i.hasNext()) {
7292                final PackageParser.Instrumentation p = i.next();
7293                if (targetPackage == null
7294                        || targetPackage.equals(p.info.targetPackage)) {
7295                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
7296                            flags);
7297                    if (ii != null) {
7298                        finalList.add(ii);
7299                    }
7300                }
7301            }
7302        }
7303
7304        return finalList;
7305    }
7306
7307    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
7308        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
7309        if (overlays == null) {
7310            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
7311            return;
7312        }
7313        for (PackageParser.Package opkg : overlays.values()) {
7314            // Not much to do if idmap fails: we already logged the error
7315            // and we certainly don't want to abort installation of pkg simply
7316            // because an overlay didn't fit properly. For these reasons,
7317            // ignore the return value of createIdmapForPackagePairLI.
7318            createIdmapForPackagePairLI(pkg, opkg);
7319        }
7320    }
7321
7322    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
7323            PackageParser.Package opkg) {
7324        if (!opkg.mTrustedOverlay) {
7325            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
7326                    opkg.baseCodePath + ": overlay not trusted");
7327            return false;
7328        }
7329        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
7330        if (overlaySet == null) {
7331            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
7332                    opkg.baseCodePath + " but target package has no known overlays");
7333            return false;
7334        }
7335        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7336        // TODO: generate idmap for split APKs
7337        try {
7338            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
7339        } catch (InstallerException e) {
7340            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
7341                    + opkg.baseCodePath);
7342            return false;
7343        }
7344        PackageParser.Package[] overlayArray =
7345            overlaySet.values().toArray(new PackageParser.Package[0]);
7346        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
7347            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
7348                return p1.mOverlayPriority - p2.mOverlayPriority;
7349            }
7350        };
7351        Arrays.sort(overlayArray, cmp);
7352
7353        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
7354        int i = 0;
7355        for (PackageParser.Package p : overlayArray) {
7356            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
7357        }
7358        return true;
7359    }
7360
7361    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
7362        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
7363        try {
7364            scanDirLI(dir, parseFlags, scanFlags, currentTime);
7365        } finally {
7366            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7367        }
7368    }
7369
7370    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
7371        final File[] files = dir.listFiles();
7372        if (ArrayUtils.isEmpty(files)) {
7373            Log.d(TAG, "No files in app dir " + dir);
7374            return;
7375        }
7376
7377        if (DEBUG_PACKAGE_SCANNING) {
7378            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
7379                    + " flags=0x" + Integer.toHexString(parseFlags));
7380        }
7381        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
7382                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir);
7383
7384        // Submit files for parsing in parallel
7385        int fileCount = 0;
7386        for (File file : files) {
7387            final boolean isPackage = (isApkFile(file) || file.isDirectory())
7388                    && !PackageInstallerService.isStageName(file.getName());
7389            if (!isPackage) {
7390                // Ignore entries which are not packages
7391                continue;
7392            }
7393            parallelPackageParser.submit(file, parseFlags);
7394            fileCount++;
7395        }
7396
7397        // Process results one by one
7398        for (; fileCount > 0; fileCount--) {
7399            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
7400            Throwable throwable = parseResult.throwable;
7401            int errorCode = PackageManager.INSTALL_SUCCEEDED;
7402
7403            if (throwable == null) {
7404                // Static shared libraries have synthetic package names
7405                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
7406                    renameStaticSharedLibraryPackage(parseResult.pkg);
7407                }
7408                try {
7409                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
7410                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
7411                                currentTime, null);
7412                    }
7413                } catch (PackageManagerException e) {
7414                    errorCode = e.error;
7415                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
7416                }
7417            } else if (throwable instanceof PackageParser.PackageParserException) {
7418                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
7419                        throwable;
7420                errorCode = e.error;
7421                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
7422            } else {
7423                throw new IllegalStateException("Unexpected exception occurred while parsing "
7424                        + parseResult.scanFile, throwable);
7425            }
7426
7427            // Delete invalid userdata apps
7428            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
7429                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
7430                logCriticalInfo(Log.WARN,
7431                        "Deleting invalid package at " + parseResult.scanFile);
7432                removeCodePathLI(parseResult.scanFile);
7433            }
7434        }
7435        parallelPackageParser.close();
7436    }
7437
7438    private static File getSettingsProblemFile() {
7439        File dataDir = Environment.getDataDirectory();
7440        File systemDir = new File(dataDir, "system");
7441        File fname = new File(systemDir, "uiderrors.txt");
7442        return fname;
7443    }
7444
7445    static void reportSettingsProblem(int priority, String msg) {
7446        logCriticalInfo(priority, msg);
7447    }
7448
7449    static void logCriticalInfo(int priority, String msg) {
7450        Slog.println(priority, TAG, msg);
7451        EventLogTags.writePmCriticalInfo(msg);
7452        try {
7453            File fname = getSettingsProblemFile();
7454            FileOutputStream out = new FileOutputStream(fname, true);
7455            PrintWriter pw = new FastPrintWriter(out);
7456            SimpleDateFormat formatter = new SimpleDateFormat();
7457            String dateString = formatter.format(new Date(System.currentTimeMillis()));
7458            pw.println(dateString + ": " + msg);
7459            pw.close();
7460            FileUtils.setPermissions(
7461                    fname.toString(),
7462                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
7463                    -1, -1);
7464        } catch (java.io.IOException e) {
7465        }
7466    }
7467
7468    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
7469        if (srcFile.isDirectory()) {
7470            final File baseFile = new File(pkg.baseCodePath);
7471            long maxModifiedTime = baseFile.lastModified();
7472            if (pkg.splitCodePaths != null) {
7473                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
7474                    final File splitFile = new File(pkg.splitCodePaths[i]);
7475                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
7476                }
7477            }
7478            return maxModifiedTime;
7479        }
7480        return srcFile.lastModified();
7481    }
7482
7483    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
7484            final int policyFlags) throws PackageManagerException {
7485        // When upgrading from pre-N MR1, verify the package time stamp using the package
7486        // directory and not the APK file.
7487        final long lastModifiedTime = mIsPreNMR1Upgrade
7488                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
7489        if (ps != null
7490                && ps.codePath.equals(srcFile)
7491                && ps.timeStamp == lastModifiedTime
7492                && !isCompatSignatureUpdateNeeded(pkg)
7493                && !isRecoverSignatureUpdateNeeded(pkg)) {
7494            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
7495            KeySetManagerService ksms = mSettings.mKeySetManagerService;
7496            ArraySet<PublicKey> signingKs;
7497            synchronized (mPackages) {
7498                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
7499            }
7500            if (ps.signatures.mSignatures != null
7501                    && ps.signatures.mSignatures.length != 0
7502                    && signingKs != null) {
7503                // Optimization: reuse the existing cached certificates
7504                // if the package appears to be unchanged.
7505                pkg.mSignatures = ps.signatures.mSignatures;
7506                pkg.mSigningKeys = signingKs;
7507                return;
7508            }
7509
7510            Slog.w(TAG, "PackageSetting for " + ps.name
7511                    + " is missing signatures.  Collecting certs again to recover them.");
7512        } else {
7513            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
7514        }
7515
7516        try {
7517            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
7518            PackageParser.collectCertificates(pkg, policyFlags);
7519        } catch (PackageParserException e) {
7520            throw PackageManagerException.from(e);
7521        } finally {
7522            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7523        }
7524    }
7525
7526    /**
7527     *  Traces a package scan.
7528     *  @see #scanPackageLI(File, int, int, long, UserHandle)
7529     */
7530    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
7531            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7532        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
7533        try {
7534            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
7535        } finally {
7536            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7537        }
7538    }
7539
7540    /**
7541     *  Scans a package and returns the newly parsed package.
7542     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
7543     */
7544    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
7545            long currentTime, UserHandle user) throws PackageManagerException {
7546        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
7547        PackageParser pp = new PackageParser();
7548        pp.setSeparateProcesses(mSeparateProcesses);
7549        pp.setOnlyCoreApps(mOnlyCore);
7550        pp.setDisplayMetrics(mMetrics);
7551
7552        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
7553            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
7554        }
7555
7556        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
7557        final PackageParser.Package pkg;
7558        try {
7559            pkg = pp.parsePackage(scanFile, parseFlags);
7560        } catch (PackageParserException e) {
7561            throw PackageManagerException.from(e);
7562        } finally {
7563            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7564        }
7565
7566        // Static shared libraries have synthetic package names
7567        if (pkg.applicationInfo.isStaticSharedLibrary()) {
7568            renameStaticSharedLibraryPackage(pkg);
7569        }
7570
7571        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
7572    }
7573
7574    /**
7575     *  Scans a package and returns the newly parsed package.
7576     *  @throws PackageManagerException on a parse error.
7577     */
7578    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
7579            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7580            throws PackageManagerException {
7581        // If the package has children and this is the first dive in the function
7582        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
7583        // packages (parent and children) would be successfully scanned before the
7584        // actual scan since scanning mutates internal state and we want to atomically
7585        // install the package and its children.
7586        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7587            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7588                scanFlags |= SCAN_CHECK_ONLY;
7589            }
7590        } else {
7591            scanFlags &= ~SCAN_CHECK_ONLY;
7592        }
7593
7594        // Scan the parent
7595        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
7596                scanFlags, currentTime, user);
7597
7598        // Scan the children
7599        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7600        for (int i = 0; i < childCount; i++) {
7601            PackageParser.Package childPackage = pkg.childPackages.get(i);
7602            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
7603                    currentTime, user);
7604        }
7605
7606
7607        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7608            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
7609        }
7610
7611        return scannedPkg;
7612    }
7613
7614    /**
7615     *  Scans a package and returns the newly parsed package.
7616     *  @throws PackageManagerException on a parse error.
7617     */
7618    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
7619            int policyFlags, int scanFlags, long currentTime, UserHandle user)
7620            throws PackageManagerException {
7621        PackageSetting ps = null;
7622        PackageSetting updatedPkg;
7623        // reader
7624        synchronized (mPackages) {
7625            // Look to see if we already know about this package.
7626            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
7627            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
7628                // This package has been renamed to its original name.  Let's
7629                // use that.
7630                ps = mSettings.getPackageLPr(oldName);
7631            }
7632            // If there was no original package, see one for the real package name.
7633            if (ps == null) {
7634                ps = mSettings.getPackageLPr(pkg.packageName);
7635            }
7636            // Check to see if this package could be hiding/updating a system
7637            // package.  Must look for it either under the original or real
7638            // package name depending on our state.
7639            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
7640            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
7641
7642            // If this is a package we don't know about on the system partition, we
7643            // may need to remove disabled child packages on the system partition
7644            // or may need to not add child packages if the parent apk is updated
7645            // on the data partition and no longer defines this child package.
7646            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7647                // If this is a parent package for an updated system app and this system
7648                // app got an OTA update which no longer defines some of the child packages
7649                // we have to prune them from the disabled system packages.
7650                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
7651                if (disabledPs != null) {
7652                    final int scannedChildCount = (pkg.childPackages != null)
7653                            ? pkg.childPackages.size() : 0;
7654                    final int disabledChildCount = disabledPs.childPackageNames != null
7655                            ? disabledPs.childPackageNames.size() : 0;
7656                    for (int i = 0; i < disabledChildCount; i++) {
7657                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
7658                        boolean disabledPackageAvailable = false;
7659                        for (int j = 0; j < scannedChildCount; j++) {
7660                            PackageParser.Package childPkg = pkg.childPackages.get(j);
7661                            if (childPkg.packageName.equals(disabledChildPackageName)) {
7662                                disabledPackageAvailable = true;
7663                                break;
7664                            }
7665                         }
7666                         if (!disabledPackageAvailable) {
7667                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
7668                         }
7669                    }
7670                }
7671            }
7672        }
7673
7674        boolean updatedPkgBetter = false;
7675        // First check if this is a system package that may involve an update
7676        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
7677            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
7678            // it needs to drop FLAG_PRIVILEGED.
7679            if (locationIsPrivileged(scanFile)) {
7680                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7681            } else {
7682                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7683            }
7684
7685            if (ps != null && !ps.codePath.equals(scanFile)) {
7686                // The path has changed from what was last scanned...  check the
7687                // version of the new path against what we have stored to determine
7688                // what to do.
7689                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
7690                if (pkg.mVersionCode <= ps.versionCode) {
7691                    // The system package has been updated and the code path does not match
7692                    // Ignore entry. Skip it.
7693                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
7694                            + " ignored: updated version " + ps.versionCode
7695                            + " better than this " + pkg.mVersionCode);
7696                    if (!updatedPkg.codePath.equals(scanFile)) {
7697                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
7698                                + ps.name + " changing from " + updatedPkg.codePathString
7699                                + " to " + scanFile);
7700                        updatedPkg.codePath = scanFile;
7701                        updatedPkg.codePathString = scanFile.toString();
7702                        updatedPkg.resourcePath = scanFile;
7703                        updatedPkg.resourcePathString = scanFile.toString();
7704                    }
7705                    updatedPkg.pkg = pkg;
7706                    updatedPkg.versionCode = pkg.mVersionCode;
7707
7708                    // Update the disabled system child packages to point to the package too.
7709                    final int childCount = updatedPkg.childPackageNames != null
7710                            ? updatedPkg.childPackageNames.size() : 0;
7711                    for (int i = 0; i < childCount; i++) {
7712                        String childPackageName = updatedPkg.childPackageNames.get(i);
7713                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
7714                                childPackageName);
7715                        if (updatedChildPkg != null) {
7716                            updatedChildPkg.pkg = pkg;
7717                            updatedChildPkg.versionCode = pkg.mVersionCode;
7718                        }
7719                    }
7720
7721                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
7722                            + scanFile + " ignored: updated version " + ps.versionCode
7723                            + " better than this " + pkg.mVersionCode);
7724                } else {
7725                    // The current app on the system partition is better than
7726                    // what we have updated to on the data partition; switch
7727                    // back to the system partition version.
7728                    // At this point, its safely assumed that package installation for
7729                    // apps in system partition will go through. If not there won't be a working
7730                    // version of the app
7731                    // writer
7732                    synchronized (mPackages) {
7733                        // Just remove the loaded entries from package lists.
7734                        mPackages.remove(ps.name);
7735                    }
7736
7737                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7738                            + " reverting from " + ps.codePathString
7739                            + ": new version " + pkg.mVersionCode
7740                            + " better than installed " + ps.versionCode);
7741
7742                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7743                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7744                    synchronized (mInstallLock) {
7745                        args.cleanUpResourcesLI();
7746                    }
7747                    synchronized (mPackages) {
7748                        mSettings.enableSystemPackageLPw(ps.name);
7749                    }
7750                    updatedPkgBetter = true;
7751                }
7752            }
7753        }
7754
7755        if (updatedPkg != null) {
7756            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7757            // initially
7758            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7759
7760            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7761            // flag set initially
7762            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7763                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7764            }
7765        }
7766
7767        // Verify certificates against what was last scanned
7768        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7769
7770        /*
7771         * A new system app appeared, but we already had a non-system one of the
7772         * same name installed earlier.
7773         */
7774        boolean shouldHideSystemApp = false;
7775        if (updatedPkg == null && ps != null
7776                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7777            /*
7778             * Check to make sure the signatures match first. If they don't,
7779             * wipe the installed application and its data.
7780             */
7781            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7782                    != PackageManager.SIGNATURE_MATCH) {
7783                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7784                        + " signatures don't match existing userdata copy; removing");
7785                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7786                        "scanPackageInternalLI")) {
7787                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7788                }
7789                ps = null;
7790            } else {
7791                /*
7792                 * If the newly-added system app is an older version than the
7793                 * already installed version, hide it. It will be scanned later
7794                 * and re-added like an update.
7795                 */
7796                if (pkg.mVersionCode <= ps.versionCode) {
7797                    shouldHideSystemApp = true;
7798                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7799                            + " but new version " + pkg.mVersionCode + " better than installed "
7800                            + ps.versionCode + "; hiding system");
7801                } else {
7802                    /*
7803                     * The newly found system app is a newer version that the
7804                     * one previously installed. Simply remove the
7805                     * already-installed application and replace it with our own
7806                     * while keeping the application data.
7807                     */
7808                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7809                            + " reverting from " + ps.codePathString + ": new version "
7810                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7811                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7812                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7813                    synchronized (mInstallLock) {
7814                        args.cleanUpResourcesLI();
7815                    }
7816                }
7817            }
7818        }
7819
7820        // The apk is forward locked (not public) if its code and resources
7821        // are kept in different files. (except for app in either system or
7822        // vendor path).
7823        // TODO grab this value from PackageSettings
7824        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7825            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7826                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7827            }
7828        }
7829
7830        // TODO: extend to support forward-locked splits
7831        String resourcePath = null;
7832        String baseResourcePath = null;
7833        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7834            if (ps != null && ps.resourcePathString != null) {
7835                resourcePath = ps.resourcePathString;
7836                baseResourcePath = ps.resourcePathString;
7837            } else {
7838                // Should not happen at all. Just log an error.
7839                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7840            }
7841        } else {
7842            resourcePath = pkg.codePath;
7843            baseResourcePath = pkg.baseCodePath;
7844        }
7845
7846        // Set application objects path explicitly.
7847        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7848        pkg.setApplicationInfoCodePath(pkg.codePath);
7849        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7850        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7851        pkg.setApplicationInfoResourcePath(resourcePath);
7852        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7853        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7854
7855        // Note that we invoke the following method only if we are about to unpack an application
7856        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7857                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7858
7859        /*
7860         * If the system app should be overridden by a previously installed
7861         * data, hide the system app now and let the /data/app scan pick it up
7862         * again.
7863         */
7864        if (shouldHideSystemApp) {
7865            synchronized (mPackages) {
7866                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7867            }
7868        }
7869
7870        return scannedPkg;
7871    }
7872
7873    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
7874        // Derive the new package synthetic package name
7875        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
7876                + pkg.staticSharedLibVersion);
7877    }
7878
7879    private static String fixProcessName(String defProcessName,
7880            String processName) {
7881        if (processName == null) {
7882            return defProcessName;
7883        }
7884        return processName;
7885    }
7886
7887    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7888            throws PackageManagerException {
7889        if (pkgSetting.signatures.mSignatures != null) {
7890            // Already existing package. Make sure signatures match
7891            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7892                    == PackageManager.SIGNATURE_MATCH;
7893            if (!match) {
7894                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7895                        == PackageManager.SIGNATURE_MATCH;
7896            }
7897            if (!match) {
7898                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7899                        == PackageManager.SIGNATURE_MATCH;
7900            }
7901            if (!match) {
7902                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7903                        + pkg.packageName + " signatures do not match the "
7904                        + "previously installed version; ignoring!");
7905            }
7906        }
7907
7908        // Check for shared user signatures
7909        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7910            // Already existing package. Make sure signatures match
7911            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7912                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7913            if (!match) {
7914                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7915                        == PackageManager.SIGNATURE_MATCH;
7916            }
7917            if (!match) {
7918                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7919                        == PackageManager.SIGNATURE_MATCH;
7920            }
7921            if (!match) {
7922                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7923                        "Package " + pkg.packageName
7924                        + " has no signatures that match those in shared user "
7925                        + pkgSetting.sharedUser.name + "; ignoring!");
7926            }
7927        }
7928    }
7929
7930    /**
7931     * Enforces that only the system UID or root's UID can call a method exposed
7932     * via Binder.
7933     *
7934     * @param message used as message if SecurityException is thrown
7935     * @throws SecurityException if the caller is not system or root
7936     */
7937    private static final void enforceSystemOrRoot(String message) {
7938        final int uid = Binder.getCallingUid();
7939        if (uid != Process.SYSTEM_UID && uid != 0) {
7940            throw new SecurityException(message);
7941        }
7942    }
7943
7944    @Override
7945    public void performFstrimIfNeeded() {
7946        enforceSystemOrRoot("Only the system can request fstrim");
7947
7948        // Before everything else, see whether we need to fstrim.
7949        try {
7950            IStorageManager sm = PackageHelper.getStorageManager();
7951            if (sm != null) {
7952                boolean doTrim = false;
7953                final long interval = android.provider.Settings.Global.getLong(
7954                        mContext.getContentResolver(),
7955                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7956                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7957                if (interval > 0) {
7958                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
7959                    if (timeSinceLast > interval) {
7960                        doTrim = true;
7961                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7962                                + "; running immediately");
7963                    }
7964                }
7965                if (doTrim) {
7966                    final boolean dexOptDialogShown;
7967                    synchronized (mPackages) {
7968                        dexOptDialogShown = mDexOptDialogShown;
7969                    }
7970                    if (!isFirstBoot() && dexOptDialogShown) {
7971                        try {
7972                            ActivityManager.getService().showBootMessage(
7973                                    mContext.getResources().getString(
7974                                            R.string.android_upgrading_fstrim), true);
7975                        } catch (RemoteException e) {
7976                        }
7977                    }
7978                    sm.runMaintenance();
7979                }
7980            } else {
7981                Slog.e(TAG, "storageManager service unavailable!");
7982            }
7983        } catch (RemoteException e) {
7984            // Can't happen; StorageManagerService is local
7985        }
7986    }
7987
7988    @Override
7989    public void updatePackagesIfNeeded() {
7990        enforceSystemOrRoot("Only the system can request package update");
7991
7992        // We need to re-extract after an OTA.
7993        boolean causeUpgrade = isUpgrade();
7994
7995        // First boot or factory reset.
7996        // Note: we also handle devices that are upgrading to N right now as if it is their
7997        //       first boot, as they do not have profile data.
7998        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7999
8000        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8001        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8002
8003        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8004            return;
8005        }
8006
8007        List<PackageParser.Package> pkgs;
8008        synchronized (mPackages) {
8009            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8010        }
8011
8012        final long startTime = System.nanoTime();
8013        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8014                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
8015
8016        final int elapsedTimeSeconds =
8017                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8018
8019        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8020        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8021        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8022        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8023        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8024    }
8025
8026    /**
8027     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8028     * containing statistics about the invocation. The array consists of three elements,
8029     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8030     * and {@code numberOfPackagesFailed}.
8031     */
8032    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8033            String compilerFilter) {
8034
8035        int numberOfPackagesVisited = 0;
8036        int numberOfPackagesOptimized = 0;
8037        int numberOfPackagesSkipped = 0;
8038        int numberOfPackagesFailed = 0;
8039        final int numberOfPackagesToDexopt = pkgs.size();
8040
8041        for (PackageParser.Package pkg : pkgs) {
8042            numberOfPackagesVisited++;
8043
8044            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8045                if (DEBUG_DEXOPT) {
8046                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8047                }
8048                numberOfPackagesSkipped++;
8049                continue;
8050            }
8051
8052            if (DEBUG_DEXOPT) {
8053                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8054                        numberOfPackagesToDexopt + ": " + pkg.packageName);
8055            }
8056
8057            if (showDialog) {
8058                try {
8059                    ActivityManager.getService().showBootMessage(
8060                            mContext.getResources().getString(R.string.android_upgrading_apk,
8061                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
8062                } catch (RemoteException e) {
8063                }
8064                synchronized (mPackages) {
8065                    mDexOptDialogShown = true;
8066                }
8067            }
8068
8069            // If the OTA updates a system app which was previously preopted to a non-preopted state
8070            // the app might end up being verified at runtime. That's because by default the apps
8071            // are verify-profile but for preopted apps there's no profile.
8072            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
8073            // that before the OTA the app was preopted) the app gets compiled with a non-profile
8074            // filter (by default interpret-only).
8075            // Note that at this stage unused apps are already filtered.
8076            if (isSystemApp(pkg) &&
8077                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
8078                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
8079                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
8080            }
8081
8082            // checkProfiles is false to avoid merging profiles during boot which
8083            // might interfere with background compilation (b/28612421).
8084            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
8085            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
8086            // trade-off worth doing to save boot time work.
8087            int dexOptStatus = performDexOptTraced(pkg.packageName,
8088                    false /* checkProfiles */,
8089                    compilerFilter,
8090                    false /* force */);
8091            switch (dexOptStatus) {
8092                case PackageDexOptimizer.DEX_OPT_PERFORMED:
8093                    numberOfPackagesOptimized++;
8094                    break;
8095                case PackageDexOptimizer.DEX_OPT_SKIPPED:
8096                    numberOfPackagesSkipped++;
8097                    break;
8098                case PackageDexOptimizer.DEX_OPT_FAILED:
8099                    numberOfPackagesFailed++;
8100                    break;
8101                default:
8102                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
8103                    break;
8104            }
8105        }
8106
8107        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
8108                numberOfPackagesFailed };
8109    }
8110
8111    @Override
8112    public void notifyPackageUse(String packageName, int reason) {
8113        synchronized (mPackages) {
8114            PackageParser.Package p = mPackages.get(packageName);
8115            if (p == null) {
8116                return;
8117            }
8118            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
8119        }
8120    }
8121
8122    @Override
8123    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
8124        int userId = UserHandle.getCallingUserId();
8125        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
8126        if (ai == null) {
8127            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
8128                + loadingPackageName + ", user=" + userId);
8129            return;
8130        }
8131        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
8132    }
8133
8134    // TODO: this is not used nor needed. Delete it.
8135    @Override
8136    public boolean performDexOptIfNeeded(String packageName) {
8137        int dexOptStatus = performDexOptTraced(packageName,
8138                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
8139        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8140    }
8141
8142    @Override
8143    public boolean performDexOpt(String packageName,
8144            boolean checkProfiles, int compileReason, boolean force) {
8145        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8146                getCompilerFilterForReason(compileReason), force);
8147        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8148    }
8149
8150    @Override
8151    public boolean performDexOptMode(String packageName,
8152            boolean checkProfiles, String targetCompilerFilter, boolean force) {
8153        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
8154                targetCompilerFilter, force);
8155        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
8156    }
8157
8158    private int performDexOptTraced(String packageName,
8159                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8160        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8161        try {
8162            return performDexOptInternal(packageName, checkProfiles,
8163                    targetCompilerFilter, force);
8164        } finally {
8165            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8166        }
8167    }
8168
8169    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
8170    // if the package can now be considered up to date for the given filter.
8171    private int performDexOptInternal(String packageName,
8172                boolean checkProfiles, String targetCompilerFilter, boolean force) {
8173        PackageParser.Package p;
8174        synchronized (mPackages) {
8175            p = mPackages.get(packageName);
8176            if (p == null) {
8177                // Package could not be found. Report failure.
8178                return PackageDexOptimizer.DEX_OPT_FAILED;
8179            }
8180            mPackageUsage.maybeWriteAsync(mPackages);
8181            mCompilerStats.maybeWriteAsync();
8182        }
8183        long callingId = Binder.clearCallingIdentity();
8184        try {
8185            synchronized (mInstallLock) {
8186                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
8187                        targetCompilerFilter, force);
8188            }
8189        } finally {
8190            Binder.restoreCallingIdentity(callingId);
8191        }
8192    }
8193
8194    public ArraySet<String> getOptimizablePackages() {
8195        ArraySet<String> pkgs = new ArraySet<String>();
8196        synchronized (mPackages) {
8197            for (PackageParser.Package p : mPackages.values()) {
8198                if (PackageDexOptimizer.canOptimizePackage(p)) {
8199                    pkgs.add(p.packageName);
8200                }
8201            }
8202        }
8203        return pkgs;
8204    }
8205
8206    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
8207            boolean checkProfiles, String targetCompilerFilter,
8208            boolean force) {
8209        // Select the dex optimizer based on the force parameter.
8210        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
8211        //       allocate an object here.
8212        PackageDexOptimizer pdo = force
8213                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
8214                : mPackageDexOptimizer;
8215
8216        // Optimize all dependencies first. Note: we ignore the return value and march on
8217        // on errors.
8218        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
8219        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
8220        if (!deps.isEmpty()) {
8221            for (PackageParser.Package depPackage : deps) {
8222                // TODO: Analyze and investigate if we (should) profile libraries.
8223                // Currently this will do a full compilation of the library by default.
8224                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
8225                        false /* checkProfiles */,
8226                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
8227                        getOrCreateCompilerPackageStats(depPackage));
8228            }
8229        }
8230        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
8231                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
8232    }
8233
8234    // Performs dexopt on the used secondary dex files belonging to the given package.
8235    // Returns true if all dex files were process successfully (which could mean either dexopt or
8236    // skip). Returns false if any of the files caused errors.
8237    @Override
8238    public boolean performDexOptSecondary(String packageName, String compilerFilter,
8239            boolean force) {
8240        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
8241    }
8242
8243    /**
8244     * Reconcile the information we have about the secondary dex files belonging to
8245     * {@code packagName} and the actual dex files. For all dex files that were
8246     * deleted, update the internal records and delete the generated oat files.
8247     */
8248    @Override
8249    public void reconcileSecondaryDexFiles(String packageName) {
8250        mDexManager.reconcileSecondaryDexFiles(packageName);
8251    }
8252
8253    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
8254    // a reference there.
8255    /*package*/ DexManager getDexManager() {
8256        return mDexManager;
8257    }
8258
8259    /**
8260     * Execute the background dexopt job immediately.
8261     */
8262    @Override
8263    public boolean runBackgroundDexoptJob() {
8264        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
8265    }
8266
8267    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
8268        if (p.usesLibraries != null || p.usesOptionalLibraries != null
8269                || p.usesStaticLibraries != null) {
8270            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
8271            Set<String> collectedNames = new HashSet<>();
8272            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
8273
8274            retValue.remove(p);
8275
8276            return retValue;
8277        } else {
8278            return Collections.emptyList();
8279        }
8280    }
8281
8282    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
8283            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8284        if (!collectedNames.contains(p.packageName)) {
8285            collectedNames.add(p.packageName);
8286            collected.add(p);
8287
8288            if (p.usesLibraries != null) {
8289                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
8290                        null, collected, collectedNames);
8291            }
8292            if (p.usesOptionalLibraries != null) {
8293                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
8294                        null, collected, collectedNames);
8295            }
8296            if (p.usesStaticLibraries != null) {
8297                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
8298                        p.usesStaticLibrariesVersions, collected, collectedNames);
8299            }
8300        }
8301    }
8302
8303    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
8304            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
8305        final int libNameCount = libs.size();
8306        for (int i = 0; i < libNameCount; i++) {
8307            String libName = libs.get(i);
8308            int version = (versions != null && versions.length == libNameCount)
8309                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
8310            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
8311            if (libPkg != null) {
8312                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
8313            }
8314        }
8315    }
8316
8317    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
8318        synchronized (mPackages) {
8319            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
8320            if (libEntry != null) {
8321                return mPackages.get(libEntry.apk);
8322            }
8323            return null;
8324        }
8325    }
8326
8327    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
8328        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
8329        if (versionedLib == null) {
8330            return null;
8331        }
8332        return versionedLib.get(version);
8333    }
8334
8335    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
8336        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
8337                pkg.staticSharedLibName);
8338        if (versionedLib == null) {
8339            return null;
8340        }
8341        int previousLibVersion = -1;
8342        final int versionCount = versionedLib.size();
8343        for (int i = 0; i < versionCount; i++) {
8344            final int libVersion = versionedLib.keyAt(i);
8345            if (libVersion < pkg.staticSharedLibVersion) {
8346                previousLibVersion = Math.max(previousLibVersion, libVersion);
8347            }
8348        }
8349        if (previousLibVersion >= 0) {
8350            return versionedLib.get(previousLibVersion);
8351        }
8352        return null;
8353    }
8354
8355    public void shutdown() {
8356        mPackageUsage.writeNow(mPackages);
8357        mCompilerStats.writeNow();
8358    }
8359
8360    @Override
8361    public void dumpProfiles(String packageName) {
8362        PackageParser.Package pkg;
8363        synchronized (mPackages) {
8364            pkg = mPackages.get(packageName);
8365            if (pkg == null) {
8366                throw new IllegalArgumentException("Unknown package: " + packageName);
8367            }
8368        }
8369        /* Only the shell, root, or the app user should be able to dump profiles. */
8370        int callingUid = Binder.getCallingUid();
8371        if (callingUid != Process.SHELL_UID &&
8372            callingUid != Process.ROOT_UID &&
8373            callingUid != pkg.applicationInfo.uid) {
8374            throw new SecurityException("dumpProfiles");
8375        }
8376
8377        synchronized (mInstallLock) {
8378            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
8379            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
8380            try {
8381                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
8382                String codePaths = TextUtils.join(";", allCodePaths);
8383                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
8384            } catch (InstallerException e) {
8385                Slog.w(TAG, "Failed to dump profiles", e);
8386            }
8387            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8388        }
8389    }
8390
8391    @Override
8392    public void forceDexOpt(String packageName) {
8393        enforceSystemOrRoot("forceDexOpt");
8394
8395        PackageParser.Package pkg;
8396        synchronized (mPackages) {
8397            pkg = mPackages.get(packageName);
8398            if (pkg == null) {
8399                throw new IllegalArgumentException("Unknown package: " + packageName);
8400            }
8401        }
8402
8403        synchronized (mInstallLock) {
8404            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
8405
8406            // Whoever is calling forceDexOpt wants a fully compiled package.
8407            // Don't use profiles since that may cause compilation to be skipped.
8408            final int res = performDexOptInternalWithDependenciesLI(pkg,
8409                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
8410                    true /* force */);
8411
8412            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8413            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
8414                throw new IllegalStateException("Failed to dexopt: " + res);
8415            }
8416        }
8417    }
8418
8419    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
8420        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8421            Slog.w(TAG, "Unable to update from " + oldPkg.name
8422                    + " to " + newPkg.packageName
8423                    + ": old package not in system partition");
8424            return false;
8425        } else if (mPackages.get(oldPkg.name) != null) {
8426            Slog.w(TAG, "Unable to update from " + oldPkg.name
8427                    + " to " + newPkg.packageName
8428                    + ": old package still exists");
8429            return false;
8430        }
8431        return true;
8432    }
8433
8434    void removeCodePathLI(File codePath) {
8435        if (codePath.isDirectory()) {
8436            try {
8437                mInstaller.rmPackageDir(codePath.getAbsolutePath());
8438            } catch (InstallerException e) {
8439                Slog.w(TAG, "Failed to remove code path", e);
8440            }
8441        } else {
8442            codePath.delete();
8443        }
8444    }
8445
8446    private int[] resolveUserIds(int userId) {
8447        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
8448    }
8449
8450    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8451        if (pkg == null) {
8452            Slog.wtf(TAG, "Package was null!", new Throwable());
8453            return;
8454        }
8455        clearAppDataLeafLIF(pkg, userId, flags);
8456        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8457        for (int i = 0; i < childCount; i++) {
8458            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8459        }
8460    }
8461
8462    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8463        final PackageSetting ps;
8464        synchronized (mPackages) {
8465            ps = mSettings.mPackages.get(pkg.packageName);
8466        }
8467        for (int realUserId : resolveUserIds(userId)) {
8468            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8469            try {
8470                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8471                        ceDataInode);
8472            } catch (InstallerException e) {
8473                Slog.w(TAG, String.valueOf(e));
8474            }
8475        }
8476    }
8477
8478    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
8479        if (pkg == null) {
8480            Slog.wtf(TAG, "Package was null!", new Throwable());
8481            return;
8482        }
8483        destroyAppDataLeafLIF(pkg, userId, flags);
8484        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8485        for (int i = 0; i < childCount; i++) {
8486            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
8487        }
8488    }
8489
8490    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
8491        final PackageSetting ps;
8492        synchronized (mPackages) {
8493            ps = mSettings.mPackages.get(pkg.packageName);
8494        }
8495        for (int realUserId : resolveUserIds(userId)) {
8496            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
8497            try {
8498                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
8499                        ceDataInode);
8500            } catch (InstallerException e) {
8501                Slog.w(TAG, String.valueOf(e));
8502            }
8503        }
8504    }
8505
8506    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
8507        if (pkg == null) {
8508            Slog.wtf(TAG, "Package was null!", new Throwable());
8509            return;
8510        }
8511        destroyAppProfilesLeafLIF(pkg);
8512        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
8513        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8514        for (int i = 0; i < childCount; i++) {
8515            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
8516            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
8517                    true /* removeBaseMarker */);
8518        }
8519    }
8520
8521    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
8522            boolean removeBaseMarker) {
8523        if (pkg.isForwardLocked()) {
8524            return;
8525        }
8526
8527        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
8528            try {
8529                path = PackageManagerServiceUtils.realpath(new File(path));
8530            } catch (IOException e) {
8531                // TODO: Should we return early here ?
8532                Slog.w(TAG, "Failed to get canonical path", e);
8533                continue;
8534            }
8535
8536            final String useMarker = path.replace('/', '@');
8537            for (int realUserId : resolveUserIds(userId)) {
8538                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
8539                if (removeBaseMarker) {
8540                    File foreignUseMark = new File(profileDir, useMarker);
8541                    if (foreignUseMark.exists()) {
8542                        if (!foreignUseMark.delete()) {
8543                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
8544                                    + pkg.packageName);
8545                        }
8546                    }
8547                }
8548
8549                File[] markers = profileDir.listFiles();
8550                if (markers != null) {
8551                    final String searchString = "@" + pkg.packageName + "@";
8552                    // We also delete all markers that contain the package name we're
8553                    // uninstalling. These are associated with secondary dex-files belonging
8554                    // to the package. Reconstructing the path of these dex files is messy
8555                    // in general.
8556                    for (File marker : markers) {
8557                        if (marker.getName().indexOf(searchString) > 0) {
8558                            if (!marker.delete()) {
8559                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
8560                                    + pkg.packageName);
8561                            }
8562                        }
8563                    }
8564                }
8565            }
8566        }
8567    }
8568
8569    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
8570        try {
8571            mInstaller.destroyAppProfiles(pkg.packageName);
8572        } catch (InstallerException e) {
8573            Slog.w(TAG, String.valueOf(e));
8574        }
8575    }
8576
8577    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
8578        if (pkg == null) {
8579            Slog.wtf(TAG, "Package was null!", new Throwable());
8580            return;
8581        }
8582        clearAppProfilesLeafLIF(pkg);
8583        // We don't remove the base foreign use marker when clearing profiles because
8584        // we will rename it when the app is updated. Unlike the actual profile contents,
8585        // the foreign use marker is good across installs.
8586        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
8587        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8588        for (int i = 0; i < childCount; i++) {
8589            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
8590        }
8591    }
8592
8593    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
8594        try {
8595            mInstaller.clearAppProfiles(pkg.packageName);
8596        } catch (InstallerException e) {
8597            Slog.w(TAG, String.valueOf(e));
8598        }
8599    }
8600
8601    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
8602            long lastUpdateTime) {
8603        // Set parent install/update time
8604        PackageSetting ps = (PackageSetting) pkg.mExtras;
8605        if (ps != null) {
8606            ps.firstInstallTime = firstInstallTime;
8607            ps.lastUpdateTime = lastUpdateTime;
8608        }
8609        // Set children install/update time
8610        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8611        for (int i = 0; i < childCount; i++) {
8612            PackageParser.Package childPkg = pkg.childPackages.get(i);
8613            ps = (PackageSetting) childPkg.mExtras;
8614            if (ps != null) {
8615                ps.firstInstallTime = firstInstallTime;
8616                ps.lastUpdateTime = lastUpdateTime;
8617            }
8618        }
8619    }
8620
8621    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
8622            PackageParser.Package changingLib) {
8623        if (file.path != null) {
8624            usesLibraryFiles.add(file.path);
8625            return;
8626        }
8627        PackageParser.Package p = mPackages.get(file.apk);
8628        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
8629            // If we are doing this while in the middle of updating a library apk,
8630            // then we need to make sure to use that new apk for determining the
8631            // dependencies here.  (We haven't yet finished committing the new apk
8632            // to the package manager state.)
8633            if (p == null || p.packageName.equals(changingLib.packageName)) {
8634                p = changingLib;
8635            }
8636        }
8637        if (p != null) {
8638            usesLibraryFiles.addAll(p.getAllCodePaths());
8639        }
8640    }
8641
8642    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
8643            PackageParser.Package changingLib) throws PackageManagerException {
8644        if (pkg == null) {
8645            return;
8646        }
8647        ArraySet<String> usesLibraryFiles = null;
8648        if (pkg.usesLibraries != null) {
8649            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
8650                    null, null, pkg.packageName, changingLib, true, null);
8651        }
8652        if (pkg.usesStaticLibraries != null) {
8653            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
8654                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
8655                    pkg.packageName, changingLib, true, usesLibraryFiles);
8656        }
8657        if (pkg.usesOptionalLibraries != null) {
8658            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
8659                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
8660        }
8661        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
8662            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
8663        } else {
8664            pkg.usesLibraryFiles = null;
8665        }
8666    }
8667
8668    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
8669            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
8670            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
8671            boolean required, @Nullable ArraySet<String> outUsedLibraries)
8672            throws PackageManagerException {
8673        final int libCount = requestedLibraries.size();
8674        for (int i = 0; i < libCount; i++) {
8675            final String libName = requestedLibraries.get(i);
8676            final int libVersion = requiredVersions != null ? requiredVersions[i]
8677                    : SharedLibraryInfo.VERSION_UNDEFINED;
8678            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
8679            if (libEntry == null) {
8680                if (required) {
8681                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8682                            "Package " + packageName + " requires unavailable shared library "
8683                                    + libName + "; failing!");
8684                } else {
8685                    Slog.w(TAG, "Package " + packageName
8686                            + " desires unavailable shared library "
8687                            + libName + "; ignoring!");
8688                }
8689            } else {
8690                if (requiredVersions != null && requiredCertDigests != null) {
8691                    if (libEntry.info.getVersion() != requiredVersions[i]) {
8692                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8693                            "Package " + packageName + " requires unavailable static shared"
8694                                    + " library " + libName + " version "
8695                                    + libEntry.info.getVersion() + "; failing!");
8696                    }
8697
8698                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
8699                    if (libPkg == null) {
8700                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8701                                "Package " + packageName + " requires unavailable static shared"
8702                                        + " library; failing!");
8703                    }
8704
8705                    String expectedCertDigest = requiredCertDigests[i];
8706                    String libCertDigest = PackageUtils.computeCertSha256Digest(
8707                                libPkg.mSignatures[0]);
8708                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
8709                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
8710                                "Package " + packageName + " requires differently signed" +
8711                                        " static shared library; failing!");
8712                    }
8713                }
8714
8715                if (outUsedLibraries == null) {
8716                    outUsedLibraries = new ArraySet<>();
8717                }
8718                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
8719            }
8720        }
8721        return outUsedLibraries;
8722    }
8723
8724    private static boolean hasString(List<String> list, List<String> which) {
8725        if (list == null) {
8726            return false;
8727        }
8728        for (int i=list.size()-1; i>=0; i--) {
8729            for (int j=which.size()-1; j>=0; j--) {
8730                if (which.get(j).equals(list.get(i))) {
8731                    return true;
8732                }
8733            }
8734        }
8735        return false;
8736    }
8737
8738    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
8739            PackageParser.Package changingPkg) {
8740        ArrayList<PackageParser.Package> res = null;
8741        for (PackageParser.Package pkg : mPackages.values()) {
8742            if (changingPkg != null
8743                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
8744                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
8745                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
8746                            changingPkg.staticSharedLibName)) {
8747                return null;
8748            }
8749            if (res == null) {
8750                res = new ArrayList<>();
8751            }
8752            res.add(pkg);
8753            try {
8754                updateSharedLibrariesLPr(pkg, changingPkg);
8755            } catch (PackageManagerException e) {
8756                // If a system app update or an app and a required lib missing we
8757                // delete the package and for updated system apps keep the data as
8758                // it is better for the user to reinstall than to be in an limbo
8759                // state. Also libs disappearing under an app should never happen
8760                // - just in case.
8761                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
8762                    final int flags = pkg.isUpdatedSystemApp()
8763                            ? PackageManager.DELETE_KEEP_DATA : 0;
8764                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
8765                            flags , null, true, null);
8766                }
8767                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
8768            }
8769        }
8770        return res;
8771    }
8772
8773    /**
8774     * Derive the value of the {@code cpuAbiOverride} based on the provided
8775     * value and an optional stored value from the package settings.
8776     */
8777    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
8778        String cpuAbiOverride = null;
8779
8780        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
8781            cpuAbiOverride = null;
8782        } else if (abiOverride != null) {
8783            cpuAbiOverride = abiOverride;
8784        } else if (settings != null) {
8785            cpuAbiOverride = settings.cpuAbiOverrideString;
8786        }
8787
8788        return cpuAbiOverride;
8789    }
8790
8791    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
8792            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
8793                    throws PackageManagerException {
8794        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
8795        // If the package has children and this is the first dive in the function
8796        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
8797        // whether all packages (parent and children) would be successfully scanned
8798        // before the actual scan since scanning mutates internal state and we want
8799        // to atomically install the package and its children.
8800        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8801            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8802                scanFlags |= SCAN_CHECK_ONLY;
8803            }
8804        } else {
8805            scanFlags &= ~SCAN_CHECK_ONLY;
8806        }
8807
8808        final PackageParser.Package scannedPkg;
8809        try {
8810            // Scan the parent
8811            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
8812            // Scan the children
8813            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8814            for (int i = 0; i < childCount; i++) {
8815                PackageParser.Package childPkg = pkg.childPackages.get(i);
8816                scanPackageLI(childPkg, policyFlags,
8817                        scanFlags, currentTime, user);
8818            }
8819        } finally {
8820            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8821        }
8822
8823        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8824            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
8825        }
8826
8827        return scannedPkg;
8828    }
8829
8830    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
8831            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8832        boolean success = false;
8833        try {
8834            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
8835                    currentTime, user);
8836            success = true;
8837            return res;
8838        } finally {
8839            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
8840                // DELETE_DATA_ON_FAILURES is only used by frozen paths
8841                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
8842                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
8843                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
8844            }
8845        }
8846    }
8847
8848    /**
8849     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
8850     */
8851    private static boolean apkHasCode(String fileName) {
8852        StrictJarFile jarFile = null;
8853        try {
8854            jarFile = new StrictJarFile(fileName,
8855                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
8856            return jarFile.findEntry("classes.dex") != null;
8857        } catch (IOException ignore) {
8858        } finally {
8859            try {
8860                if (jarFile != null) {
8861                    jarFile.close();
8862                }
8863            } catch (IOException ignore) {}
8864        }
8865        return false;
8866    }
8867
8868    /**
8869     * Enforces code policy for the package. This ensures that if an APK has
8870     * declared hasCode="true" in its manifest that the APK actually contains
8871     * code.
8872     *
8873     * @throws PackageManagerException If bytecode could not be found when it should exist
8874     */
8875    private static void assertCodePolicy(PackageParser.Package pkg)
8876            throws PackageManagerException {
8877        final boolean shouldHaveCode =
8878                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
8879        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
8880            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8881                    "Package " + pkg.baseCodePath + " code is missing");
8882        }
8883
8884        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8885            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8886                final boolean splitShouldHaveCode =
8887                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
8888                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
8889                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8890                            "Package " + pkg.splitCodePaths[i] + " code is missing");
8891                }
8892            }
8893        }
8894    }
8895
8896    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8897            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8898                    throws PackageManagerException {
8899        if (DEBUG_PACKAGE_SCANNING) {
8900            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8901                Log.d(TAG, "Scanning package " + pkg.packageName);
8902        }
8903
8904        applyPolicy(pkg, policyFlags);
8905
8906        assertPackageIsValid(pkg, policyFlags, scanFlags);
8907
8908        // Initialize package source and resource directories
8909        final File scanFile = new File(pkg.codePath);
8910        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8911        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8912
8913        SharedUserSetting suid = null;
8914        PackageSetting pkgSetting = null;
8915
8916        // Getting the package setting may have a side-effect, so if we
8917        // are only checking if scan would succeed, stash a copy of the
8918        // old setting to restore at the end.
8919        PackageSetting nonMutatedPs = null;
8920
8921        // We keep references to the derived CPU Abis from settings in oder to reuse
8922        // them in the case where we're not upgrading or booting for the first time.
8923        String primaryCpuAbiFromSettings = null;
8924        String secondaryCpuAbiFromSettings = null;
8925
8926        // writer
8927        synchronized (mPackages) {
8928            if (pkg.mSharedUserId != null) {
8929                // SIDE EFFECTS; may potentially allocate a new shared user
8930                suid = mSettings.getSharedUserLPw(
8931                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
8932                if (DEBUG_PACKAGE_SCANNING) {
8933                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8934                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8935                                + "): packages=" + suid.packages);
8936                }
8937            }
8938
8939            // Check if we are renaming from an original package name.
8940            PackageSetting origPackage = null;
8941            String realName = null;
8942            if (pkg.mOriginalPackages != null) {
8943                // This package may need to be renamed to a previously
8944                // installed name.  Let's check on that...
8945                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8946                if (pkg.mOriginalPackages.contains(renamed)) {
8947                    // This package had originally been installed as the
8948                    // original name, and we have already taken care of
8949                    // transitioning to the new one.  Just update the new
8950                    // one to continue using the old name.
8951                    realName = pkg.mRealPackage;
8952                    if (!pkg.packageName.equals(renamed)) {
8953                        // Callers into this function may have already taken
8954                        // care of renaming the package; only do it here if
8955                        // it is not already done.
8956                        pkg.setPackageName(renamed);
8957                    }
8958                } else {
8959                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8960                        if ((origPackage = mSettings.getPackageLPr(
8961                                pkg.mOriginalPackages.get(i))) != null) {
8962                            // We do have the package already installed under its
8963                            // original name...  should we use it?
8964                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8965                                // New package is not compatible with original.
8966                                origPackage = null;
8967                                continue;
8968                            } else if (origPackage.sharedUser != null) {
8969                                // Make sure uid is compatible between packages.
8970                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8971                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8972                                            + " to " + pkg.packageName + ": old uid "
8973                                            + origPackage.sharedUser.name
8974                                            + " differs from " + pkg.mSharedUserId);
8975                                    origPackage = null;
8976                                    continue;
8977                                }
8978                                // TODO: Add case when shared user id is added [b/28144775]
8979                            } else {
8980                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8981                                        + pkg.packageName + " to old name " + origPackage.name);
8982                            }
8983                            break;
8984                        }
8985                    }
8986                }
8987            }
8988
8989            if (mTransferedPackages.contains(pkg.packageName)) {
8990                Slog.w(TAG, "Package " + pkg.packageName
8991                        + " was transferred to another, but its .apk remains");
8992            }
8993
8994            // See comments in nonMutatedPs declaration
8995            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8996                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
8997                if (foundPs != null) {
8998                    nonMutatedPs = new PackageSetting(foundPs);
8999                }
9000            }
9001
9002            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
9003                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
9004                if (foundPs != null) {
9005                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
9006                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
9007                }
9008            }
9009
9010            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9011            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
9012                PackageManagerService.reportSettingsProblem(Log.WARN,
9013                        "Package " + pkg.packageName + " shared user changed from "
9014                                + (pkgSetting.sharedUser != null
9015                                        ? pkgSetting.sharedUser.name : "<nothing>")
9016                                + " to "
9017                                + (suid != null ? suid.name : "<nothing>")
9018                                + "; replacing with new");
9019                pkgSetting = null;
9020            }
9021            final PackageSetting oldPkgSetting =
9022                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
9023            final PackageSetting disabledPkgSetting =
9024                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9025
9026            String[] usesStaticLibraries = null;
9027            if (pkg.usesStaticLibraries != null) {
9028                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
9029                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
9030            }
9031
9032            if (pkgSetting == null) {
9033                final String parentPackageName = (pkg.parentPackage != null)
9034                        ? pkg.parentPackage.packageName : null;
9035
9036                // REMOVE SharedUserSetting from method; update in a separate call
9037                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
9038                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
9039                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
9040                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
9041                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
9042                        true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(),
9043                        UserManagerService.getInstance(), usesStaticLibraries,
9044                        pkg.usesStaticLibrariesVersions);
9045                // SIDE EFFECTS; updates system state; move elsewhere
9046                if (origPackage != null) {
9047                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
9048                }
9049                mSettings.addUserToSettingLPw(pkgSetting);
9050            } else {
9051                // REMOVE SharedUserSetting from method; update in a separate call.
9052                //
9053                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
9054                // secondaryCpuAbi are not known at this point so we always update them
9055                // to null here, only to reset them at a later point.
9056                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
9057                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
9058                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
9059                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
9060                        UserManagerService.getInstance(), usesStaticLibraries,
9061                        pkg.usesStaticLibrariesVersions);
9062            }
9063            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
9064            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
9065
9066            // SIDE EFFECTS; modifies system state; move elsewhere
9067            if (pkgSetting.origPackage != null) {
9068                // If we are first transitioning from an original package,
9069                // fix up the new package's name now.  We need to do this after
9070                // looking up the package under its new name, so getPackageLP
9071                // can take care of fiddling things correctly.
9072                pkg.setPackageName(origPackage.name);
9073
9074                // File a report about this.
9075                String msg = "New package " + pkgSetting.realName
9076                        + " renamed to replace old package " + pkgSetting.name;
9077                reportSettingsProblem(Log.WARN, msg);
9078
9079                // Make a note of it.
9080                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9081                    mTransferedPackages.add(origPackage.name);
9082                }
9083
9084                // No longer need to retain this.
9085                pkgSetting.origPackage = null;
9086            }
9087
9088            // SIDE EFFECTS; modifies system state; move elsewhere
9089            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
9090                // Make a note of it.
9091                mTransferedPackages.add(pkg.packageName);
9092            }
9093
9094            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
9095                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9096            }
9097
9098            if ((scanFlags & SCAN_BOOTING) == 0
9099                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9100                // Check all shared libraries and map to their actual file path.
9101                // We only do this here for apps not on a system dir, because those
9102                // are the only ones that can fail an install due to this.  We
9103                // will take care of the system apps by updating all of their
9104                // library paths after the scan is done. Also during the initial
9105                // scan don't update any libs as we do this wholesale after all
9106                // apps are scanned to avoid dependency based scanning.
9107                updateSharedLibrariesLPr(pkg, null);
9108            }
9109
9110            if (mFoundPolicyFile) {
9111                SELinuxMMAC.assignSeinfoValue(pkg);
9112            }
9113
9114            pkg.applicationInfo.uid = pkgSetting.appId;
9115            pkg.mExtras = pkgSetting;
9116
9117
9118            // Static shared libs have same package with different versions where
9119            // we internally use a synthetic package name to allow multiple versions
9120            // of the same package, therefore we need to compare signatures against
9121            // the package setting for the latest library version.
9122            PackageSetting signatureCheckPs = pkgSetting;
9123            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9124                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
9125                if (libraryEntry != null) {
9126                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
9127                }
9128            }
9129
9130            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
9131                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
9132                    // We just determined the app is signed correctly, so bring
9133                    // over the latest parsed certs.
9134                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9135                } else {
9136                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9137                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9138                                "Package " + pkg.packageName + " upgrade keys do not match the "
9139                                + "previously installed version");
9140                    } else {
9141                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
9142                        String msg = "System package " + pkg.packageName
9143                                + " signature changed; retaining data.";
9144                        reportSettingsProblem(Log.WARN, msg);
9145                    }
9146                }
9147            } else {
9148                try {
9149                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
9150                    verifySignaturesLP(signatureCheckPs, pkg);
9151                    // We just determined the app is signed correctly, so bring
9152                    // over the latest parsed certs.
9153                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9154                } catch (PackageManagerException e) {
9155                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9156                        throw e;
9157                    }
9158                    // The signature has changed, but this package is in the system
9159                    // image...  let's recover!
9160                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
9161                    // However...  if this package is part of a shared user, but it
9162                    // doesn't match the signature of the shared user, let's fail.
9163                    // What this means is that you can't change the signatures
9164                    // associated with an overall shared user, which doesn't seem all
9165                    // that unreasonable.
9166                    if (signatureCheckPs.sharedUser != null) {
9167                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
9168                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
9169                            throw new PackageManagerException(
9170                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9171                                    "Signature mismatch for shared user: "
9172                                            + pkgSetting.sharedUser);
9173                        }
9174                    }
9175                    // File a report about this.
9176                    String msg = "System package " + pkg.packageName
9177                            + " signature changed; retaining data.";
9178                    reportSettingsProblem(Log.WARN, msg);
9179                }
9180            }
9181
9182            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
9183                // This package wants to adopt ownership of permissions from
9184                // another package.
9185                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
9186                    final String origName = pkg.mAdoptPermissions.get(i);
9187                    final PackageSetting orig = mSettings.getPackageLPr(origName);
9188                    if (orig != null) {
9189                        if (verifyPackageUpdateLPr(orig, pkg)) {
9190                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
9191                                    + pkg.packageName);
9192                            // SIDE EFFECTS; updates permissions system state; move elsewhere
9193                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
9194                        }
9195                    }
9196                }
9197            }
9198        }
9199
9200        pkg.applicationInfo.processName = fixProcessName(
9201                pkg.applicationInfo.packageName,
9202                pkg.applicationInfo.processName);
9203
9204        if (pkg != mPlatformPackage) {
9205            // Get all of our default paths setup
9206            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
9207        }
9208
9209        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
9210
9211        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
9212            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
9213                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
9214                derivePackageAbi(
9215                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
9216                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9217
9218                // Some system apps still use directory structure for native libraries
9219                // in which case we might end up not detecting abi solely based on apk
9220                // structure. Try to detect abi based on directory structure.
9221                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
9222                        pkg.applicationInfo.primaryCpuAbi == null) {
9223                    setBundledAppAbisAndRoots(pkg, pkgSetting);
9224                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9225                }
9226            } else {
9227                // This is not a first boot or an upgrade, don't bother deriving the
9228                // ABI during the scan. Instead, trust the value that was stored in the
9229                // package setting.
9230                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
9231                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
9232
9233                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9234
9235                if (DEBUG_ABI_SELECTION) {
9236                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
9237                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
9238                        pkg.applicationInfo.secondaryCpuAbi);
9239                }
9240            }
9241        } else {
9242            if ((scanFlags & SCAN_MOVE) != 0) {
9243                // We haven't run dex-opt for this move (since we've moved the compiled output too)
9244                // but we already have this packages package info in the PackageSetting. We just
9245                // use that and derive the native library path based on the new codepath.
9246                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
9247                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
9248            }
9249
9250            // Set native library paths again. For moves, the path will be updated based on the
9251            // ABIs we've determined above. For non-moves, the path will be updated based on the
9252            // ABIs we determined during compilation, but the path will depend on the final
9253            // package path (after the rename away from the stage path).
9254            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
9255        }
9256
9257        // This is a special case for the "system" package, where the ABI is
9258        // dictated by the zygote configuration (and init.rc). We should keep track
9259        // of this ABI so that we can deal with "normal" applications that run under
9260        // the same UID correctly.
9261        if (mPlatformPackage == pkg) {
9262            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
9263                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
9264        }
9265
9266        // If there's a mismatch between the abi-override in the package setting
9267        // and the abiOverride specified for the install. Warn about this because we
9268        // would've already compiled the app without taking the package setting into
9269        // account.
9270        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
9271            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
9272                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
9273                        " for package " + pkg.packageName);
9274            }
9275        }
9276
9277        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9278        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9279        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
9280
9281        // Copy the derived override back to the parsed package, so that we can
9282        // update the package settings accordingly.
9283        pkg.cpuAbiOverride = cpuAbiOverride;
9284
9285        if (DEBUG_ABI_SELECTION) {
9286            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
9287                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
9288                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
9289        }
9290
9291        // Push the derived path down into PackageSettings so we know what to
9292        // clean up at uninstall time.
9293        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
9294
9295        if (DEBUG_ABI_SELECTION) {
9296            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
9297                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
9298                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
9299        }
9300
9301        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
9302        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
9303            // We don't do this here during boot because we can do it all
9304            // at once after scanning all existing packages.
9305            //
9306            // We also do this *before* we perform dexopt on this package, so that
9307            // we can avoid redundant dexopts, and also to make sure we've got the
9308            // code and package path correct.
9309            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
9310        }
9311
9312        if (mFactoryTest && pkg.requestedPermissions.contains(
9313                android.Manifest.permission.FACTORY_TEST)) {
9314            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
9315        }
9316
9317        if (isSystemApp(pkg)) {
9318            pkgSetting.isOrphaned = true;
9319        }
9320
9321        // Take care of first install / last update times.
9322        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
9323        if (currentTime != 0) {
9324            if (pkgSetting.firstInstallTime == 0) {
9325                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
9326            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
9327                pkgSetting.lastUpdateTime = currentTime;
9328            }
9329        } else if (pkgSetting.firstInstallTime == 0) {
9330            // We need *something*.  Take time time stamp of the file.
9331            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
9332        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
9333            if (scanFileTime != pkgSetting.timeStamp) {
9334                // A package on the system image has changed; consider this
9335                // to be an update.
9336                pkgSetting.lastUpdateTime = scanFileTime;
9337            }
9338        }
9339        pkgSetting.setTimeStamp(scanFileTime);
9340
9341        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9342            if (nonMutatedPs != null) {
9343                synchronized (mPackages) {
9344                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
9345                }
9346            }
9347        } else {
9348            // Modify state for the given package setting
9349            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
9350                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
9351            if (isEphemeral(pkg)) {
9352                final int userId = user == null ? 0 : user.getIdentifier();
9353                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
9354            }
9355        }
9356        return pkg;
9357    }
9358
9359    /**
9360     * Applies policy to the parsed package based upon the given policy flags.
9361     * Ensures the package is in a good state.
9362     * <p>
9363     * Implementation detail: This method must NOT have any side effect. It would
9364     * ideally be static, but, it requires locks to read system state.
9365     */
9366    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
9367        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
9368            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
9369            if (pkg.applicationInfo.isDirectBootAware()) {
9370                // we're direct boot aware; set for all components
9371                for (PackageParser.Service s : pkg.services) {
9372                    s.info.encryptionAware = s.info.directBootAware = true;
9373                }
9374                for (PackageParser.Provider p : pkg.providers) {
9375                    p.info.encryptionAware = p.info.directBootAware = true;
9376                }
9377                for (PackageParser.Activity a : pkg.activities) {
9378                    a.info.encryptionAware = a.info.directBootAware = true;
9379                }
9380                for (PackageParser.Activity r : pkg.receivers) {
9381                    r.info.encryptionAware = r.info.directBootAware = true;
9382                }
9383            }
9384        } else {
9385            // Only allow system apps to be flagged as core apps.
9386            pkg.coreApp = false;
9387            // clear flags not applicable to regular apps
9388            pkg.applicationInfo.privateFlags &=
9389                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
9390            pkg.applicationInfo.privateFlags &=
9391                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
9392        }
9393        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
9394
9395        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
9396            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
9397        }
9398
9399        if (!isSystemApp(pkg)) {
9400            // Only system apps can use these features.
9401            pkg.mOriginalPackages = null;
9402            pkg.mRealPackage = null;
9403            pkg.mAdoptPermissions = null;
9404        }
9405    }
9406
9407    /**
9408     * Asserts the parsed package is valid according to the given policy. If the
9409     * package is invalid, for whatever reason, throws {@link PackgeManagerException}.
9410     * <p>
9411     * Implementation detail: This method must NOT have any side effects. It would
9412     * ideally be static, but, it requires locks to read system state.
9413     *
9414     * @throws PackageManagerException If the package fails any of the validation checks
9415     */
9416    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
9417            throws PackageManagerException {
9418        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
9419            assertCodePolicy(pkg);
9420        }
9421
9422        if (pkg.applicationInfo.getCodePath() == null ||
9423                pkg.applicationInfo.getResourcePath() == null) {
9424            // Bail out. The resource and code paths haven't been set.
9425            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
9426                    "Code and resource paths haven't been set correctly");
9427        }
9428
9429        // Make sure we're not adding any bogus keyset info
9430        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9431        ksms.assertScannedPackageValid(pkg);
9432
9433        synchronized (mPackages) {
9434            // The special "android" package can only be defined once
9435            if (pkg.packageName.equals("android")) {
9436                if (mAndroidApplication != null) {
9437                    Slog.w(TAG, "*************************************************");
9438                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
9439                    Slog.w(TAG, " codePath=" + pkg.codePath);
9440                    Slog.w(TAG, "*************************************************");
9441                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9442                            "Core android package being redefined.  Skipping.");
9443                }
9444            }
9445
9446            // A package name must be unique; don't allow duplicates
9447            if (mPackages.containsKey(pkg.packageName)) {
9448                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
9449                        "Application package " + pkg.packageName
9450                        + " already installed.  Skipping duplicate.");
9451            }
9452
9453            if (pkg.applicationInfo.isStaticSharedLibrary()) {
9454                // Static libs have a synthetic package name containing the version
9455                // but we still want the base name to be unique.
9456                if (mPackages.containsKey(pkg.manifestPackageName)) {
9457                    throw new PackageManagerException(
9458                            "Duplicate static shared lib provider package");
9459                }
9460
9461                // Static shared libraries should have at least O target SDK
9462                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
9463                    throw new PackageManagerException(
9464                            "Packages declaring static-shared libs must target O SDK or higher");
9465                }
9466
9467                // Package declaring static a shared lib cannot be ephemeral
9468                if (pkg.applicationInfo.isInstantApp()) {
9469                    throw new PackageManagerException(
9470                            "Packages declaring static-shared libs cannot be ephemeral");
9471                }
9472
9473                // Package declaring static a shared lib cannot be renamed since the package
9474                // name is synthetic and apps can't code around package manager internals.
9475                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
9476                    throw new PackageManagerException(
9477                            "Packages declaring static-shared libs cannot be renamed");
9478                }
9479
9480                // Package declaring static a shared lib cannot declare child packages
9481                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
9482                    throw new PackageManagerException(
9483                            "Packages declaring static-shared libs cannot have child packages");
9484                }
9485
9486                // Package declaring static a shared lib cannot declare dynamic libs
9487                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
9488                    throw new PackageManagerException(
9489                            "Packages declaring static-shared libs cannot declare dynamic libs");
9490                }
9491
9492                // Package declaring static a shared lib cannot declare shared users
9493                if (pkg.mSharedUserId != null) {
9494                    throw new PackageManagerException(
9495                            "Packages declaring static-shared libs cannot declare shared users");
9496                }
9497
9498                // Static shared libs cannot declare activities
9499                if (!pkg.activities.isEmpty()) {
9500                    throw new PackageManagerException(
9501                            "Static shared libs cannot declare activities");
9502                }
9503
9504                // Static shared libs cannot declare services
9505                if (!pkg.services.isEmpty()) {
9506                    throw new PackageManagerException(
9507                            "Static shared libs cannot declare services");
9508                }
9509
9510                // Static shared libs cannot declare providers
9511                if (!pkg.providers.isEmpty()) {
9512                    throw new PackageManagerException(
9513                            "Static shared libs cannot declare content providers");
9514                }
9515
9516                // Static shared libs cannot declare receivers
9517                if (!pkg.receivers.isEmpty()) {
9518                    throw new PackageManagerException(
9519                            "Static shared libs cannot declare broadcast receivers");
9520                }
9521
9522                // Static shared libs cannot declare permission groups
9523                if (!pkg.permissionGroups.isEmpty()) {
9524                    throw new PackageManagerException(
9525                            "Static shared libs cannot declare permission groups");
9526                }
9527
9528                // Static shared libs cannot declare permissions
9529                if (!pkg.permissions.isEmpty()) {
9530                    throw new PackageManagerException(
9531                            "Static shared libs cannot declare permissions");
9532                }
9533
9534                // Static shared libs cannot declare protected broadcasts
9535                if (pkg.protectedBroadcasts != null) {
9536                    throw new PackageManagerException(
9537                            "Static shared libs cannot declare protected broadcasts");
9538                }
9539
9540                // Static shared libs cannot be overlay targets
9541                if (pkg.mOverlayTarget != null) {
9542                    throw new PackageManagerException(
9543                            "Static shared libs cannot be overlay targets");
9544                }
9545
9546                // The version codes must be ordered as lib versions
9547                int minVersionCode = Integer.MIN_VALUE;
9548                int maxVersionCode = Integer.MAX_VALUE;
9549
9550                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9551                        pkg.staticSharedLibName);
9552                if (versionedLib != null) {
9553                    final int versionCount = versionedLib.size();
9554                    for (int i = 0; i < versionCount; i++) {
9555                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
9556                        // TODO: We will change version code to long, so in the new API it is long
9557                        final int libVersionCode = (int) libInfo.getDeclaringPackage()
9558                                .getVersionCode();
9559                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
9560                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
9561                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
9562                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
9563                        } else {
9564                            minVersionCode = maxVersionCode = libVersionCode;
9565                            break;
9566                        }
9567                    }
9568                }
9569                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
9570                    throw new PackageManagerException("Static shared"
9571                            + " lib version codes must be ordered as lib versions");
9572                }
9573            }
9574
9575            // Only privileged apps and updated privileged apps can add child packages.
9576            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
9577                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
9578                    throw new PackageManagerException("Only privileged apps can add child "
9579                            + "packages. Ignoring package " + pkg.packageName);
9580                }
9581                final int childCount = pkg.childPackages.size();
9582                for (int i = 0; i < childCount; i++) {
9583                    PackageParser.Package childPkg = pkg.childPackages.get(i);
9584                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
9585                            childPkg.packageName)) {
9586                        throw new PackageManagerException("Can't override child of "
9587                                + "another disabled app. Ignoring package " + pkg.packageName);
9588                    }
9589                }
9590            }
9591
9592            // If we're only installing presumed-existing packages, require that the
9593            // scanned APK is both already known and at the path previously established
9594            // for it.  Previously unknown packages we pick up normally, but if we have an
9595            // a priori expectation about this package's install presence, enforce it.
9596            // With a singular exception for new system packages. When an OTA contains
9597            // a new system package, we allow the codepath to change from a system location
9598            // to the user-installed location. If we don't allow this change, any newer,
9599            // user-installed version of the application will be ignored.
9600            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
9601                if (mExpectingBetter.containsKey(pkg.packageName)) {
9602                    logCriticalInfo(Log.WARN,
9603                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
9604                } else {
9605                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
9606                    if (known != null) {
9607                        if (DEBUG_PACKAGE_SCANNING) {
9608                            Log.d(TAG, "Examining " + pkg.codePath
9609                                    + " and requiring known paths " + known.codePathString
9610                                    + " & " + known.resourcePathString);
9611                        }
9612                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
9613                                || !pkg.applicationInfo.getResourcePath().equals(
9614                                        known.resourcePathString)) {
9615                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
9616                                    "Application package " + pkg.packageName
9617                                    + " found at " + pkg.applicationInfo.getCodePath()
9618                                    + " but expected at " + known.codePathString
9619                                    + "; ignoring.");
9620                        }
9621                    }
9622                }
9623            }
9624
9625            // Verify that this new package doesn't have any content providers
9626            // that conflict with existing packages.  Only do this if the
9627            // package isn't already installed, since we don't want to break
9628            // things that are installed.
9629            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
9630                final int N = pkg.providers.size();
9631                int i;
9632                for (i=0; i<N; i++) {
9633                    PackageParser.Provider p = pkg.providers.get(i);
9634                    if (p.info.authority != null) {
9635                        String names[] = p.info.authority.split(";");
9636                        for (int j = 0; j < names.length; j++) {
9637                            if (mProvidersByAuthority.containsKey(names[j])) {
9638                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9639                                final String otherPackageName =
9640                                        ((other != null && other.getComponentName() != null) ?
9641                                                other.getComponentName().getPackageName() : "?");
9642                                throw new PackageManagerException(
9643                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
9644                                        "Can't install because provider name " + names[j]
9645                                                + " (in package " + pkg.applicationInfo.packageName
9646                                                + ") is already used by " + otherPackageName);
9647                            }
9648                        }
9649                    }
9650                }
9651            }
9652        }
9653    }
9654
9655    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
9656            int type, String declaringPackageName, int declaringVersionCode) {
9657        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9658        if (versionedLib == null) {
9659            versionedLib = new SparseArray<>();
9660            mSharedLibraries.put(name, versionedLib);
9661            if (type == SharedLibraryInfo.TYPE_STATIC) {
9662                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
9663            }
9664        } else if (versionedLib.indexOfKey(version) >= 0) {
9665            return false;
9666        }
9667        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
9668                version, type, declaringPackageName, declaringVersionCode);
9669        versionedLib.put(version, libEntry);
9670        return true;
9671    }
9672
9673    private boolean removeSharedLibraryLPw(String name, int version) {
9674        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9675        if (versionedLib == null) {
9676            return false;
9677        }
9678        final int libIdx = versionedLib.indexOfKey(version);
9679        if (libIdx < 0) {
9680            return false;
9681        }
9682        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
9683        versionedLib.remove(version);
9684        if (versionedLib.size() <= 0) {
9685            mSharedLibraries.remove(name);
9686            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
9687                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
9688                        .getPackageName());
9689            }
9690        }
9691        return true;
9692    }
9693
9694    /**
9695     * Adds a scanned package to the system. When this method is finished, the package will
9696     * be available for query, resolution, etc...
9697     */
9698    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
9699            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
9700        final String pkgName = pkg.packageName;
9701        if (mCustomResolverComponentName != null &&
9702                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
9703            setUpCustomResolverActivity(pkg);
9704        }
9705
9706        if (pkg.packageName.equals("android")) {
9707            synchronized (mPackages) {
9708                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9709                    // Set up information for our fall-back user intent resolution activity.
9710                    mPlatformPackage = pkg;
9711                    pkg.mVersionCode = mSdkVersion;
9712                    mAndroidApplication = pkg.applicationInfo;
9713
9714                    if (!mResolverReplaced) {
9715                        mResolveActivity.applicationInfo = mAndroidApplication;
9716                        mResolveActivity.name = ResolverActivity.class.getName();
9717                        mResolveActivity.packageName = mAndroidApplication.packageName;
9718                        mResolveActivity.processName = "system:ui";
9719                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9720                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
9721                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
9722                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
9723                        mResolveActivity.exported = true;
9724                        mResolveActivity.enabled = true;
9725                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
9726                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
9727                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
9728                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
9729                                | ActivityInfo.CONFIG_ORIENTATION
9730                                | ActivityInfo.CONFIG_KEYBOARD
9731                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
9732                        mResolveInfo.activityInfo = mResolveActivity;
9733                        mResolveInfo.priority = 0;
9734                        mResolveInfo.preferredOrder = 0;
9735                        mResolveInfo.match = 0;
9736                        mResolveComponentName = new ComponentName(
9737                                mAndroidApplication.packageName, mResolveActivity.name);
9738                    }
9739                }
9740            }
9741        }
9742
9743        ArrayList<PackageParser.Package> clientLibPkgs = null;
9744        // writer
9745        synchronized (mPackages) {
9746            boolean hasStaticSharedLibs = false;
9747
9748            // Any app can add new static shared libraries
9749            if (pkg.staticSharedLibName != null) {
9750                // Static shared libs don't allow renaming as they have synthetic package
9751                // names to allow install of multiple versions, so use name from manifest.
9752                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
9753                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
9754                        pkg.manifestPackageName, pkg.mVersionCode)) {
9755                    hasStaticSharedLibs = true;
9756                } else {
9757                    Slog.w(TAG, "Package " + pkg.packageName + " library "
9758                                + pkg.staticSharedLibName + " already exists; skipping");
9759                }
9760                // Static shared libs cannot be updated once installed since they
9761                // use synthetic package name which includes the version code, so
9762                // not need to update other packages's shared lib dependencies.
9763            }
9764
9765            if (!hasStaticSharedLibs
9766                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9767                // Only system apps can add new dynamic shared libraries.
9768                if (pkg.libraryNames != null) {
9769                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
9770                        String name = pkg.libraryNames.get(i);
9771                        boolean allowed = false;
9772                        if (pkg.isUpdatedSystemApp()) {
9773                            // New library entries can only be added through the
9774                            // system image.  This is important to get rid of a lot
9775                            // of nasty edge cases: for example if we allowed a non-
9776                            // system update of the app to add a library, then uninstalling
9777                            // the update would make the library go away, and assumptions
9778                            // we made such as through app install filtering would now
9779                            // have allowed apps on the device which aren't compatible
9780                            // with it.  Better to just have the restriction here, be
9781                            // conservative, and create many fewer cases that can negatively
9782                            // impact the user experience.
9783                            final PackageSetting sysPs = mSettings
9784                                    .getDisabledSystemPkgLPr(pkg.packageName);
9785                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
9786                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
9787                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
9788                                        allowed = true;
9789                                        break;
9790                                    }
9791                                }
9792                            }
9793                        } else {
9794                            allowed = true;
9795                        }
9796                        if (allowed) {
9797                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
9798                                    SharedLibraryInfo.VERSION_UNDEFINED,
9799                                    SharedLibraryInfo.TYPE_DYNAMIC,
9800                                    pkg.packageName, pkg.mVersionCode)) {
9801                                Slog.w(TAG, "Package " + pkg.packageName + " library "
9802                                        + name + " already exists; skipping");
9803                            }
9804                        } else {
9805                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
9806                                    + name + " that is not declared on system image; skipping");
9807                        }
9808                    }
9809
9810                    if ((scanFlags & SCAN_BOOTING) == 0) {
9811                        // If we are not booting, we need to update any applications
9812                        // that are clients of our shared library.  If we are booting,
9813                        // this will all be done once the scan is complete.
9814                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
9815                    }
9816                }
9817            }
9818        }
9819
9820        if ((scanFlags & SCAN_BOOTING) != 0) {
9821            // No apps can run during boot scan, so they don't need to be frozen
9822        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
9823            // Caller asked to not kill app, so it's probably not frozen
9824        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
9825            // Caller asked us to ignore frozen check for some reason; they
9826            // probably didn't know the package name
9827        } else {
9828            // We're doing major surgery on this package, so it better be frozen
9829            // right now to keep it from launching
9830            checkPackageFrozen(pkgName);
9831        }
9832
9833        // Also need to kill any apps that are dependent on the library.
9834        if (clientLibPkgs != null) {
9835            for (int i=0; i<clientLibPkgs.size(); i++) {
9836                PackageParser.Package clientPkg = clientLibPkgs.get(i);
9837                killApplication(clientPkg.applicationInfo.packageName,
9838                        clientPkg.applicationInfo.uid, "update lib");
9839            }
9840        }
9841
9842        // writer
9843        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
9844
9845        boolean createIdmapFailed = false;
9846        synchronized (mPackages) {
9847            // We don't expect installation to fail beyond this point
9848
9849            if (pkgSetting.pkg != null) {
9850                // Note that |user| might be null during the initial boot scan. If a codePath
9851                // for an app has changed during a boot scan, it's due to an app update that's
9852                // part of the system partition and marker changes must be applied to all users.
9853                final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier();
9854                final int[] userIds = resolveUserIds(userId);
9855                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds);
9856            }
9857
9858            // Add the new setting to mSettings
9859            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
9860            // Add the new setting to mPackages
9861            mPackages.put(pkg.applicationInfo.packageName, pkg);
9862            // Make sure we don't accidentally delete its data.
9863            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
9864            while (iter.hasNext()) {
9865                PackageCleanItem item = iter.next();
9866                if (pkgName.equals(item.packageName)) {
9867                    iter.remove();
9868                }
9869            }
9870
9871            // Add the package's KeySets to the global KeySetManagerService
9872            KeySetManagerService ksms = mSettings.mKeySetManagerService;
9873            ksms.addScannedPackageLPw(pkg);
9874
9875            int N = pkg.providers.size();
9876            StringBuilder r = null;
9877            int i;
9878            for (i=0; i<N; i++) {
9879                PackageParser.Provider p = pkg.providers.get(i);
9880                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
9881                        p.info.processName);
9882                mProviders.addProvider(p);
9883                p.syncable = p.info.isSyncable;
9884                if (p.info.authority != null) {
9885                    String names[] = p.info.authority.split(";");
9886                    p.info.authority = null;
9887                    for (int j = 0; j < names.length; j++) {
9888                        if (j == 1 && p.syncable) {
9889                            // We only want the first authority for a provider to possibly be
9890                            // syncable, so if we already added this provider using a different
9891                            // authority clear the syncable flag. We copy the provider before
9892                            // changing it because the mProviders object contains a reference
9893                            // to a provider that we don't want to change.
9894                            // Only do this for the second authority since the resulting provider
9895                            // object can be the same for all future authorities for this provider.
9896                            p = new PackageParser.Provider(p);
9897                            p.syncable = false;
9898                        }
9899                        if (!mProvidersByAuthority.containsKey(names[j])) {
9900                            mProvidersByAuthority.put(names[j], p);
9901                            if (p.info.authority == null) {
9902                                p.info.authority = names[j];
9903                            } else {
9904                                p.info.authority = p.info.authority + ";" + names[j];
9905                            }
9906                            if (DEBUG_PACKAGE_SCANNING) {
9907                                if (chatty)
9908                                    Log.d(TAG, "Registered content provider: " + names[j]
9909                                            + ", className = " + p.info.name + ", isSyncable = "
9910                                            + p.info.isSyncable);
9911                            }
9912                        } else {
9913                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
9914                            Slog.w(TAG, "Skipping provider name " + names[j] +
9915                                    " (in package " + pkg.applicationInfo.packageName +
9916                                    "): name already used by "
9917                                    + ((other != null && other.getComponentName() != null)
9918                                            ? other.getComponentName().getPackageName() : "?"));
9919                        }
9920                    }
9921                }
9922                if (chatty) {
9923                    if (r == null) {
9924                        r = new StringBuilder(256);
9925                    } else {
9926                        r.append(' ');
9927                    }
9928                    r.append(p.info.name);
9929                }
9930            }
9931            if (r != null) {
9932                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
9933            }
9934
9935            N = pkg.services.size();
9936            r = null;
9937            for (i=0; i<N; i++) {
9938                PackageParser.Service s = pkg.services.get(i);
9939                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
9940                        s.info.processName);
9941                mServices.addService(s);
9942                if (chatty) {
9943                    if (r == null) {
9944                        r = new StringBuilder(256);
9945                    } else {
9946                        r.append(' ');
9947                    }
9948                    r.append(s.info.name);
9949                }
9950            }
9951            if (r != null) {
9952                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
9953            }
9954
9955            N = pkg.receivers.size();
9956            r = null;
9957            for (i=0; i<N; i++) {
9958                PackageParser.Activity a = pkg.receivers.get(i);
9959                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
9960                        a.info.processName);
9961                mReceivers.addActivity(a, "receiver");
9962                if (chatty) {
9963                    if (r == null) {
9964                        r = new StringBuilder(256);
9965                    } else {
9966                        r.append(' ');
9967                    }
9968                    r.append(a.info.name);
9969                }
9970            }
9971            if (r != null) {
9972                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
9973            }
9974
9975            N = pkg.activities.size();
9976            r = null;
9977            for (i=0; i<N; i++) {
9978                PackageParser.Activity a = pkg.activities.get(i);
9979                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
9980                        a.info.processName);
9981                mActivities.addActivity(a, "activity");
9982                if (chatty) {
9983                    if (r == null) {
9984                        r = new StringBuilder(256);
9985                    } else {
9986                        r.append(' ');
9987                    }
9988                    r.append(a.info.name);
9989                }
9990            }
9991            if (r != null) {
9992                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
9993            }
9994
9995            N = pkg.permissionGroups.size();
9996            r = null;
9997            for (i=0; i<N; i++) {
9998                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
9999                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
10000                final String curPackageName = cur == null ? null : cur.info.packageName;
10001                // Dont allow ephemeral apps to define new permission groups.
10002                if (pkg.applicationInfo.isInstantApp()) {
10003                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10004                            + pg.info.packageName
10005                            + " ignored: ephemeral apps cannot define new permission groups.");
10006                    continue;
10007                }
10008                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
10009                if (cur == null || isPackageUpdate) {
10010                    mPermissionGroups.put(pg.info.name, pg);
10011                    if (chatty) {
10012                        if (r == null) {
10013                            r = new StringBuilder(256);
10014                        } else {
10015                            r.append(' ');
10016                        }
10017                        if (isPackageUpdate) {
10018                            r.append("UPD:");
10019                        }
10020                        r.append(pg.info.name);
10021                    }
10022                } else {
10023                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
10024                            + pg.info.packageName + " ignored: original from "
10025                            + cur.info.packageName);
10026                    if (chatty) {
10027                        if (r == null) {
10028                            r = new StringBuilder(256);
10029                        } else {
10030                            r.append(' ');
10031                        }
10032                        r.append("DUP:");
10033                        r.append(pg.info.name);
10034                    }
10035                }
10036            }
10037            if (r != null) {
10038                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
10039            }
10040
10041            N = pkg.permissions.size();
10042            r = null;
10043            for (i=0; i<N; i++) {
10044                PackageParser.Permission p = pkg.permissions.get(i);
10045
10046                // Dont allow ephemeral apps to define new permissions.
10047                if (pkg.applicationInfo.isInstantApp()) {
10048                    Slog.w(TAG, "Permission " + p.info.name + " from package "
10049                            + p.info.packageName
10050                            + " ignored: ephemeral apps cannot define new permissions.");
10051                    continue;
10052                }
10053
10054                // Assume by default that we did not install this permission into the system.
10055                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
10056
10057                // Now that permission groups have a special meaning, we ignore permission
10058                // groups for legacy apps to prevent unexpected behavior. In particular,
10059                // permissions for one app being granted to someone just becase they happen
10060                // to be in a group defined by another app (before this had no implications).
10061                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
10062                    p.group = mPermissionGroups.get(p.info.group);
10063                    // Warn for a permission in an unknown group.
10064                    if (p.info.group != null && p.group == null) {
10065                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10066                                + p.info.packageName + " in an unknown group " + p.info.group);
10067                    }
10068                }
10069
10070                ArrayMap<String, BasePermission> permissionMap =
10071                        p.tree ? mSettings.mPermissionTrees
10072                                : mSettings.mPermissions;
10073                BasePermission bp = permissionMap.get(p.info.name);
10074
10075                // Allow system apps to redefine non-system permissions
10076                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
10077                    final boolean currentOwnerIsSystem = (bp.perm != null
10078                            && isSystemApp(bp.perm.owner));
10079                    if (isSystemApp(p.owner)) {
10080                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
10081                            // It's a built-in permission and no owner, take ownership now
10082                            bp.packageSetting = pkgSetting;
10083                            bp.perm = p;
10084                            bp.uid = pkg.applicationInfo.uid;
10085                            bp.sourcePackage = p.info.packageName;
10086                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10087                        } else if (!currentOwnerIsSystem) {
10088                            String msg = "New decl " + p.owner + " of permission  "
10089                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
10090                            reportSettingsProblem(Log.WARN, msg);
10091                            bp = null;
10092                        }
10093                    }
10094                }
10095
10096                if (bp == null) {
10097                    bp = new BasePermission(p.info.name, p.info.packageName,
10098                            BasePermission.TYPE_NORMAL);
10099                    permissionMap.put(p.info.name, bp);
10100                }
10101
10102                if (bp.perm == null) {
10103                    if (bp.sourcePackage == null
10104                            || bp.sourcePackage.equals(p.info.packageName)) {
10105                        BasePermission tree = findPermissionTreeLP(p.info.name);
10106                        if (tree == null
10107                                || tree.sourcePackage.equals(p.info.packageName)) {
10108                            bp.packageSetting = pkgSetting;
10109                            bp.perm = p;
10110                            bp.uid = pkg.applicationInfo.uid;
10111                            bp.sourcePackage = p.info.packageName;
10112                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
10113                            if (chatty) {
10114                                if (r == null) {
10115                                    r = new StringBuilder(256);
10116                                } else {
10117                                    r.append(' ');
10118                                }
10119                                r.append(p.info.name);
10120                            }
10121                        } else {
10122                            Slog.w(TAG, "Permission " + p.info.name + " from package "
10123                                    + p.info.packageName + " ignored: base tree "
10124                                    + tree.name + " is from package "
10125                                    + tree.sourcePackage);
10126                        }
10127                    } else {
10128                        Slog.w(TAG, "Permission " + p.info.name + " from package "
10129                                + p.info.packageName + " ignored: original from "
10130                                + bp.sourcePackage);
10131                    }
10132                } else if (chatty) {
10133                    if (r == null) {
10134                        r = new StringBuilder(256);
10135                    } else {
10136                        r.append(' ');
10137                    }
10138                    r.append("DUP:");
10139                    r.append(p.info.name);
10140                }
10141                if (bp.perm == p) {
10142                    bp.protectionLevel = p.info.protectionLevel;
10143                }
10144            }
10145
10146            if (r != null) {
10147                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
10148            }
10149
10150            N = pkg.instrumentation.size();
10151            r = null;
10152            for (i=0; i<N; i++) {
10153                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
10154                a.info.packageName = pkg.applicationInfo.packageName;
10155                a.info.sourceDir = pkg.applicationInfo.sourceDir;
10156                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
10157                a.info.splitNames = pkg.splitNames;
10158                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
10159                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
10160                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
10161                a.info.dataDir = pkg.applicationInfo.dataDir;
10162                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
10163                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
10164                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
10165                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
10166                mInstrumentation.put(a.getComponentName(), a);
10167                if (chatty) {
10168                    if (r == null) {
10169                        r = new StringBuilder(256);
10170                    } else {
10171                        r.append(' ');
10172                    }
10173                    r.append(a.info.name);
10174                }
10175            }
10176            if (r != null) {
10177                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
10178            }
10179
10180            if (pkg.protectedBroadcasts != null) {
10181                N = pkg.protectedBroadcasts.size();
10182                for (i=0; i<N; i++) {
10183                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
10184                }
10185            }
10186
10187            // Create idmap files for pairs of (packages, overlay packages).
10188            // Note: "android", ie framework-res.apk, is handled by native layers.
10189            if (pkg.mOverlayTarget != null) {
10190                // This is an overlay package.
10191                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
10192                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
10193                        mOverlays.put(pkg.mOverlayTarget,
10194                                new ArrayMap<String, PackageParser.Package>());
10195                    }
10196                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
10197                    map.put(pkg.packageName, pkg);
10198                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
10199                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
10200                        createIdmapFailed = true;
10201                    }
10202                }
10203            } else if (mOverlays.containsKey(pkg.packageName) &&
10204                    !pkg.packageName.equals("android")) {
10205                // This is a regular package, with one or more known overlay packages.
10206                createIdmapsForPackageLI(pkg);
10207            }
10208        }
10209
10210        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10211
10212        if (createIdmapFailed) {
10213            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10214                    "scanPackageLI failed to createIdmap");
10215        }
10216    }
10217
10218    private static void maybeRenameForeignDexMarkers(PackageParser.Package existing,
10219            PackageParser.Package update, int[] userIds) {
10220        if (existing.applicationInfo == null || update.applicationInfo == null) {
10221            // This isn't due to an app installation.
10222            return;
10223        }
10224
10225        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
10226        final File newCodePath = new File(update.applicationInfo.getCodePath());
10227
10228        // The codePath hasn't changed, so there's nothing for us to do.
10229        if (Objects.equals(oldCodePath, newCodePath)) {
10230            return;
10231        }
10232
10233        File canonicalNewCodePath;
10234        try {
10235            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
10236        } catch (IOException e) {
10237            Slog.w(TAG, "Failed to get canonical path.", e);
10238            return;
10239        }
10240
10241        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
10242        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
10243        // that the last component of the path (i.e, the name) doesn't need canonicalization
10244        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
10245        // but may change in the future. Hopefully this function won't exist at that point.
10246        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
10247                oldCodePath.getName());
10248
10249        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
10250        // with "@".
10251        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
10252        if (!oldMarkerPrefix.endsWith("@")) {
10253            oldMarkerPrefix += "@";
10254        }
10255        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
10256        if (!newMarkerPrefix.endsWith("@")) {
10257            newMarkerPrefix += "@";
10258        }
10259
10260        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
10261        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
10262        for (String updatedPath : updatedPaths) {
10263            String updatedPathName = new File(updatedPath).getName();
10264            markerSuffixes.add(updatedPathName.replace('/', '@'));
10265        }
10266
10267        for (int userId : userIds) {
10268            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
10269
10270            for (String markerSuffix : markerSuffixes) {
10271                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
10272                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
10273                if (oldForeignUseMark.exists()) {
10274                    try {
10275                        Os.rename(oldForeignUseMark.getAbsolutePath(),
10276                                newForeignUseMark.getAbsolutePath());
10277                    } catch (ErrnoException e) {
10278                        Slog.w(TAG, "Failed to rename foreign use marker", e);
10279                        oldForeignUseMark.delete();
10280                    }
10281                }
10282            }
10283        }
10284    }
10285
10286    /**
10287     * Derive the ABI of a non-system package located at {@code scanFile}. This information
10288     * is derived purely on the basis of the contents of {@code scanFile} and
10289     * {@code cpuAbiOverride}.
10290     *
10291     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
10292     */
10293    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
10294                                 String cpuAbiOverride, boolean extractLibs,
10295                                 File appLib32InstallDir)
10296            throws PackageManagerException {
10297        // Give ourselves some initial paths; we'll come back for another
10298        // pass once we've determined ABI below.
10299        setNativeLibraryPaths(pkg, appLib32InstallDir);
10300
10301        // We would never need to extract libs for forward-locked and external packages,
10302        // since the container service will do it for us. We shouldn't attempt to
10303        // extract libs from system app when it was not updated.
10304        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
10305                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
10306            extractLibs = false;
10307        }
10308
10309        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
10310        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
10311
10312        NativeLibraryHelper.Handle handle = null;
10313        try {
10314            handle = NativeLibraryHelper.Handle.create(pkg);
10315            // TODO(multiArch): This can be null for apps that didn't go through the
10316            // usual installation process. We can calculate it again, like we
10317            // do during install time.
10318            //
10319            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
10320            // unnecessary.
10321            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
10322
10323            // Null out the abis so that they can be recalculated.
10324            pkg.applicationInfo.primaryCpuAbi = null;
10325            pkg.applicationInfo.secondaryCpuAbi = null;
10326            if (isMultiArch(pkg.applicationInfo)) {
10327                // Warn if we've set an abiOverride for multi-lib packages..
10328                // By definition, we need to copy both 32 and 64 bit libraries for
10329                // such packages.
10330                if (pkg.cpuAbiOverride != null
10331                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
10332                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
10333                }
10334
10335                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
10336                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
10337                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
10338                    if (extractLibs) {
10339                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10340                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10341                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
10342                                useIsaSpecificSubdirs);
10343                    } else {
10344                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10345                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
10346                    }
10347                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10348                }
10349
10350                maybeThrowExceptionForMultiArchCopy(
10351                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
10352
10353                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
10354                    if (extractLibs) {
10355                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10356                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10357                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
10358                                useIsaSpecificSubdirs);
10359                    } else {
10360                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10361                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
10362                    }
10363                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10364                }
10365
10366                maybeThrowExceptionForMultiArchCopy(
10367                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
10368
10369                if (abi64 >= 0) {
10370                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
10371                }
10372
10373                if (abi32 >= 0) {
10374                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
10375                    if (abi64 >= 0) {
10376                        if (pkg.use32bitAbi) {
10377                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
10378                            pkg.applicationInfo.primaryCpuAbi = abi;
10379                        } else {
10380                            pkg.applicationInfo.secondaryCpuAbi = abi;
10381                        }
10382                    } else {
10383                        pkg.applicationInfo.primaryCpuAbi = abi;
10384                    }
10385                }
10386
10387            } else {
10388                String[] abiList = (cpuAbiOverride != null) ?
10389                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
10390
10391                // Enable gross and lame hacks for apps that are built with old
10392                // SDK tools. We must scan their APKs for renderscript bitcode and
10393                // not launch them if it's present. Don't bother checking on devices
10394                // that don't have 64 bit support.
10395                boolean needsRenderScriptOverride = false;
10396                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
10397                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
10398                    abiList = Build.SUPPORTED_32_BIT_ABIS;
10399                    needsRenderScriptOverride = true;
10400                }
10401
10402                final int copyRet;
10403                if (extractLibs) {
10404                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
10405                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
10406                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
10407                } else {
10408                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
10409                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
10410                }
10411                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10412
10413                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
10414                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
10415                            "Error unpackaging native libs for app, errorCode=" + copyRet);
10416                }
10417
10418                if (copyRet >= 0) {
10419                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
10420                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
10421                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
10422                } else if (needsRenderScriptOverride) {
10423                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
10424                }
10425            }
10426        } catch (IOException ioe) {
10427            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
10428        } finally {
10429            IoUtils.closeQuietly(handle);
10430        }
10431
10432        // Now that we've calculated the ABIs and determined if it's an internal app,
10433        // we will go ahead and populate the nativeLibraryPath.
10434        setNativeLibraryPaths(pkg, appLib32InstallDir);
10435    }
10436
10437    /**
10438     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
10439     * i.e, so that all packages can be run inside a single process if required.
10440     *
10441     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
10442     * this function will either try and make the ABI for all packages in {@code packagesForUser}
10443     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
10444     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
10445     * updating a package that belongs to a shared user.
10446     *
10447     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
10448     * adds unnecessary complexity.
10449     */
10450    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
10451            PackageParser.Package scannedPackage) {
10452        String requiredInstructionSet = null;
10453        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
10454            requiredInstructionSet = VMRuntime.getInstructionSet(
10455                     scannedPackage.applicationInfo.primaryCpuAbi);
10456        }
10457
10458        PackageSetting requirer = null;
10459        for (PackageSetting ps : packagesForUser) {
10460            // If packagesForUser contains scannedPackage, we skip it. This will happen
10461            // when scannedPackage is an update of an existing package. Without this check,
10462            // we will never be able to change the ABI of any package belonging to a shared
10463            // user, even if it's compatible with other packages.
10464            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10465                if (ps.primaryCpuAbiString == null) {
10466                    continue;
10467                }
10468
10469                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
10470                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
10471                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
10472                    // this but there's not much we can do.
10473                    String errorMessage = "Instruction set mismatch, "
10474                            + ((requirer == null) ? "[caller]" : requirer)
10475                            + " requires " + requiredInstructionSet + " whereas " + ps
10476                            + " requires " + instructionSet;
10477                    Slog.w(TAG, errorMessage);
10478                }
10479
10480                if (requiredInstructionSet == null) {
10481                    requiredInstructionSet = instructionSet;
10482                    requirer = ps;
10483                }
10484            }
10485        }
10486
10487        if (requiredInstructionSet != null) {
10488            String adjustedAbi;
10489            if (requirer != null) {
10490                // requirer != null implies that either scannedPackage was null or that scannedPackage
10491                // did not require an ABI, in which case we have to adjust scannedPackage to match
10492                // the ABI of the set (which is the same as requirer's ABI)
10493                adjustedAbi = requirer.primaryCpuAbiString;
10494                if (scannedPackage != null) {
10495                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
10496                }
10497            } else {
10498                // requirer == null implies that we're updating all ABIs in the set to
10499                // match scannedPackage.
10500                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
10501            }
10502
10503            for (PackageSetting ps : packagesForUser) {
10504                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
10505                    if (ps.primaryCpuAbiString != null) {
10506                        continue;
10507                    }
10508
10509                    ps.primaryCpuAbiString = adjustedAbi;
10510                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
10511                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
10512                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
10513                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
10514                                + " (requirer="
10515                                + (requirer == null ? "null" : requirer.pkg.packageName)
10516                                + ", scannedPackage="
10517                                + (scannedPackage != null ? scannedPackage.packageName : "null")
10518                                + ")");
10519                        try {
10520                            mInstaller.rmdex(ps.codePathString,
10521                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
10522                        } catch (InstallerException ignored) {
10523                        }
10524                    }
10525                }
10526            }
10527        }
10528    }
10529
10530    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
10531        synchronized (mPackages) {
10532            mResolverReplaced = true;
10533            // Set up information for custom user intent resolution activity.
10534            mResolveActivity.applicationInfo = pkg.applicationInfo;
10535            mResolveActivity.name = mCustomResolverComponentName.getClassName();
10536            mResolveActivity.packageName = pkg.applicationInfo.packageName;
10537            mResolveActivity.processName = pkg.applicationInfo.packageName;
10538            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10539            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
10540                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10541            mResolveActivity.theme = 0;
10542            mResolveActivity.exported = true;
10543            mResolveActivity.enabled = true;
10544            mResolveInfo.activityInfo = mResolveActivity;
10545            mResolveInfo.priority = 0;
10546            mResolveInfo.preferredOrder = 0;
10547            mResolveInfo.match = 0;
10548            mResolveComponentName = mCustomResolverComponentName;
10549            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
10550                    mResolveComponentName);
10551        }
10552    }
10553
10554    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
10555        if (installerComponent == null) {
10556            if (DEBUG_EPHEMERAL) {
10557                Slog.d(TAG, "Clear ephemeral installer activity");
10558            }
10559            mEphemeralInstallerActivity.applicationInfo = null;
10560            return;
10561        }
10562
10563        if (DEBUG_EPHEMERAL) {
10564            Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent);
10565        }
10566        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
10567        // Set up information for ephemeral installer activity
10568        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
10569        mEphemeralInstallerActivity.name = installerComponent.getClassName();
10570        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
10571        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
10572        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10573        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
10574                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
10575        mEphemeralInstallerActivity.theme = 0;
10576        mEphemeralInstallerActivity.exported = true;
10577        mEphemeralInstallerActivity.enabled = true;
10578        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
10579        mEphemeralInstallerInfo.priority = 0;
10580        mEphemeralInstallerInfo.preferredOrder = 1;
10581        mEphemeralInstallerInfo.isDefault = true;
10582        mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
10583                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
10584    }
10585
10586    private static String calculateBundledApkRoot(final String codePathString) {
10587        final File codePath = new File(codePathString);
10588        final File codeRoot;
10589        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
10590            codeRoot = Environment.getRootDirectory();
10591        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
10592            codeRoot = Environment.getOemDirectory();
10593        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
10594            codeRoot = Environment.getVendorDirectory();
10595        } else {
10596            // Unrecognized code path; take its top real segment as the apk root:
10597            // e.g. /something/app/blah.apk => /something
10598            try {
10599                File f = codePath.getCanonicalFile();
10600                File parent = f.getParentFile();    // non-null because codePath is a file
10601                File tmp;
10602                while ((tmp = parent.getParentFile()) != null) {
10603                    f = parent;
10604                    parent = tmp;
10605                }
10606                codeRoot = f;
10607                Slog.w(TAG, "Unrecognized code path "
10608                        + codePath + " - using " + codeRoot);
10609            } catch (IOException e) {
10610                // Can't canonicalize the code path -- shenanigans?
10611                Slog.w(TAG, "Can't canonicalize code path " + codePath);
10612                return Environment.getRootDirectory().getPath();
10613            }
10614        }
10615        return codeRoot.getPath();
10616    }
10617
10618    /**
10619     * Derive and set the location of native libraries for the given package,
10620     * which varies depending on where and how the package was installed.
10621     */
10622    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
10623        final ApplicationInfo info = pkg.applicationInfo;
10624        final String codePath = pkg.codePath;
10625        final File codeFile = new File(codePath);
10626        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
10627        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
10628
10629        info.nativeLibraryRootDir = null;
10630        info.nativeLibraryRootRequiresIsa = false;
10631        info.nativeLibraryDir = null;
10632        info.secondaryNativeLibraryDir = null;
10633
10634        if (isApkFile(codeFile)) {
10635            // Monolithic install
10636            if (bundledApp) {
10637                // If "/system/lib64/apkname" exists, assume that is the per-package
10638                // native library directory to use; otherwise use "/system/lib/apkname".
10639                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
10640                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
10641                        getPrimaryInstructionSet(info));
10642
10643                // This is a bundled system app so choose the path based on the ABI.
10644                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
10645                // is just the default path.
10646                final String apkName = deriveCodePathName(codePath);
10647                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
10648                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
10649                        apkName).getAbsolutePath();
10650
10651                if (info.secondaryCpuAbi != null) {
10652                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
10653                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
10654                            secondaryLibDir, apkName).getAbsolutePath();
10655                }
10656            } else if (asecApp) {
10657                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
10658                        .getAbsolutePath();
10659            } else {
10660                final String apkName = deriveCodePathName(codePath);
10661                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
10662                        .getAbsolutePath();
10663            }
10664
10665            info.nativeLibraryRootRequiresIsa = false;
10666            info.nativeLibraryDir = info.nativeLibraryRootDir;
10667        } else {
10668            // Cluster install
10669            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
10670            info.nativeLibraryRootRequiresIsa = true;
10671
10672            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
10673                    getPrimaryInstructionSet(info)).getAbsolutePath();
10674
10675            if (info.secondaryCpuAbi != null) {
10676                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
10677                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
10678            }
10679        }
10680    }
10681
10682    /**
10683     * Calculate the abis and roots for a bundled app. These can uniquely
10684     * be determined from the contents of the system partition, i.e whether
10685     * it contains 64 or 32 bit shared libraries etc. We do not validate any
10686     * of this information, and instead assume that the system was built
10687     * sensibly.
10688     */
10689    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
10690                                           PackageSetting pkgSetting) {
10691        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
10692
10693        // If "/system/lib64/apkname" exists, assume that is the per-package
10694        // native library directory to use; otherwise use "/system/lib/apkname".
10695        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
10696        setBundledAppAbi(pkg, apkRoot, apkName);
10697        // pkgSetting might be null during rescan following uninstall of updates
10698        // to a bundled app, so accommodate that possibility.  The settings in
10699        // that case will be established later from the parsed package.
10700        //
10701        // If the settings aren't null, sync them up with what we've just derived.
10702        // note that apkRoot isn't stored in the package settings.
10703        if (pkgSetting != null) {
10704            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10705            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10706        }
10707    }
10708
10709    /**
10710     * Deduces the ABI of a bundled app and sets the relevant fields on the
10711     * parsed pkg object.
10712     *
10713     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
10714     *        under which system libraries are installed.
10715     * @param apkName the name of the installed package.
10716     */
10717    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
10718        final File codeFile = new File(pkg.codePath);
10719
10720        final boolean has64BitLibs;
10721        final boolean has32BitLibs;
10722        if (isApkFile(codeFile)) {
10723            // Monolithic install
10724            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
10725            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
10726        } else {
10727            // Cluster install
10728            final File rootDir = new File(codeFile, LIB_DIR_NAME);
10729            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
10730                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
10731                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
10732                has64BitLibs = (new File(rootDir, isa)).exists();
10733            } else {
10734                has64BitLibs = false;
10735            }
10736            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
10737                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
10738                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
10739                has32BitLibs = (new File(rootDir, isa)).exists();
10740            } else {
10741                has32BitLibs = false;
10742            }
10743        }
10744
10745        if (has64BitLibs && !has32BitLibs) {
10746            // The package has 64 bit libs, but not 32 bit libs. Its primary
10747            // ABI should be 64 bit. We can safely assume here that the bundled
10748            // native libraries correspond to the most preferred ABI in the list.
10749
10750            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10751            pkg.applicationInfo.secondaryCpuAbi = null;
10752        } else if (has32BitLibs && !has64BitLibs) {
10753            // The package has 32 bit libs but not 64 bit libs. Its primary
10754            // ABI should be 32 bit.
10755
10756            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10757            pkg.applicationInfo.secondaryCpuAbi = null;
10758        } else if (has32BitLibs && has64BitLibs) {
10759            // The application has both 64 and 32 bit bundled libraries. We check
10760            // here that the app declares multiArch support, and warn if it doesn't.
10761            //
10762            // We will be lenient here and record both ABIs. The primary will be the
10763            // ABI that's higher on the list, i.e, a device that's configured to prefer
10764            // 64 bit apps will see a 64 bit primary ABI,
10765
10766            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
10767                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
10768            }
10769
10770            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
10771                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10772                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10773            } else {
10774                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
10775                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
10776            }
10777        } else {
10778            pkg.applicationInfo.primaryCpuAbi = null;
10779            pkg.applicationInfo.secondaryCpuAbi = null;
10780        }
10781    }
10782
10783    private void killApplication(String pkgName, int appId, String reason) {
10784        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
10785    }
10786
10787    private void killApplication(String pkgName, int appId, int userId, String reason) {
10788        // Request the ActivityManager to kill the process(only for existing packages)
10789        // so that we do not end up in a confused state while the user is still using the older
10790        // version of the application while the new one gets installed.
10791        final long token = Binder.clearCallingIdentity();
10792        try {
10793            IActivityManager am = ActivityManager.getService();
10794            if (am != null) {
10795                try {
10796                    am.killApplication(pkgName, appId, userId, reason);
10797                } catch (RemoteException e) {
10798                }
10799            }
10800        } finally {
10801            Binder.restoreCallingIdentity(token);
10802        }
10803    }
10804
10805    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
10806        // Remove the parent package setting
10807        PackageSetting ps = (PackageSetting) pkg.mExtras;
10808        if (ps != null) {
10809            removePackageLI(ps, chatty);
10810        }
10811        // Remove the child package setting
10812        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10813        for (int i = 0; i < childCount; i++) {
10814            PackageParser.Package childPkg = pkg.childPackages.get(i);
10815            ps = (PackageSetting) childPkg.mExtras;
10816            if (ps != null) {
10817                removePackageLI(ps, chatty);
10818            }
10819        }
10820    }
10821
10822    void removePackageLI(PackageSetting ps, boolean chatty) {
10823        if (DEBUG_INSTALL) {
10824            if (chatty)
10825                Log.d(TAG, "Removing package " + ps.name);
10826        }
10827
10828        // writer
10829        synchronized (mPackages) {
10830            mPackages.remove(ps.name);
10831            final PackageParser.Package pkg = ps.pkg;
10832            if (pkg != null) {
10833                cleanPackageDataStructuresLILPw(pkg, chatty);
10834            }
10835        }
10836    }
10837
10838    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
10839        if (DEBUG_INSTALL) {
10840            if (chatty)
10841                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
10842        }
10843
10844        // writer
10845        synchronized (mPackages) {
10846            // Remove the parent package
10847            mPackages.remove(pkg.applicationInfo.packageName);
10848            cleanPackageDataStructuresLILPw(pkg, chatty);
10849
10850            // Remove the child packages
10851            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10852            for (int i = 0; i < childCount; i++) {
10853                PackageParser.Package childPkg = pkg.childPackages.get(i);
10854                mPackages.remove(childPkg.applicationInfo.packageName);
10855                cleanPackageDataStructuresLILPw(childPkg, chatty);
10856            }
10857        }
10858    }
10859
10860    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
10861        int N = pkg.providers.size();
10862        StringBuilder r = null;
10863        int i;
10864        for (i=0; i<N; i++) {
10865            PackageParser.Provider p = pkg.providers.get(i);
10866            mProviders.removeProvider(p);
10867            if (p.info.authority == null) {
10868
10869                /* There was another ContentProvider with this authority when
10870                 * this app was installed so this authority is null,
10871                 * Ignore it as we don't have to unregister the provider.
10872                 */
10873                continue;
10874            }
10875            String names[] = p.info.authority.split(";");
10876            for (int j = 0; j < names.length; j++) {
10877                if (mProvidersByAuthority.get(names[j]) == p) {
10878                    mProvidersByAuthority.remove(names[j]);
10879                    if (DEBUG_REMOVE) {
10880                        if (chatty)
10881                            Log.d(TAG, "Unregistered content provider: " + names[j]
10882                                    + ", className = " + p.info.name + ", isSyncable = "
10883                                    + p.info.isSyncable);
10884                    }
10885                }
10886            }
10887            if (DEBUG_REMOVE && chatty) {
10888                if (r == null) {
10889                    r = new StringBuilder(256);
10890                } else {
10891                    r.append(' ');
10892                }
10893                r.append(p.info.name);
10894            }
10895        }
10896        if (r != null) {
10897            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
10898        }
10899
10900        N = pkg.services.size();
10901        r = null;
10902        for (i=0; i<N; i++) {
10903            PackageParser.Service s = pkg.services.get(i);
10904            mServices.removeService(s);
10905            if (chatty) {
10906                if (r == null) {
10907                    r = new StringBuilder(256);
10908                } else {
10909                    r.append(' ');
10910                }
10911                r.append(s.info.name);
10912            }
10913        }
10914        if (r != null) {
10915            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
10916        }
10917
10918        N = pkg.receivers.size();
10919        r = null;
10920        for (i=0; i<N; i++) {
10921            PackageParser.Activity a = pkg.receivers.get(i);
10922            mReceivers.removeActivity(a, "receiver");
10923            if (DEBUG_REMOVE && chatty) {
10924                if (r == null) {
10925                    r = new StringBuilder(256);
10926                } else {
10927                    r.append(' ');
10928                }
10929                r.append(a.info.name);
10930            }
10931        }
10932        if (r != null) {
10933            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
10934        }
10935
10936        N = pkg.activities.size();
10937        r = null;
10938        for (i=0; i<N; i++) {
10939            PackageParser.Activity a = pkg.activities.get(i);
10940            mActivities.removeActivity(a, "activity");
10941            if (DEBUG_REMOVE && chatty) {
10942                if (r == null) {
10943                    r = new StringBuilder(256);
10944                } else {
10945                    r.append(' ');
10946                }
10947                r.append(a.info.name);
10948            }
10949        }
10950        if (r != null) {
10951            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
10952        }
10953
10954        N = pkg.permissions.size();
10955        r = null;
10956        for (i=0; i<N; i++) {
10957            PackageParser.Permission p = pkg.permissions.get(i);
10958            BasePermission bp = mSettings.mPermissions.get(p.info.name);
10959            if (bp == null) {
10960                bp = mSettings.mPermissionTrees.get(p.info.name);
10961            }
10962            if (bp != null && bp.perm == p) {
10963                bp.perm = null;
10964                if (DEBUG_REMOVE && chatty) {
10965                    if (r == null) {
10966                        r = new StringBuilder(256);
10967                    } else {
10968                        r.append(' ');
10969                    }
10970                    r.append(p.info.name);
10971                }
10972            }
10973            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10974                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
10975                if (appOpPkgs != null) {
10976                    appOpPkgs.remove(pkg.packageName);
10977                }
10978            }
10979        }
10980        if (r != null) {
10981            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
10982        }
10983
10984        N = pkg.requestedPermissions.size();
10985        r = null;
10986        for (i=0; i<N; i++) {
10987            String perm = pkg.requestedPermissions.get(i);
10988            BasePermission bp = mSettings.mPermissions.get(perm);
10989            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
10990                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
10991                if (appOpPkgs != null) {
10992                    appOpPkgs.remove(pkg.packageName);
10993                    if (appOpPkgs.isEmpty()) {
10994                        mAppOpPermissionPackages.remove(perm);
10995                    }
10996                }
10997            }
10998        }
10999        if (r != null) {
11000            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
11001        }
11002
11003        N = pkg.instrumentation.size();
11004        r = null;
11005        for (i=0; i<N; i++) {
11006            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11007            mInstrumentation.remove(a.getComponentName());
11008            if (DEBUG_REMOVE && chatty) {
11009                if (r == null) {
11010                    r = new StringBuilder(256);
11011                } else {
11012                    r.append(' ');
11013                }
11014                r.append(a.info.name);
11015            }
11016        }
11017        if (r != null) {
11018            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
11019        }
11020
11021        r = null;
11022        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
11023            // Only system apps can hold shared libraries.
11024            if (pkg.libraryNames != null) {
11025                for (i = 0; i < pkg.libraryNames.size(); i++) {
11026                    String name = pkg.libraryNames.get(i);
11027                    if (removeSharedLibraryLPw(name, 0)) {
11028                        if (DEBUG_REMOVE && chatty) {
11029                            if (r == null) {
11030                                r = new StringBuilder(256);
11031                            } else {
11032                                r.append(' ');
11033                            }
11034                            r.append(name);
11035                        }
11036                    }
11037                }
11038            }
11039        }
11040
11041        r = null;
11042
11043        // Any package can hold static shared libraries.
11044        if (pkg.staticSharedLibName != null) {
11045            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
11046                if (DEBUG_REMOVE && chatty) {
11047                    if (r == null) {
11048                        r = new StringBuilder(256);
11049                    } else {
11050                        r.append(' ');
11051                    }
11052                    r.append(pkg.staticSharedLibName);
11053                }
11054            }
11055        }
11056
11057        if (r != null) {
11058            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
11059        }
11060    }
11061
11062    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
11063        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
11064            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
11065                return true;
11066            }
11067        }
11068        return false;
11069    }
11070
11071    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
11072    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
11073    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
11074
11075    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
11076        // Update the parent permissions
11077        updatePermissionsLPw(pkg.packageName, pkg, flags);
11078        // Update the child permissions
11079        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11080        for (int i = 0; i < childCount; i++) {
11081            PackageParser.Package childPkg = pkg.childPackages.get(i);
11082            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
11083        }
11084    }
11085
11086    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
11087            int flags) {
11088        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
11089        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
11090    }
11091
11092    private void updatePermissionsLPw(String changingPkg,
11093            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
11094        // Make sure there are no dangling permission trees.
11095        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
11096        while (it.hasNext()) {
11097            final BasePermission bp = it.next();
11098            if (bp.packageSetting == null) {
11099                // We may not yet have parsed the package, so just see if
11100                // we still know about its settings.
11101                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11102            }
11103            if (bp.packageSetting == null) {
11104                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
11105                        + " from package " + bp.sourcePackage);
11106                it.remove();
11107            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11108                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11109                    Slog.i(TAG, "Removing old permission tree: " + bp.name
11110                            + " from package " + bp.sourcePackage);
11111                    flags |= UPDATE_PERMISSIONS_ALL;
11112                    it.remove();
11113                }
11114            }
11115        }
11116
11117        // Make sure all dynamic permissions have been assigned to a package,
11118        // and make sure there are no dangling permissions.
11119        it = mSettings.mPermissions.values().iterator();
11120        while (it.hasNext()) {
11121            final BasePermission bp = it.next();
11122            if (bp.type == BasePermission.TYPE_DYNAMIC) {
11123                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
11124                        + bp.name + " pkg=" + bp.sourcePackage
11125                        + " info=" + bp.pendingInfo);
11126                if (bp.packageSetting == null && bp.pendingInfo != null) {
11127                    final BasePermission tree = findPermissionTreeLP(bp.name);
11128                    if (tree != null && tree.perm != null) {
11129                        bp.packageSetting = tree.packageSetting;
11130                        bp.perm = new PackageParser.Permission(tree.perm.owner,
11131                                new PermissionInfo(bp.pendingInfo));
11132                        bp.perm.info.packageName = tree.perm.info.packageName;
11133                        bp.perm.info.name = bp.name;
11134                        bp.uid = tree.uid;
11135                    }
11136                }
11137            }
11138            if (bp.packageSetting == null) {
11139                // We may not yet have parsed the package, so just see if
11140                // we still know about its settings.
11141                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
11142            }
11143            if (bp.packageSetting == null) {
11144                Slog.w(TAG, "Removing dangling permission: " + bp.name
11145                        + " from package " + bp.sourcePackage);
11146                it.remove();
11147            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
11148                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
11149                    Slog.i(TAG, "Removing old permission: " + bp.name
11150                            + " from package " + bp.sourcePackage);
11151                    flags |= UPDATE_PERMISSIONS_ALL;
11152                    it.remove();
11153                }
11154            }
11155        }
11156
11157        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
11158        // Now update the permissions for all packages, in particular
11159        // replace the granted permissions of the system packages.
11160        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
11161            for (PackageParser.Package pkg : mPackages.values()) {
11162                if (pkg != pkgInfo) {
11163                    // Only replace for packages on requested volume
11164                    final String volumeUuid = getVolumeUuidForPackage(pkg);
11165                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
11166                            && Objects.equals(replaceVolumeUuid, volumeUuid);
11167                    grantPermissionsLPw(pkg, replace, changingPkg);
11168                }
11169            }
11170        }
11171
11172        if (pkgInfo != null) {
11173            // Only replace for packages on requested volume
11174            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
11175            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
11176                    && Objects.equals(replaceVolumeUuid, volumeUuid);
11177            grantPermissionsLPw(pkgInfo, replace, changingPkg);
11178        }
11179        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11180    }
11181
11182    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
11183            String packageOfInterest) {
11184        // IMPORTANT: There are two types of permissions: install and runtime.
11185        // Install time permissions are granted when the app is installed to
11186        // all device users and users added in the future. Runtime permissions
11187        // are granted at runtime explicitly to specific users. Normal and signature
11188        // protected permissions are install time permissions. Dangerous permissions
11189        // are install permissions if the app's target SDK is Lollipop MR1 or older,
11190        // otherwise they are runtime permissions. This function does not manage
11191        // runtime permissions except for the case an app targeting Lollipop MR1
11192        // being upgraded to target a newer SDK, in which case dangerous permissions
11193        // are transformed from install time to runtime ones.
11194
11195        final PackageSetting ps = (PackageSetting) pkg.mExtras;
11196        if (ps == null) {
11197            return;
11198        }
11199
11200        PermissionsState permissionsState = ps.getPermissionsState();
11201        PermissionsState origPermissions = permissionsState;
11202
11203        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
11204
11205        boolean runtimePermissionsRevoked = false;
11206        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
11207
11208        boolean changedInstallPermission = false;
11209
11210        if (replace) {
11211            ps.installPermissionsFixed = false;
11212            if (!ps.isSharedUser()) {
11213                origPermissions = new PermissionsState(permissionsState);
11214                permissionsState.reset();
11215            } else {
11216                // We need to know only about runtime permission changes since the
11217                // calling code always writes the install permissions state but
11218                // the runtime ones are written only if changed. The only cases of
11219                // changed runtime permissions here are promotion of an install to
11220                // runtime and revocation of a runtime from a shared user.
11221                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
11222                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
11223                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
11224                    runtimePermissionsRevoked = true;
11225                }
11226            }
11227        }
11228
11229        permissionsState.setGlobalGids(mGlobalGids);
11230
11231        final int N = pkg.requestedPermissions.size();
11232        for (int i=0; i<N; i++) {
11233            final String name = pkg.requestedPermissions.get(i);
11234            final BasePermission bp = mSettings.mPermissions.get(name);
11235
11236            if (DEBUG_INSTALL) {
11237                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
11238            }
11239
11240            if (bp == null || bp.packageSetting == null) {
11241                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11242                    Slog.w(TAG, "Unknown permission " + name
11243                            + " in package " + pkg.packageName);
11244                }
11245                continue;
11246            }
11247
11248
11249            // Limit ephemeral apps to ephemeral allowed permissions.
11250            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
11251                Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
11252                        + pkg.packageName);
11253                continue;
11254            }
11255
11256            final String perm = bp.name;
11257            boolean allowedSig = false;
11258            int grant = GRANT_DENIED;
11259
11260            // Keep track of app op permissions.
11261            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
11262                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
11263                if (pkgs == null) {
11264                    pkgs = new ArraySet<>();
11265                    mAppOpPermissionPackages.put(bp.name, pkgs);
11266                }
11267                pkgs.add(pkg.packageName);
11268            }
11269
11270            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
11271            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
11272                    >= Build.VERSION_CODES.M;
11273            switch (level) {
11274                case PermissionInfo.PROTECTION_NORMAL: {
11275                    // For all apps normal permissions are install time ones.
11276                    grant = GRANT_INSTALL;
11277                } break;
11278
11279                case PermissionInfo.PROTECTION_DANGEROUS: {
11280                    // If a permission review is required for legacy apps we represent
11281                    // their permissions as always granted runtime ones since we need
11282                    // to keep the review required permission flag per user while an
11283                    // install permission's state is shared across all users.
11284                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
11285                        // For legacy apps dangerous permissions are install time ones.
11286                        grant = GRANT_INSTALL;
11287                    } else if (origPermissions.hasInstallPermission(bp.name)) {
11288                        // For legacy apps that became modern, install becomes runtime.
11289                        grant = GRANT_UPGRADE;
11290                    } else if (mPromoteSystemApps
11291                            && isSystemApp(ps)
11292                            && mExistingSystemPackages.contains(ps.name)) {
11293                        // For legacy system apps, install becomes runtime.
11294                        // We cannot check hasInstallPermission() for system apps since those
11295                        // permissions were granted implicitly and not persisted pre-M.
11296                        grant = GRANT_UPGRADE;
11297                    } else {
11298                        // For modern apps keep runtime permissions unchanged.
11299                        grant = GRANT_RUNTIME;
11300                    }
11301                } break;
11302
11303                case PermissionInfo.PROTECTION_SIGNATURE: {
11304                    // For all apps signature permissions are install time ones.
11305                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
11306                    if (allowedSig) {
11307                        grant = GRANT_INSTALL;
11308                    }
11309                } break;
11310            }
11311
11312            if (DEBUG_INSTALL) {
11313                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
11314            }
11315
11316            if (grant != GRANT_DENIED) {
11317                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
11318                    // If this is an existing, non-system package, then
11319                    // we can't add any new permissions to it.
11320                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
11321                        // Except...  if this is a permission that was added
11322                        // to the platform (note: need to only do this when
11323                        // updating the platform).
11324                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
11325                            grant = GRANT_DENIED;
11326                        }
11327                    }
11328                }
11329
11330                switch (grant) {
11331                    case GRANT_INSTALL: {
11332                        // Revoke this as runtime permission to handle the case of
11333                        // a runtime permission being downgraded to an install one.
11334                        // Also in permission review mode we keep dangerous permissions
11335                        // for legacy apps
11336                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11337                            if (origPermissions.getRuntimePermissionState(
11338                                    bp.name, userId) != null) {
11339                                // Revoke the runtime permission and clear the flags.
11340                                origPermissions.revokeRuntimePermission(bp, userId);
11341                                origPermissions.updatePermissionFlags(bp, userId,
11342                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
11343                                // If we revoked a permission permission, we have to write.
11344                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11345                                        changedRuntimePermissionUserIds, userId);
11346                            }
11347                        }
11348                        // Grant an install permission.
11349                        if (permissionsState.grantInstallPermission(bp) !=
11350                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
11351                            changedInstallPermission = true;
11352                        }
11353                    } break;
11354
11355                    case GRANT_RUNTIME: {
11356                        // Grant previously granted runtime permissions.
11357                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11358                            PermissionState permissionState = origPermissions
11359                                    .getRuntimePermissionState(bp.name, userId);
11360                            int flags = permissionState != null
11361                                    ? permissionState.getFlags() : 0;
11362                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
11363                                // Don't propagate the permission in a permission review mode if
11364                                // the former was revoked, i.e. marked to not propagate on upgrade.
11365                                // Note that in a permission review mode install permissions are
11366                                // represented as constantly granted runtime ones since we need to
11367                                // keep a per user state associated with the permission. Also the
11368                                // revoke on upgrade flag is no longer applicable and is reset.
11369                                final boolean revokeOnUpgrade = (flags & PackageManager
11370                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
11371                                if (revokeOnUpgrade) {
11372                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
11373                                    // Since we changed the flags, we have to write.
11374                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11375                                            changedRuntimePermissionUserIds, userId);
11376                                }
11377                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
11378                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
11379                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
11380                                        // If we cannot put the permission as it was,
11381                                        // we have to write.
11382                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11383                                                changedRuntimePermissionUserIds, userId);
11384                                    }
11385                                }
11386
11387                                // If the app supports runtime permissions no need for a review.
11388                                if (mPermissionReviewRequired
11389                                        && appSupportsRuntimePermissions
11390                                        && (flags & PackageManager
11391                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
11392                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
11393                                    // Since we changed the flags, we have to write.
11394                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11395                                            changedRuntimePermissionUserIds, userId);
11396                                }
11397                            } else if (mPermissionReviewRequired
11398                                    && !appSupportsRuntimePermissions) {
11399                                // For legacy apps that need a permission review, every new
11400                                // runtime permission is granted but it is pending a review.
11401                                // We also need to review only platform defined runtime
11402                                // permissions as these are the only ones the platform knows
11403                                // how to disable the API to simulate revocation as legacy
11404                                // apps don't expect to run with revoked permissions.
11405                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
11406                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
11407                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
11408                                        // We changed the flags, hence have to write.
11409                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11410                                                changedRuntimePermissionUserIds, userId);
11411                                    }
11412                                }
11413                                if (permissionsState.grantRuntimePermission(bp, userId)
11414                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11415                                    // We changed the permission, hence have to write.
11416                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11417                                            changedRuntimePermissionUserIds, userId);
11418                                }
11419                            }
11420                            // Propagate the permission flags.
11421                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
11422                        }
11423                    } break;
11424
11425                    case GRANT_UPGRADE: {
11426                        // Grant runtime permissions for a previously held install permission.
11427                        PermissionState permissionState = origPermissions
11428                                .getInstallPermissionState(bp.name);
11429                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
11430
11431                        if (origPermissions.revokeInstallPermission(bp)
11432                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
11433                            // We will be transferring the permission flags, so clear them.
11434                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
11435                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
11436                            changedInstallPermission = true;
11437                        }
11438
11439                        // If the permission is not to be promoted to runtime we ignore it and
11440                        // also its other flags as they are not applicable to install permissions.
11441                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
11442                            for (int userId : currentUserIds) {
11443                                if (permissionsState.grantRuntimePermission(bp, userId) !=
11444                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11445                                    // Transfer the permission flags.
11446                                    permissionsState.updatePermissionFlags(bp, userId,
11447                                            flags, flags);
11448                                    // If we granted the permission, we have to write.
11449                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
11450                                            changedRuntimePermissionUserIds, userId);
11451                                }
11452                            }
11453                        }
11454                    } break;
11455
11456                    default: {
11457                        if (packageOfInterest == null
11458                                || packageOfInterest.equals(pkg.packageName)) {
11459                            Slog.w(TAG, "Not granting permission " + perm
11460                                    + " to package " + pkg.packageName
11461                                    + " because it was previously installed without");
11462                        }
11463                    } break;
11464                }
11465            } else {
11466                if (permissionsState.revokeInstallPermission(bp) !=
11467                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
11468                    // Also drop the permission flags.
11469                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
11470                            PackageManager.MASK_PERMISSION_FLAGS, 0);
11471                    changedInstallPermission = true;
11472                    Slog.i(TAG, "Un-granting permission " + perm
11473                            + " from package " + pkg.packageName
11474                            + " (protectionLevel=" + bp.protectionLevel
11475                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11476                            + ")");
11477                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
11478                    // Don't print warning for app op permissions, since it is fine for them
11479                    // not to be granted, there is a UI for the user to decide.
11480                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
11481                        Slog.w(TAG, "Not granting permission " + perm
11482                                + " to package " + pkg.packageName
11483                                + " (protectionLevel=" + bp.protectionLevel
11484                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
11485                                + ")");
11486                    }
11487                }
11488            }
11489        }
11490
11491        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
11492                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
11493            // This is the first that we have heard about this package, so the
11494            // permissions we have now selected are fixed until explicitly
11495            // changed.
11496            ps.installPermissionsFixed = true;
11497        }
11498
11499        // Persist the runtime permissions state for users with changes. If permissions
11500        // were revoked because no app in the shared user declares them we have to
11501        // write synchronously to avoid losing runtime permissions state.
11502        for (int userId : changedRuntimePermissionUserIds) {
11503            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
11504        }
11505    }
11506
11507    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
11508        boolean allowed = false;
11509        final int NP = PackageParser.NEW_PERMISSIONS.length;
11510        for (int ip=0; ip<NP; ip++) {
11511            final PackageParser.NewPermissionInfo npi
11512                    = PackageParser.NEW_PERMISSIONS[ip];
11513            if (npi.name.equals(perm)
11514                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
11515                allowed = true;
11516                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
11517                        + pkg.packageName);
11518                break;
11519            }
11520        }
11521        return allowed;
11522    }
11523
11524    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
11525            BasePermission bp, PermissionsState origPermissions) {
11526        boolean privilegedPermission = (bp.protectionLevel
11527                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
11528        boolean privappPermissionsDisable =
11529                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
11530        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
11531        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
11532        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
11533                && !platformPackage && platformPermission) {
11534            ArraySet<String> wlPermissions = SystemConfig.getInstance()
11535                    .getPrivAppPermissions(pkg.packageName);
11536            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
11537            if (!whitelisted) {
11538                Slog.w(TAG, "Privileged permission " + perm + " for package "
11539                        + pkg.packageName + " - not in privapp-permissions whitelist");
11540                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
11541                    return false;
11542                }
11543            }
11544        }
11545        boolean allowed = (compareSignatures(
11546                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
11547                        == PackageManager.SIGNATURE_MATCH)
11548                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
11549                        == PackageManager.SIGNATURE_MATCH);
11550        if (!allowed && privilegedPermission) {
11551            if (isSystemApp(pkg)) {
11552                // For updated system applications, a system permission
11553                // is granted only if it had been defined by the original application.
11554                if (pkg.isUpdatedSystemApp()) {
11555                    final PackageSetting sysPs = mSettings
11556                            .getDisabledSystemPkgLPr(pkg.packageName);
11557                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
11558                        // If the original was granted this permission, we take
11559                        // that grant decision as read and propagate it to the
11560                        // update.
11561                        if (sysPs.isPrivileged()) {
11562                            allowed = true;
11563                        }
11564                    } else {
11565                        // The system apk may have been updated with an older
11566                        // version of the one on the data partition, but which
11567                        // granted a new system permission that it didn't have
11568                        // before.  In this case we do want to allow the app to
11569                        // now get the new permission if the ancestral apk is
11570                        // privileged to get it.
11571                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
11572                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
11573                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
11574                                    allowed = true;
11575                                    break;
11576                                }
11577                            }
11578                        }
11579                        // Also if a privileged parent package on the system image or any of
11580                        // its children requested a privileged permission, the updated child
11581                        // packages can also get the permission.
11582                        if (pkg.parentPackage != null) {
11583                            final PackageSetting disabledSysParentPs = mSettings
11584                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
11585                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
11586                                    && disabledSysParentPs.isPrivileged()) {
11587                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
11588                                    allowed = true;
11589                                } else if (disabledSysParentPs.pkg.childPackages != null) {
11590                                    final int count = disabledSysParentPs.pkg.childPackages.size();
11591                                    for (int i = 0; i < count; i++) {
11592                                        PackageParser.Package disabledSysChildPkg =
11593                                                disabledSysParentPs.pkg.childPackages.get(i);
11594                                        if (isPackageRequestingPermission(disabledSysChildPkg,
11595                                                perm)) {
11596                                            allowed = true;
11597                                            break;
11598                                        }
11599                                    }
11600                                }
11601                            }
11602                        }
11603                    }
11604                } else {
11605                    allowed = isPrivilegedApp(pkg);
11606                }
11607            }
11608        }
11609        if (!allowed) {
11610            if (!allowed && (bp.protectionLevel
11611                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
11612                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
11613                // If this was a previously normal/dangerous permission that got moved
11614                // to a system permission as part of the runtime permission redesign, then
11615                // we still want to blindly grant it to old apps.
11616                allowed = true;
11617            }
11618            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
11619                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
11620                // If this permission is to be granted to the system installer and
11621                // this app is an installer, then it gets the permission.
11622                allowed = true;
11623            }
11624            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
11625                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
11626                // If this permission is to be granted to the system verifier and
11627                // this app is a verifier, then it gets the permission.
11628                allowed = true;
11629            }
11630            if (!allowed && (bp.protectionLevel
11631                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
11632                    && isSystemApp(pkg)) {
11633                // Any pre-installed system app is allowed to get this permission.
11634                allowed = true;
11635            }
11636            if (!allowed && (bp.protectionLevel
11637                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
11638                // For development permissions, a development permission
11639                // is granted only if it was already granted.
11640                allowed = origPermissions.hasInstallPermission(perm);
11641            }
11642            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
11643                    && pkg.packageName.equals(mSetupWizardPackage)) {
11644                // If this permission is to be granted to the system setup wizard and
11645                // this app is a setup wizard, then it gets the permission.
11646                allowed = true;
11647            }
11648        }
11649        return allowed;
11650    }
11651
11652    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
11653        final int permCount = pkg.requestedPermissions.size();
11654        for (int j = 0; j < permCount; j++) {
11655            String requestedPermission = pkg.requestedPermissions.get(j);
11656            if (permission.equals(requestedPermission)) {
11657                return true;
11658            }
11659        }
11660        return false;
11661    }
11662
11663    final class ActivityIntentResolver
11664            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
11665        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11666                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
11667            if (!sUserManager.exists(userId)) return null;
11668            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0)
11669                    | (visibleToEphemeral ? PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY : 0)
11670                    | (isEphemeral ? PackageManager.MATCH_EPHEMERAL : 0);
11671            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
11672                    isEphemeral, userId);
11673        }
11674
11675        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11676                int userId) {
11677            if (!sUserManager.exists(userId)) return null;
11678            mFlags = flags;
11679            return super.queryIntent(intent, resolvedType,
11680                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
11681                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
11682                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
11683        }
11684
11685        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11686                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
11687            if (!sUserManager.exists(userId)) return null;
11688            if (packageActivities == null) {
11689                return null;
11690            }
11691            mFlags = flags;
11692            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11693            final boolean vislbleToEphemeral =
11694                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
11695            final boolean isEphemeral = (flags & PackageManager.MATCH_EPHEMERAL) != 0;
11696            final int N = packageActivities.size();
11697            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
11698                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
11699
11700            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
11701            for (int i = 0; i < N; ++i) {
11702                intentFilters = packageActivities.get(i).intents;
11703                if (intentFilters != null && intentFilters.size() > 0) {
11704                    PackageParser.ActivityIntentInfo[] array =
11705                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
11706                    intentFilters.toArray(array);
11707                    listCut.add(array);
11708                }
11709            }
11710            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
11711                    vislbleToEphemeral, isEphemeral, listCut, userId);
11712        }
11713
11714        /**
11715         * Finds a privileged activity that matches the specified activity names.
11716         */
11717        private PackageParser.Activity findMatchingActivity(
11718                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
11719            for (PackageParser.Activity sysActivity : activityList) {
11720                if (sysActivity.info.name.equals(activityInfo.name)) {
11721                    return sysActivity;
11722                }
11723                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
11724                    return sysActivity;
11725                }
11726                if (sysActivity.info.targetActivity != null) {
11727                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
11728                        return sysActivity;
11729                    }
11730                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
11731                        return sysActivity;
11732                    }
11733                }
11734            }
11735            return null;
11736        }
11737
11738        public class IterGenerator<E> {
11739            public Iterator<E> generate(ActivityIntentInfo info) {
11740                return null;
11741            }
11742        }
11743
11744        public class ActionIterGenerator extends IterGenerator<String> {
11745            @Override
11746            public Iterator<String> generate(ActivityIntentInfo info) {
11747                return info.actionsIterator();
11748            }
11749        }
11750
11751        public class CategoriesIterGenerator extends IterGenerator<String> {
11752            @Override
11753            public Iterator<String> generate(ActivityIntentInfo info) {
11754                return info.categoriesIterator();
11755            }
11756        }
11757
11758        public class SchemesIterGenerator extends IterGenerator<String> {
11759            @Override
11760            public Iterator<String> generate(ActivityIntentInfo info) {
11761                return info.schemesIterator();
11762            }
11763        }
11764
11765        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
11766            @Override
11767            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
11768                return info.authoritiesIterator();
11769            }
11770        }
11771
11772        /**
11773         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
11774         * MODIFIED. Do not pass in a list that should not be changed.
11775         */
11776        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
11777                IterGenerator<T> generator, Iterator<T> searchIterator) {
11778            // loop through the set of actions; every one must be found in the intent filter
11779            while (searchIterator.hasNext()) {
11780                // we must have at least one filter in the list to consider a match
11781                if (intentList.size() == 0) {
11782                    break;
11783                }
11784
11785                final T searchAction = searchIterator.next();
11786
11787                // loop through the set of intent filters
11788                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
11789                while (intentIter.hasNext()) {
11790                    final ActivityIntentInfo intentInfo = intentIter.next();
11791                    boolean selectionFound = false;
11792
11793                    // loop through the intent filter's selection criteria; at least one
11794                    // of them must match the searched criteria
11795                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
11796                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
11797                        final T intentSelection = intentSelectionIter.next();
11798                        if (intentSelection != null && intentSelection.equals(searchAction)) {
11799                            selectionFound = true;
11800                            break;
11801                        }
11802                    }
11803
11804                    // the selection criteria wasn't found in this filter's set; this filter
11805                    // is not a potential match
11806                    if (!selectionFound) {
11807                        intentIter.remove();
11808                    }
11809                }
11810            }
11811        }
11812
11813        private boolean isProtectedAction(ActivityIntentInfo filter) {
11814            final Iterator<String> actionsIter = filter.actionsIterator();
11815            while (actionsIter != null && actionsIter.hasNext()) {
11816                final String filterAction = actionsIter.next();
11817                if (PROTECTED_ACTIONS.contains(filterAction)) {
11818                    return true;
11819                }
11820            }
11821            return false;
11822        }
11823
11824        /**
11825         * Adjusts the priority of the given intent filter according to policy.
11826         * <p>
11827         * <ul>
11828         * <li>The priority for non privileged applications is capped to '0'</li>
11829         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
11830         * <li>The priority for unbundled updates to privileged applications is capped to the
11831         *      priority defined on the system partition</li>
11832         * </ul>
11833         * <p>
11834         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
11835         * allowed to obtain any priority on any action.
11836         */
11837        private void adjustPriority(
11838                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
11839            // nothing to do; priority is fine as-is
11840            if (intent.getPriority() <= 0) {
11841                return;
11842            }
11843
11844            final ActivityInfo activityInfo = intent.activity.info;
11845            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
11846
11847            final boolean privilegedApp =
11848                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
11849            if (!privilegedApp) {
11850                // non-privileged applications can never define a priority >0
11851                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
11852                        + " package: " + applicationInfo.packageName
11853                        + " activity: " + intent.activity.className
11854                        + " origPrio: " + intent.getPriority());
11855                intent.setPriority(0);
11856                return;
11857            }
11858
11859            if (systemActivities == null) {
11860                // the system package is not disabled; we're parsing the system partition
11861                if (isProtectedAction(intent)) {
11862                    if (mDeferProtectedFilters) {
11863                        // We can't deal with these just yet. No component should ever obtain a
11864                        // >0 priority for a protected actions, with ONE exception -- the setup
11865                        // wizard. The setup wizard, however, cannot be known until we're able to
11866                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
11867                        // until all intent filters have been processed. Chicken, meet egg.
11868                        // Let the filter temporarily have a high priority and rectify the
11869                        // priorities after all system packages have been scanned.
11870                        mProtectedFilters.add(intent);
11871                        if (DEBUG_FILTERS) {
11872                            Slog.i(TAG, "Protected action; save for later;"
11873                                    + " package: " + applicationInfo.packageName
11874                                    + " activity: " + intent.activity.className
11875                                    + " origPrio: " + intent.getPriority());
11876                        }
11877                        return;
11878                    } else {
11879                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
11880                            Slog.i(TAG, "No setup wizard;"
11881                                + " All protected intents capped to priority 0");
11882                        }
11883                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
11884                            if (DEBUG_FILTERS) {
11885                                Slog.i(TAG, "Found setup wizard;"
11886                                    + " allow priority " + intent.getPriority() + ";"
11887                                    + " package: " + intent.activity.info.packageName
11888                                    + " activity: " + intent.activity.className
11889                                    + " priority: " + intent.getPriority());
11890                            }
11891                            // setup wizard gets whatever it wants
11892                            return;
11893                        }
11894                        Slog.w(TAG, "Protected action; cap priority to 0;"
11895                                + " package: " + intent.activity.info.packageName
11896                                + " activity: " + intent.activity.className
11897                                + " origPrio: " + intent.getPriority());
11898                        intent.setPriority(0);
11899                        return;
11900                    }
11901                }
11902                // privileged apps on the system image get whatever priority they request
11903                return;
11904            }
11905
11906            // privileged app unbundled update ... try to find the same activity
11907            final PackageParser.Activity foundActivity =
11908                    findMatchingActivity(systemActivities, activityInfo);
11909            if (foundActivity == null) {
11910                // this is a new activity; it cannot obtain >0 priority
11911                if (DEBUG_FILTERS) {
11912                    Slog.i(TAG, "New activity; cap priority to 0;"
11913                            + " package: " + applicationInfo.packageName
11914                            + " activity: " + intent.activity.className
11915                            + " origPrio: " + intent.getPriority());
11916                }
11917                intent.setPriority(0);
11918                return;
11919            }
11920
11921            // found activity, now check for filter equivalence
11922
11923            // a shallow copy is enough; we modify the list, not its contents
11924            final List<ActivityIntentInfo> intentListCopy =
11925                    new ArrayList<>(foundActivity.intents);
11926            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
11927
11928            // find matching action subsets
11929            final Iterator<String> actionsIterator = intent.actionsIterator();
11930            if (actionsIterator != null) {
11931                getIntentListSubset(
11932                        intentListCopy, new ActionIterGenerator(), actionsIterator);
11933                if (intentListCopy.size() == 0) {
11934                    // no more intents to match; we're not equivalent
11935                    if (DEBUG_FILTERS) {
11936                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
11937                                + " package: " + applicationInfo.packageName
11938                                + " activity: " + intent.activity.className
11939                                + " origPrio: " + intent.getPriority());
11940                    }
11941                    intent.setPriority(0);
11942                    return;
11943                }
11944            }
11945
11946            // find matching category subsets
11947            final Iterator<String> categoriesIterator = intent.categoriesIterator();
11948            if (categoriesIterator != null) {
11949                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
11950                        categoriesIterator);
11951                if (intentListCopy.size() == 0) {
11952                    // no more intents to match; we're not equivalent
11953                    if (DEBUG_FILTERS) {
11954                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
11955                                + " package: " + applicationInfo.packageName
11956                                + " activity: " + intent.activity.className
11957                                + " origPrio: " + intent.getPriority());
11958                    }
11959                    intent.setPriority(0);
11960                    return;
11961                }
11962            }
11963
11964            // find matching schemes subsets
11965            final Iterator<String> schemesIterator = intent.schemesIterator();
11966            if (schemesIterator != null) {
11967                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
11968                        schemesIterator);
11969                if (intentListCopy.size() == 0) {
11970                    // no more intents to match; we're not equivalent
11971                    if (DEBUG_FILTERS) {
11972                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
11973                                + " package: " + applicationInfo.packageName
11974                                + " activity: " + intent.activity.className
11975                                + " origPrio: " + intent.getPriority());
11976                    }
11977                    intent.setPriority(0);
11978                    return;
11979                }
11980            }
11981
11982            // find matching authorities subsets
11983            final Iterator<IntentFilter.AuthorityEntry>
11984                    authoritiesIterator = intent.authoritiesIterator();
11985            if (authoritiesIterator != null) {
11986                getIntentListSubset(intentListCopy,
11987                        new AuthoritiesIterGenerator(),
11988                        authoritiesIterator);
11989                if (intentListCopy.size() == 0) {
11990                    // no more intents to match; we're not equivalent
11991                    if (DEBUG_FILTERS) {
11992                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
11993                                + " package: " + applicationInfo.packageName
11994                                + " activity: " + intent.activity.className
11995                                + " origPrio: " + intent.getPriority());
11996                    }
11997                    intent.setPriority(0);
11998                    return;
11999                }
12000            }
12001
12002            // we found matching filter(s); app gets the max priority of all intents
12003            int cappedPriority = 0;
12004            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12005                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12006            }
12007            if (intent.getPriority() > cappedPriority) {
12008                if (DEBUG_FILTERS) {
12009                    Slog.i(TAG, "Found matching filter(s);"
12010                            + " cap priority to " + cappedPriority + ";"
12011                            + " package: " + applicationInfo.packageName
12012                            + " activity: " + intent.activity.className
12013                            + " origPrio: " + intent.getPriority());
12014                }
12015                intent.setPriority(cappedPriority);
12016                return;
12017            }
12018            // all this for nothing; the requested priority was <= what was on the system
12019        }
12020
12021        public final void addActivity(PackageParser.Activity a, String type) {
12022            mActivities.put(a.getComponentName(), a);
12023            if (DEBUG_SHOW_INFO)
12024                Log.v(
12025                TAG, "  " + type + " " +
12026                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12027            if (DEBUG_SHOW_INFO)
12028                Log.v(TAG, "    Class=" + a.info.name);
12029            final int NI = a.intents.size();
12030            for (int j=0; j<NI; j++) {
12031                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12032                if ("activity".equals(type)) {
12033                    final PackageSetting ps =
12034                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12035                    final List<PackageParser.Activity> systemActivities =
12036                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12037                    adjustPriority(systemActivities, intent);
12038                }
12039                if (DEBUG_SHOW_INFO) {
12040                    Log.v(TAG, "    IntentFilter:");
12041                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12042                }
12043                if (!intent.debugCheck()) {
12044                    Log.w(TAG, "==> For Activity " + a.info.name);
12045                }
12046                addFilter(intent);
12047            }
12048        }
12049
12050        public final void removeActivity(PackageParser.Activity a, String type) {
12051            mActivities.remove(a.getComponentName());
12052            if (DEBUG_SHOW_INFO) {
12053                Log.v(TAG, "  " + type + " "
12054                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12055                                : a.info.name) + ":");
12056                Log.v(TAG, "    Class=" + a.info.name);
12057            }
12058            final int NI = a.intents.size();
12059            for (int j=0; j<NI; j++) {
12060                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12061                if (DEBUG_SHOW_INFO) {
12062                    Log.v(TAG, "    IntentFilter:");
12063                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12064                }
12065                removeFilter(intent);
12066            }
12067        }
12068
12069        @Override
12070        protected boolean allowFilterResult(
12071                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12072            ActivityInfo filterAi = filter.activity.info;
12073            for (int i=dest.size()-1; i>=0; i--) {
12074                ActivityInfo destAi = dest.get(i).activityInfo;
12075                if (destAi.name == filterAi.name
12076                        && destAi.packageName == filterAi.packageName) {
12077                    return false;
12078                }
12079            }
12080            return true;
12081        }
12082
12083        @Override
12084        protected ActivityIntentInfo[] newArray(int size) {
12085            return new ActivityIntentInfo[size];
12086        }
12087
12088        @Override
12089        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12090            if (!sUserManager.exists(userId)) return true;
12091            PackageParser.Package p = filter.activity.owner;
12092            if (p != null) {
12093                PackageSetting ps = (PackageSetting)p.mExtras;
12094                if (ps != null) {
12095                    // System apps are never considered stopped for purposes of
12096                    // filtering, because there may be no way for the user to
12097                    // actually re-launch them.
12098                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12099                            && ps.getStopped(userId);
12100                }
12101            }
12102            return false;
12103        }
12104
12105        @Override
12106        protected boolean isPackageForFilter(String packageName,
12107                PackageParser.ActivityIntentInfo info) {
12108            return packageName.equals(info.activity.owner.packageName);
12109        }
12110
12111        @Override
12112        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12113                int match, int userId) {
12114            if (!sUserManager.exists(userId)) return null;
12115            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12116                return null;
12117            }
12118            final PackageParser.Activity activity = info.activity;
12119            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12120            if (ps == null) {
12121                return null;
12122            }
12123            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
12124                    ps.readUserState(userId), userId);
12125            if (ai == null) {
12126                return null;
12127            }
12128            final ResolveInfo res = new ResolveInfo();
12129            res.activityInfo = ai;
12130            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12131                res.filter = info;
12132            }
12133            if (info != null) {
12134                res.handleAllWebDataURI = info.handleAllWebDataURI();
12135            }
12136            res.priority = info.getPriority();
12137            res.preferredOrder = activity.owner.mPreferredOrder;
12138            //System.out.println("Result: " + res.activityInfo.className +
12139            //                   " = " + res.priority);
12140            res.match = match;
12141            res.isDefault = info.hasDefault;
12142            res.labelRes = info.labelRes;
12143            res.nonLocalizedLabel = info.nonLocalizedLabel;
12144            if (userNeedsBadging(userId)) {
12145                res.noResourceId = true;
12146            } else {
12147                res.icon = info.icon;
12148            }
12149            res.iconResourceId = info.icon;
12150            res.system = res.activityInfo.applicationInfo.isSystemApp();
12151            return res;
12152        }
12153
12154        @Override
12155        protected void sortResults(List<ResolveInfo> results) {
12156            Collections.sort(results, mResolvePrioritySorter);
12157        }
12158
12159        @Override
12160        protected void dumpFilter(PrintWriter out, String prefix,
12161                PackageParser.ActivityIntentInfo filter) {
12162            out.print(prefix); out.print(
12163                    Integer.toHexString(System.identityHashCode(filter.activity)));
12164                    out.print(' ');
12165                    filter.activity.printComponentShortName(out);
12166                    out.print(" filter ");
12167                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12168        }
12169
12170        @Override
12171        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12172            return filter.activity;
12173        }
12174
12175        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12176            PackageParser.Activity activity = (PackageParser.Activity)label;
12177            out.print(prefix); out.print(
12178                    Integer.toHexString(System.identityHashCode(activity)));
12179                    out.print(' ');
12180                    activity.printComponentShortName(out);
12181            if (count > 1) {
12182                out.print(" ("); out.print(count); out.print(" filters)");
12183            }
12184            out.println();
12185        }
12186
12187        // Keys are String (activity class name), values are Activity.
12188        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12189                = new ArrayMap<ComponentName, PackageParser.Activity>();
12190        private int mFlags;
12191    }
12192
12193    private final class ServiceIntentResolver
12194            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12195        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12196                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
12197            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12198            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
12199                    isEphemeral, userId);
12200        }
12201
12202        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12203                int userId) {
12204            if (!sUserManager.exists(userId)) return null;
12205            mFlags = flags;
12206            return super.queryIntent(intent, resolvedType,
12207                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12208                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
12209                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
12210        }
12211
12212        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12213                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12214            if (!sUserManager.exists(userId)) return null;
12215            if (packageServices == null) {
12216                return null;
12217            }
12218            mFlags = flags;
12219            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12220            final boolean vislbleToEphemeral =
12221                    (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
12222            final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0;
12223            final int N = packageServices.size();
12224            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12225                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12226
12227            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12228            for (int i = 0; i < N; ++i) {
12229                intentFilters = packageServices.get(i).intents;
12230                if (intentFilters != null && intentFilters.size() > 0) {
12231                    PackageParser.ServiceIntentInfo[] array =
12232                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12233                    intentFilters.toArray(array);
12234                    listCut.add(array);
12235                }
12236            }
12237            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
12238                    vislbleToEphemeral, isEphemeral, listCut, userId);
12239        }
12240
12241        public final void addService(PackageParser.Service s) {
12242            mServices.put(s.getComponentName(), s);
12243            if (DEBUG_SHOW_INFO) {
12244                Log.v(TAG, "  "
12245                        + (s.info.nonLocalizedLabel != null
12246                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12247                Log.v(TAG, "    Class=" + s.info.name);
12248            }
12249            final int NI = s.intents.size();
12250            int j;
12251            for (j=0; j<NI; j++) {
12252                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12253                if (DEBUG_SHOW_INFO) {
12254                    Log.v(TAG, "    IntentFilter:");
12255                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12256                }
12257                if (!intent.debugCheck()) {
12258                    Log.w(TAG, "==> For Service " + s.info.name);
12259                }
12260                addFilter(intent);
12261            }
12262        }
12263
12264        public final void removeService(PackageParser.Service s) {
12265            mServices.remove(s.getComponentName());
12266            if (DEBUG_SHOW_INFO) {
12267                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12268                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12269                Log.v(TAG, "    Class=" + s.info.name);
12270            }
12271            final int NI = s.intents.size();
12272            int j;
12273            for (j=0; j<NI; j++) {
12274                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12275                if (DEBUG_SHOW_INFO) {
12276                    Log.v(TAG, "    IntentFilter:");
12277                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12278                }
12279                removeFilter(intent);
12280            }
12281        }
12282
12283        @Override
12284        protected boolean allowFilterResult(
12285                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12286            ServiceInfo filterSi = filter.service.info;
12287            for (int i=dest.size()-1; i>=0; i--) {
12288                ServiceInfo destAi = dest.get(i).serviceInfo;
12289                if (destAi.name == filterSi.name
12290                        && destAi.packageName == filterSi.packageName) {
12291                    return false;
12292                }
12293            }
12294            return true;
12295        }
12296
12297        @Override
12298        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12299            return new PackageParser.ServiceIntentInfo[size];
12300        }
12301
12302        @Override
12303        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12304            if (!sUserManager.exists(userId)) return true;
12305            PackageParser.Package p = filter.service.owner;
12306            if (p != null) {
12307                PackageSetting ps = (PackageSetting)p.mExtras;
12308                if (ps != null) {
12309                    // System apps are never considered stopped for purposes of
12310                    // filtering, because there may be no way for the user to
12311                    // actually re-launch them.
12312                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12313                            && ps.getStopped(userId);
12314                }
12315            }
12316            return false;
12317        }
12318
12319        @Override
12320        protected boolean isPackageForFilter(String packageName,
12321                PackageParser.ServiceIntentInfo info) {
12322            return packageName.equals(info.service.owner.packageName);
12323        }
12324
12325        @Override
12326        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12327                int match, int userId) {
12328            if (!sUserManager.exists(userId)) return null;
12329            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12330            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12331                return null;
12332            }
12333            final PackageParser.Service service = info.service;
12334            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12335            if (ps == null) {
12336                return null;
12337            }
12338            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12339                    ps.readUserState(userId), userId);
12340            if (si == null) {
12341                return null;
12342            }
12343            final ResolveInfo res = new ResolveInfo();
12344            res.serviceInfo = si;
12345            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12346                res.filter = filter;
12347            }
12348            res.priority = info.getPriority();
12349            res.preferredOrder = service.owner.mPreferredOrder;
12350            res.match = match;
12351            res.isDefault = info.hasDefault;
12352            res.labelRes = info.labelRes;
12353            res.nonLocalizedLabel = info.nonLocalizedLabel;
12354            res.icon = info.icon;
12355            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12356            return res;
12357        }
12358
12359        @Override
12360        protected void sortResults(List<ResolveInfo> results) {
12361            Collections.sort(results, mResolvePrioritySorter);
12362        }
12363
12364        @Override
12365        protected void dumpFilter(PrintWriter out, String prefix,
12366                PackageParser.ServiceIntentInfo filter) {
12367            out.print(prefix); out.print(
12368                    Integer.toHexString(System.identityHashCode(filter.service)));
12369                    out.print(' ');
12370                    filter.service.printComponentShortName(out);
12371                    out.print(" filter ");
12372                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12373        }
12374
12375        @Override
12376        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12377            return filter.service;
12378        }
12379
12380        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12381            PackageParser.Service service = (PackageParser.Service)label;
12382            out.print(prefix); out.print(
12383                    Integer.toHexString(System.identityHashCode(service)));
12384                    out.print(' ');
12385                    service.printComponentShortName(out);
12386            if (count > 1) {
12387                out.print(" ("); out.print(count); out.print(" filters)");
12388            }
12389            out.println();
12390        }
12391
12392//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12393//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12394//            final List<ResolveInfo> retList = Lists.newArrayList();
12395//            while (i.hasNext()) {
12396//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12397//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12398//                    retList.add(resolveInfo);
12399//                }
12400//            }
12401//            return retList;
12402//        }
12403
12404        // Keys are String (activity class name), values are Activity.
12405        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12406                = new ArrayMap<ComponentName, PackageParser.Service>();
12407        private int mFlags;
12408    }
12409
12410    private final class ProviderIntentResolver
12411            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
12412        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12413                boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) {
12414            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12415            return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral,
12416                    isEphemeral, userId);
12417        }
12418
12419        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12420                int userId) {
12421            if (!sUserManager.exists(userId))
12422                return null;
12423            mFlags = flags;
12424            return super.queryIntent(intent, resolvedType,
12425                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12426                    (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0,
12427                    (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId);
12428        }
12429
12430        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12431                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
12432            if (!sUserManager.exists(userId))
12433                return null;
12434            if (packageProviders == null) {
12435                return null;
12436            }
12437            mFlags = flags;
12438            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12439            final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0;
12440            final boolean vislbleToEphemeral =
12441                    (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0;
12442            final int N = packageProviders.size();
12443            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
12444                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
12445
12446            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
12447            for (int i = 0; i < N; ++i) {
12448                intentFilters = packageProviders.get(i).intents;
12449                if (intentFilters != null && intentFilters.size() > 0) {
12450                    PackageParser.ProviderIntentInfo[] array =
12451                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
12452                    intentFilters.toArray(array);
12453                    listCut.add(array);
12454                }
12455            }
12456            return super.queryIntentFromList(intent, resolvedType, defaultOnly,
12457                    vislbleToEphemeral, isEphemeral, listCut, userId);
12458        }
12459
12460        public final void addProvider(PackageParser.Provider p) {
12461            if (mProviders.containsKey(p.getComponentName())) {
12462                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
12463                return;
12464            }
12465
12466            mProviders.put(p.getComponentName(), p);
12467            if (DEBUG_SHOW_INFO) {
12468                Log.v(TAG, "  "
12469                        + (p.info.nonLocalizedLabel != null
12470                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
12471                Log.v(TAG, "    Class=" + p.info.name);
12472            }
12473            final int NI = p.intents.size();
12474            int j;
12475            for (j = 0; j < NI; j++) {
12476                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12477                if (DEBUG_SHOW_INFO) {
12478                    Log.v(TAG, "    IntentFilter:");
12479                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12480                }
12481                if (!intent.debugCheck()) {
12482                    Log.w(TAG, "==> For Provider " + p.info.name);
12483                }
12484                addFilter(intent);
12485            }
12486        }
12487
12488        public final void removeProvider(PackageParser.Provider p) {
12489            mProviders.remove(p.getComponentName());
12490            if (DEBUG_SHOW_INFO) {
12491                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
12492                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
12493                Log.v(TAG, "    Class=" + p.info.name);
12494            }
12495            final int NI = p.intents.size();
12496            int j;
12497            for (j = 0; j < NI; j++) {
12498                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
12499                if (DEBUG_SHOW_INFO) {
12500                    Log.v(TAG, "    IntentFilter:");
12501                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12502                }
12503                removeFilter(intent);
12504            }
12505        }
12506
12507        @Override
12508        protected boolean allowFilterResult(
12509                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
12510            ProviderInfo filterPi = filter.provider.info;
12511            for (int i = dest.size() - 1; i >= 0; i--) {
12512                ProviderInfo destPi = dest.get(i).providerInfo;
12513                if (destPi.name == filterPi.name
12514                        && destPi.packageName == filterPi.packageName) {
12515                    return false;
12516                }
12517            }
12518            return true;
12519        }
12520
12521        @Override
12522        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
12523            return new PackageParser.ProviderIntentInfo[size];
12524        }
12525
12526        @Override
12527        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
12528            if (!sUserManager.exists(userId))
12529                return true;
12530            PackageParser.Package p = filter.provider.owner;
12531            if (p != null) {
12532                PackageSetting ps = (PackageSetting) p.mExtras;
12533                if (ps != null) {
12534                    // System apps are never considered stopped for purposes of
12535                    // filtering, because there may be no way for the user to
12536                    // actually re-launch them.
12537                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12538                            && ps.getStopped(userId);
12539                }
12540            }
12541            return false;
12542        }
12543
12544        @Override
12545        protected boolean isPackageForFilter(String packageName,
12546                PackageParser.ProviderIntentInfo info) {
12547            return packageName.equals(info.provider.owner.packageName);
12548        }
12549
12550        @Override
12551        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
12552                int match, int userId) {
12553            if (!sUserManager.exists(userId))
12554                return null;
12555            final PackageParser.ProviderIntentInfo info = filter;
12556            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
12557                return null;
12558            }
12559            final PackageParser.Provider provider = info.provider;
12560            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
12561            if (ps == null) {
12562                return null;
12563            }
12564            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
12565                    ps.readUserState(userId), userId);
12566            if (pi == null) {
12567                return null;
12568            }
12569            final ResolveInfo res = new ResolveInfo();
12570            res.providerInfo = pi;
12571            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
12572                res.filter = filter;
12573            }
12574            res.priority = info.getPriority();
12575            res.preferredOrder = provider.owner.mPreferredOrder;
12576            res.match = match;
12577            res.isDefault = info.hasDefault;
12578            res.labelRes = info.labelRes;
12579            res.nonLocalizedLabel = info.nonLocalizedLabel;
12580            res.icon = info.icon;
12581            res.system = res.providerInfo.applicationInfo.isSystemApp();
12582            return res;
12583        }
12584
12585        @Override
12586        protected void sortResults(List<ResolveInfo> results) {
12587            Collections.sort(results, mResolvePrioritySorter);
12588        }
12589
12590        @Override
12591        protected void dumpFilter(PrintWriter out, String prefix,
12592                PackageParser.ProviderIntentInfo filter) {
12593            out.print(prefix);
12594            out.print(
12595                    Integer.toHexString(System.identityHashCode(filter.provider)));
12596            out.print(' ');
12597            filter.provider.printComponentShortName(out);
12598            out.print(" filter ");
12599            out.println(Integer.toHexString(System.identityHashCode(filter)));
12600        }
12601
12602        @Override
12603        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
12604            return filter.provider;
12605        }
12606
12607        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12608            PackageParser.Provider provider = (PackageParser.Provider)label;
12609            out.print(prefix); out.print(
12610                    Integer.toHexString(System.identityHashCode(provider)));
12611                    out.print(' ');
12612                    provider.printComponentShortName(out);
12613            if (count > 1) {
12614                out.print(" ("); out.print(count); out.print(" filters)");
12615            }
12616            out.println();
12617        }
12618
12619        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
12620                = new ArrayMap<ComponentName, PackageParser.Provider>();
12621        private int mFlags;
12622    }
12623
12624    static final class EphemeralIntentResolver
12625            extends IntentResolver<EphemeralResponse, EphemeralResponse> {
12626        /**
12627         * The result that has the highest defined order. Ordering applies on a
12628         * per-package basis. Mapping is from package name to Pair of order and
12629         * EphemeralResolveInfo.
12630         * <p>
12631         * NOTE: This is implemented as a field variable for convenience and efficiency.
12632         * By having a field variable, we're able to track filter ordering as soon as
12633         * a non-zero order is defined. Otherwise, multiple loops across the result set
12634         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
12635         * this needs to be contained entirely within {@link #filterResults()}.
12636         */
12637        final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>();
12638
12639        @Override
12640        protected EphemeralResponse[] newArray(int size) {
12641            return new EphemeralResponse[size];
12642        }
12643
12644        @Override
12645        protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) {
12646            return true;
12647        }
12648
12649        @Override
12650        protected EphemeralResponse newResult(EphemeralResponse responseObj, int match,
12651                int userId) {
12652            if (!sUserManager.exists(userId)) {
12653                return null;
12654            }
12655            final String packageName = responseObj.resolveInfo.getPackageName();
12656            final Integer order = responseObj.getOrder();
12657            final Pair<Integer, EphemeralResolveInfo> lastOrderResult =
12658                    mOrderResult.get(packageName);
12659            // ordering is enabled and this item's order isn't high enough
12660            if (lastOrderResult != null && lastOrderResult.first >= order) {
12661                return null;
12662            }
12663            final EphemeralResolveInfo res = responseObj.resolveInfo;
12664            if (order > 0) {
12665                // non-zero order, enable ordering
12666                mOrderResult.put(packageName, new Pair<>(order, res));
12667            }
12668            return responseObj;
12669        }
12670
12671        @Override
12672        protected void filterResults(List<EphemeralResponse> results) {
12673            // only do work if ordering is enabled [most of the time it won't be]
12674            if (mOrderResult.size() == 0) {
12675                return;
12676            }
12677            int resultSize = results.size();
12678            for (int i = 0; i < resultSize; i++) {
12679                final EphemeralResolveInfo info = results.get(i).resolveInfo;
12680                final String packageName = info.getPackageName();
12681                final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName);
12682                if (savedInfo == null) {
12683                    // package doesn't having ordering
12684                    continue;
12685                }
12686                if (savedInfo.second == info) {
12687                    // circled back to the highest ordered item; remove from order list
12688                    mOrderResult.remove(savedInfo);
12689                    if (mOrderResult.size() == 0) {
12690                        // no more ordered items
12691                        break;
12692                    }
12693                    continue;
12694                }
12695                // item has a worse order, remove it from the result list
12696                results.remove(i);
12697                resultSize--;
12698                i--;
12699            }
12700        }
12701    }
12702
12703    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
12704            new Comparator<ResolveInfo>() {
12705        public int compare(ResolveInfo r1, ResolveInfo r2) {
12706            int v1 = r1.priority;
12707            int v2 = r2.priority;
12708            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
12709            if (v1 != v2) {
12710                return (v1 > v2) ? -1 : 1;
12711            }
12712            v1 = r1.preferredOrder;
12713            v2 = r2.preferredOrder;
12714            if (v1 != v2) {
12715                return (v1 > v2) ? -1 : 1;
12716            }
12717            if (r1.isDefault != r2.isDefault) {
12718                return r1.isDefault ? -1 : 1;
12719            }
12720            v1 = r1.match;
12721            v2 = r2.match;
12722            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
12723            if (v1 != v2) {
12724                return (v1 > v2) ? -1 : 1;
12725            }
12726            if (r1.system != r2.system) {
12727                return r1.system ? -1 : 1;
12728            }
12729            if (r1.activityInfo != null) {
12730                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
12731            }
12732            if (r1.serviceInfo != null) {
12733                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
12734            }
12735            if (r1.providerInfo != null) {
12736                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
12737            }
12738            return 0;
12739        }
12740    };
12741
12742    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
12743            new Comparator<ProviderInfo>() {
12744        public int compare(ProviderInfo p1, ProviderInfo p2) {
12745            final int v1 = p1.initOrder;
12746            final int v2 = p2.initOrder;
12747            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
12748        }
12749    };
12750
12751    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12752            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12753            final int[] userIds) {
12754        mHandler.post(new Runnable() {
12755            @Override
12756            public void run() {
12757                try {
12758                    final IActivityManager am = ActivityManager.getService();
12759                    if (am == null) return;
12760                    final int[] resolvedUserIds;
12761                    if (userIds == null) {
12762                        resolvedUserIds = am.getRunningUserIds();
12763                    } else {
12764                        resolvedUserIds = userIds;
12765                    }
12766                    for (int id : resolvedUserIds) {
12767                        final Intent intent = new Intent(action,
12768                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
12769                        if (extras != null) {
12770                            intent.putExtras(extras);
12771                        }
12772                        if (targetPkg != null) {
12773                            intent.setPackage(targetPkg);
12774                        }
12775                        // Modify the UID when posting to other users
12776                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
12777                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
12778                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
12779                            intent.putExtra(Intent.EXTRA_UID, uid);
12780                        }
12781                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
12782                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
12783                        if (DEBUG_BROADCASTS) {
12784                            RuntimeException here = new RuntimeException("here");
12785                            here.fillInStackTrace();
12786                            Slog.d(TAG, "Sending to user " + id + ": "
12787                                    + intent.toShortString(false, true, false, false)
12788                                    + " " + intent.getExtras(), here);
12789                        }
12790                        am.broadcastIntent(null, intent, null, finishedReceiver,
12791                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
12792                                null, finishedReceiver != null, false, id);
12793                    }
12794                } catch (RemoteException ex) {
12795                }
12796            }
12797        });
12798    }
12799
12800    /**
12801     * Check if the external storage media is available. This is true if there
12802     * is a mounted external storage medium or if the external storage is
12803     * emulated.
12804     */
12805    private boolean isExternalMediaAvailable() {
12806        return mMediaMounted || Environment.isExternalStorageEmulated();
12807    }
12808
12809    @Override
12810    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
12811        // writer
12812        synchronized (mPackages) {
12813            if (!isExternalMediaAvailable()) {
12814                // If the external storage is no longer mounted at this point,
12815                // the caller may not have been able to delete all of this
12816                // packages files and can not delete any more.  Bail.
12817                return null;
12818            }
12819            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
12820            if (lastPackage != null) {
12821                pkgs.remove(lastPackage);
12822            }
12823            if (pkgs.size() > 0) {
12824                return pkgs.get(0);
12825            }
12826        }
12827        return null;
12828    }
12829
12830    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
12831        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
12832                userId, andCode ? 1 : 0, packageName);
12833        if (mSystemReady) {
12834            msg.sendToTarget();
12835        } else {
12836            if (mPostSystemReadyMessages == null) {
12837                mPostSystemReadyMessages = new ArrayList<>();
12838            }
12839            mPostSystemReadyMessages.add(msg);
12840        }
12841    }
12842
12843    void startCleaningPackages() {
12844        // reader
12845        if (!isExternalMediaAvailable()) {
12846            return;
12847        }
12848        synchronized (mPackages) {
12849            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
12850                return;
12851            }
12852        }
12853        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
12854        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
12855        IActivityManager am = ActivityManager.getService();
12856        if (am != null) {
12857            try {
12858                am.startService(null, intent, null, -1, null, mContext.getOpPackageName(),
12859                        UserHandle.USER_SYSTEM);
12860            } catch (RemoteException e) {
12861            }
12862        }
12863    }
12864
12865    @Override
12866    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
12867            int installFlags, String installerPackageName, int userId) {
12868        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
12869
12870        final int callingUid = Binder.getCallingUid();
12871        enforceCrossUserPermission(callingUid, userId,
12872                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
12873
12874        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
12875            try {
12876                if (observer != null) {
12877                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
12878                }
12879            } catch (RemoteException re) {
12880            }
12881            return;
12882        }
12883
12884        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
12885            installFlags |= PackageManager.INSTALL_FROM_ADB;
12886
12887        } else {
12888            // Caller holds INSTALL_PACKAGES permission, so we're less strict
12889            // about installerPackageName.
12890
12891            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
12892            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
12893        }
12894
12895        UserHandle user;
12896        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
12897            user = UserHandle.ALL;
12898        } else {
12899            user = new UserHandle(userId);
12900        }
12901
12902        // Only system components can circumvent runtime permissions when installing.
12903        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
12904                && mContext.checkCallingOrSelfPermission(Manifest.permission
12905                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
12906            throw new SecurityException("You need the "
12907                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
12908                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
12909        }
12910
12911        final File originFile = new File(originPath);
12912        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
12913
12914        final Message msg = mHandler.obtainMessage(INIT_COPY);
12915        final VerificationInfo verificationInfo = new VerificationInfo(
12916                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
12917        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
12918                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
12919                null /*packageAbiOverride*/, null /*grantedPermissions*/,
12920                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
12921        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
12922        msg.obj = params;
12923
12924        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
12925                System.identityHashCode(msg.obj));
12926        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
12927                System.identityHashCode(msg.obj));
12928
12929        mHandler.sendMessage(msg);
12930    }
12931
12932
12933    /**
12934     * Ensure that the install reason matches what we know about the package installer (e.g. whether
12935     * it is acting on behalf on an enterprise or the user).
12936     *
12937     * Note that the ordering of the conditionals in this method is important. The checks we perform
12938     * are as follows, in this order:
12939     *
12940     * 1) If the install is being performed by a system app, we can trust the app to have set the
12941     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
12942     *    what it is.
12943     * 2) If the install is being performed by a device or profile owner app, the install reason
12944     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
12945     *    set the install reason correctly. If the app targets an older SDK version where install
12946     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
12947     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
12948     * 3) In all other cases, the install is being performed by a regular app that is neither part
12949     *    of the system nor a device or profile owner. We have no reason to believe that this app is
12950     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
12951     *    set to enterprise policy and if so, change it to unknown instead.
12952     */
12953    private int fixUpInstallReason(String installerPackageName, int installerUid,
12954            int installReason) {
12955        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
12956                == PERMISSION_GRANTED) {
12957            // If the install is being performed by a system app, we trust that app to have set the
12958            // install reason correctly.
12959            return installReason;
12960        }
12961
12962        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12963            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12964        if (dpm != null) {
12965            ComponentName owner = null;
12966            try {
12967                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
12968                if (owner == null) {
12969                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
12970                }
12971            } catch (RemoteException e) {
12972            }
12973            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
12974                // If the install is being performed by a device or profile owner, the install
12975                // reason should be enterprise policy.
12976                return PackageManager.INSTALL_REASON_POLICY;
12977            }
12978        }
12979
12980        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
12981            // If the install is being performed by a regular app (i.e. neither system app nor
12982            // device or profile owner), we have no reason to believe that the app is acting on
12983            // behalf of an enterprise. If the app set the install reason to enterprise policy,
12984            // change it to unknown instead.
12985            return PackageManager.INSTALL_REASON_UNKNOWN;
12986        }
12987
12988        // If the install is being performed by a regular app and the install reason was set to any
12989        // value but enterprise policy, leave the install reason unchanged.
12990        return installReason;
12991    }
12992
12993    void installStage(String packageName, File stagedDir, String stagedCid,
12994            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
12995            String installerPackageName, int installerUid, UserHandle user,
12996            Certificate[][] certificates) {
12997        if (DEBUG_EPHEMERAL) {
12998            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12999                Slog.d(TAG, "Ephemeral install of " + packageName);
13000            }
13001        }
13002        final VerificationInfo verificationInfo = new VerificationInfo(
13003                sessionParams.originatingUri, sessionParams.referrerUri,
13004                sessionParams.originatingUid, installerUid);
13005
13006        final OriginInfo origin;
13007        if (stagedDir != null) {
13008            origin = OriginInfo.fromStagedFile(stagedDir);
13009        } else {
13010            origin = OriginInfo.fromStagedContainer(stagedCid);
13011        }
13012
13013        final Message msg = mHandler.obtainMessage(INIT_COPY);
13014        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13015                sessionParams.installReason);
13016        final InstallParams params = new InstallParams(origin, null, observer,
13017                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13018                verificationInfo, user, sessionParams.abiOverride,
13019                sessionParams.grantedRuntimePermissions, certificates, installReason);
13020        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13021        msg.obj = params;
13022
13023        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13024                System.identityHashCode(msg.obj));
13025        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13026                System.identityHashCode(msg.obj));
13027
13028        mHandler.sendMessage(msg);
13029    }
13030
13031    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13032            int userId) {
13033        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13034        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
13035    }
13036
13037    private void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
13038            int appId, int... userIds) {
13039        if (ArrayUtils.isEmpty(userIds)) {
13040            return;
13041        }
13042        Bundle extras = new Bundle(1);
13043        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13044        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
13045
13046        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13047                packageName, extras, 0, null, null, userIds);
13048        if (isSystem) {
13049            mHandler.post(() -> {
13050                        for (int userId : userIds) {
13051                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
13052                        }
13053                    }
13054            );
13055        }
13056    }
13057
13058    /**
13059     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13060     * automatically without needing an explicit launch.
13061     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13062     */
13063    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
13064        // If user is not running, the app didn't miss any broadcast
13065        if (!mUserManagerInternal.isUserRunning(userId)) {
13066            return;
13067        }
13068        final IActivityManager am = ActivityManager.getService();
13069        try {
13070            // Deliver LOCKED_BOOT_COMPLETED first
13071            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13072                    .setPackage(packageName);
13073            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13074            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13075                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13076
13077            // Deliver BOOT_COMPLETED only if user is unlocked
13078            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13079                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13080                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13081                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13082            }
13083        } catch (RemoteException e) {
13084            throw e.rethrowFromSystemServer();
13085        }
13086    }
13087
13088    @Override
13089    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13090            int userId) {
13091        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13092        PackageSetting pkgSetting;
13093        final int uid = Binder.getCallingUid();
13094        enforceCrossUserPermission(uid, userId,
13095                true /* requireFullPermission */, true /* checkShell */,
13096                "setApplicationHiddenSetting for user " + userId);
13097
13098        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13099            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13100            return false;
13101        }
13102
13103        long callingId = Binder.clearCallingIdentity();
13104        try {
13105            boolean sendAdded = false;
13106            boolean sendRemoved = false;
13107            // writer
13108            synchronized (mPackages) {
13109                pkgSetting = mSettings.mPackages.get(packageName);
13110                if (pkgSetting == null) {
13111                    return false;
13112                }
13113                // Do not allow "android" is being disabled
13114                if ("android".equals(packageName)) {
13115                    Slog.w(TAG, "Cannot hide package: android");
13116                    return false;
13117                }
13118                // Cannot hide static shared libs as they are considered
13119                // a part of the using app (emulating static linking). Also
13120                // static libs are installed always on internal storage.
13121                PackageParser.Package pkg = mPackages.get(packageName);
13122                if (pkg != null && pkg.staticSharedLibName != null) {
13123                    Slog.w(TAG, "Cannot hide package: " + packageName
13124                            + " providing static shared library: "
13125                            + pkg.staticSharedLibName);
13126                    return false;
13127                }
13128                // Only allow protected packages to hide themselves.
13129                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
13130                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13131                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13132                    return false;
13133                }
13134
13135                if (pkgSetting.getHidden(userId) != hidden) {
13136                    pkgSetting.setHidden(hidden, userId);
13137                    mSettings.writePackageRestrictionsLPr(userId);
13138                    if (hidden) {
13139                        sendRemoved = true;
13140                    } else {
13141                        sendAdded = true;
13142                    }
13143                }
13144            }
13145            if (sendAdded) {
13146                sendPackageAddedForUser(packageName, pkgSetting, userId);
13147                return true;
13148            }
13149            if (sendRemoved) {
13150                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13151                        "hiding pkg");
13152                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13153                return true;
13154            }
13155        } finally {
13156            Binder.restoreCallingIdentity(callingId);
13157        }
13158        return false;
13159    }
13160
13161    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13162            int userId) {
13163        final PackageRemovedInfo info = new PackageRemovedInfo();
13164        info.removedPackage = packageName;
13165        info.removedUsers = new int[] {userId};
13166        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13167        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13168    }
13169
13170    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13171        if (pkgList.length > 0) {
13172            Bundle extras = new Bundle(1);
13173            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13174
13175            sendPackageBroadcast(
13176                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13177                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13178                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13179                    new int[] {userId});
13180        }
13181    }
13182
13183    /**
13184     * Returns true if application is not found or there was an error. Otherwise it returns
13185     * the hidden state of the package for the given user.
13186     */
13187    @Override
13188    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13189        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13190        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13191                true /* requireFullPermission */, false /* checkShell */,
13192                "getApplicationHidden for user " + userId);
13193        PackageSetting pkgSetting;
13194        long callingId = Binder.clearCallingIdentity();
13195        try {
13196            // writer
13197            synchronized (mPackages) {
13198                pkgSetting = mSettings.mPackages.get(packageName);
13199                if (pkgSetting == null) {
13200                    return true;
13201                }
13202                return pkgSetting.getHidden(userId);
13203            }
13204        } finally {
13205            Binder.restoreCallingIdentity(callingId);
13206        }
13207    }
13208
13209    /**
13210     * @hide
13211     */
13212    @Override
13213    public int installExistingPackageAsUser(String packageName, int userId, int installReason) {
13214        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13215                null);
13216        PackageSetting pkgSetting;
13217        final int uid = Binder.getCallingUid();
13218        enforceCrossUserPermission(uid, userId,
13219                true /* requireFullPermission */, true /* checkShell */,
13220                "installExistingPackage for user " + userId);
13221        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13222            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13223        }
13224
13225        long callingId = Binder.clearCallingIdentity();
13226        try {
13227            boolean installed = false;
13228
13229            // writer
13230            synchronized (mPackages) {
13231                pkgSetting = mSettings.mPackages.get(packageName);
13232                if (pkgSetting == null) {
13233                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13234                }
13235                if (!pkgSetting.getInstalled(userId)) {
13236                    pkgSetting.setInstalled(true, userId);
13237                    pkgSetting.setHidden(false, userId);
13238                    pkgSetting.setInstallReason(installReason, userId);
13239                    mSettings.writePackageRestrictionsLPr(userId);
13240                    installed = true;
13241                }
13242            }
13243
13244            if (installed) {
13245                if (pkgSetting.pkg != null) {
13246                    synchronized (mInstallLock) {
13247                        // We don't need to freeze for a brand new install
13248                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13249                    }
13250                }
13251                sendPackageAddedForUser(packageName, pkgSetting, userId);
13252            }
13253        } finally {
13254            Binder.restoreCallingIdentity(callingId);
13255        }
13256
13257        return PackageManager.INSTALL_SUCCEEDED;
13258    }
13259
13260    boolean isUserRestricted(int userId, String restrictionKey) {
13261        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13262        if (restrictions.getBoolean(restrictionKey, false)) {
13263            Log.w(TAG, "User is restricted: " + restrictionKey);
13264            return true;
13265        }
13266        return false;
13267    }
13268
13269    @Override
13270    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13271            int userId) {
13272        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13273        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13274                true /* requireFullPermission */, true /* checkShell */,
13275                "setPackagesSuspended for user " + userId);
13276
13277        if (ArrayUtils.isEmpty(packageNames)) {
13278            return packageNames;
13279        }
13280
13281        // List of package names for whom the suspended state has changed.
13282        List<String> changedPackages = new ArrayList<>(packageNames.length);
13283        // List of package names for whom the suspended state is not set as requested in this
13284        // method.
13285        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13286        long callingId = Binder.clearCallingIdentity();
13287        try {
13288            for (int i = 0; i < packageNames.length; i++) {
13289                String packageName = packageNames[i];
13290                boolean changed = false;
13291                final int appId;
13292                synchronized (mPackages) {
13293                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13294                    if (pkgSetting == null) {
13295                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13296                                + "\". Skipping suspending/un-suspending.");
13297                        unactionedPackages.add(packageName);
13298                        continue;
13299                    }
13300                    appId = pkgSetting.appId;
13301                    if (pkgSetting.getSuspended(userId) != suspended) {
13302                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13303                            unactionedPackages.add(packageName);
13304                            continue;
13305                        }
13306                        pkgSetting.setSuspended(suspended, userId);
13307                        mSettings.writePackageRestrictionsLPr(userId);
13308                        changed = true;
13309                        changedPackages.add(packageName);
13310                    }
13311                }
13312
13313                if (changed && suspended) {
13314                    killApplication(packageName, UserHandle.getUid(userId, appId),
13315                            "suspending package");
13316                }
13317            }
13318        } finally {
13319            Binder.restoreCallingIdentity(callingId);
13320        }
13321
13322        if (!changedPackages.isEmpty()) {
13323            sendPackagesSuspendedForUser(changedPackages.toArray(
13324                    new String[changedPackages.size()]), userId, suspended);
13325        }
13326
13327        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13328    }
13329
13330    @Override
13331    public boolean isPackageSuspendedForUser(String packageName, int userId) {
13332        enforceCrossUserPermission(Binder.getCallingUid(), userId,
13333                true /* requireFullPermission */, false /* checkShell */,
13334                "isPackageSuspendedForUser for user " + userId);
13335        synchronized (mPackages) {
13336            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13337            if (pkgSetting == null) {
13338                throw new IllegalArgumentException("Unknown target package: " + packageName);
13339            }
13340            return pkgSetting.getSuspended(userId);
13341        }
13342    }
13343
13344    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
13345        if (isPackageDeviceAdmin(packageName, userId)) {
13346            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13347                    + "\": has an active device admin");
13348            return false;
13349        }
13350
13351        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13352        if (packageName.equals(activeLauncherPackageName)) {
13353            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13354                    + "\": contains the active launcher");
13355            return false;
13356        }
13357
13358        if (packageName.equals(mRequiredInstallerPackage)) {
13359            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13360                    + "\": required for package installation");
13361            return false;
13362        }
13363
13364        if (packageName.equals(mRequiredUninstallerPackage)) {
13365            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13366                    + "\": required for package uninstallation");
13367            return false;
13368        }
13369
13370        if (packageName.equals(mRequiredVerifierPackage)) {
13371            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13372                    + "\": required for package verification");
13373            return false;
13374        }
13375
13376        if (packageName.equals(getDefaultDialerPackageName(userId))) {
13377            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13378                    + "\": is the default dialer");
13379            return false;
13380        }
13381
13382        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13383            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
13384                    + "\": protected package");
13385            return false;
13386        }
13387
13388        // Cannot suspend static shared libs as they are considered
13389        // a part of the using app (emulating static linking). Also
13390        // static libs are installed always on internal storage.
13391        PackageParser.Package pkg = mPackages.get(packageName);
13392        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13393            Slog.w(TAG, "Cannot suspend package: " + packageName
13394                    + " providing static shared library: "
13395                    + pkg.staticSharedLibName);
13396            return false;
13397        }
13398
13399        return true;
13400    }
13401
13402    private String getActiveLauncherPackageName(int userId) {
13403        Intent intent = new Intent(Intent.ACTION_MAIN);
13404        intent.addCategory(Intent.CATEGORY_HOME);
13405        ResolveInfo resolveInfo = resolveIntent(
13406                intent,
13407                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
13408                PackageManager.MATCH_DEFAULT_ONLY,
13409                userId);
13410
13411        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
13412    }
13413
13414    private String getDefaultDialerPackageName(int userId) {
13415        synchronized (mPackages) {
13416            return mSettings.getDefaultDialerPackageNameLPw(userId);
13417        }
13418    }
13419
13420    @Override
13421    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
13422        mContext.enforceCallingOrSelfPermission(
13423                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13424                "Only package verification agents can verify applications");
13425
13426        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13427        final PackageVerificationResponse response = new PackageVerificationResponse(
13428                verificationCode, Binder.getCallingUid());
13429        msg.arg1 = id;
13430        msg.obj = response;
13431        mHandler.sendMessage(msg);
13432    }
13433
13434    @Override
13435    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
13436            long millisecondsToDelay) {
13437        mContext.enforceCallingOrSelfPermission(
13438                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13439                "Only package verification agents can extend verification timeouts");
13440
13441        final PackageVerificationState state = mPendingVerification.get(id);
13442        final PackageVerificationResponse response = new PackageVerificationResponse(
13443                verificationCodeAtTimeout, Binder.getCallingUid());
13444
13445        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
13446            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
13447        }
13448        if (millisecondsToDelay < 0) {
13449            millisecondsToDelay = 0;
13450        }
13451        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
13452                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
13453            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
13454        }
13455
13456        if ((state != null) && !state.timeoutExtended()) {
13457            state.extendTimeout();
13458
13459            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
13460            msg.arg1 = id;
13461            msg.obj = response;
13462            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
13463        }
13464    }
13465
13466    private void broadcastPackageVerified(int verificationId, Uri packageUri,
13467            int verificationCode, UserHandle user) {
13468        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
13469        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
13470        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
13471        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13472        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
13473
13474        mContext.sendBroadcastAsUser(intent, user,
13475                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
13476    }
13477
13478    private ComponentName matchComponentForVerifier(String packageName,
13479            List<ResolveInfo> receivers) {
13480        ActivityInfo targetReceiver = null;
13481
13482        final int NR = receivers.size();
13483        for (int i = 0; i < NR; i++) {
13484            final ResolveInfo info = receivers.get(i);
13485            if (info.activityInfo == null) {
13486                continue;
13487            }
13488
13489            if (packageName.equals(info.activityInfo.packageName)) {
13490                targetReceiver = info.activityInfo;
13491                break;
13492            }
13493        }
13494
13495        if (targetReceiver == null) {
13496            return null;
13497        }
13498
13499        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
13500    }
13501
13502    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
13503            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
13504        if (pkgInfo.verifiers.length == 0) {
13505            return null;
13506        }
13507
13508        final int N = pkgInfo.verifiers.length;
13509        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
13510        for (int i = 0; i < N; i++) {
13511            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
13512
13513            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
13514                    receivers);
13515            if (comp == null) {
13516                continue;
13517            }
13518
13519            final int verifierUid = getUidForVerifier(verifierInfo);
13520            if (verifierUid == -1) {
13521                continue;
13522            }
13523
13524            if (DEBUG_VERIFY) {
13525                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
13526                        + " with the correct signature");
13527            }
13528            sufficientVerifiers.add(comp);
13529            verificationState.addSufficientVerifier(verifierUid);
13530        }
13531
13532        return sufficientVerifiers;
13533    }
13534
13535    private int getUidForVerifier(VerifierInfo verifierInfo) {
13536        synchronized (mPackages) {
13537            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
13538            if (pkg == null) {
13539                return -1;
13540            } else if (pkg.mSignatures.length != 1) {
13541                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13542                        + " has more than one signature; ignoring");
13543                return -1;
13544            }
13545
13546            /*
13547             * If the public key of the package's signature does not match
13548             * our expected public key, then this is a different package and
13549             * we should skip.
13550             */
13551
13552            final byte[] expectedPublicKey;
13553            try {
13554                final Signature verifierSig = pkg.mSignatures[0];
13555                final PublicKey publicKey = verifierSig.getPublicKey();
13556                expectedPublicKey = publicKey.getEncoded();
13557            } catch (CertificateException e) {
13558                return -1;
13559            }
13560
13561            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
13562
13563            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
13564                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
13565                        + " does not have the expected public key; ignoring");
13566                return -1;
13567            }
13568
13569            return pkg.applicationInfo.uid;
13570        }
13571    }
13572
13573    @Override
13574    public void finishPackageInstall(int token, boolean didLaunch) {
13575        enforceSystemOrRoot("Only the system is allowed to finish installs");
13576
13577        if (DEBUG_INSTALL) {
13578            Slog.v(TAG, "BM finishing package install for " + token);
13579        }
13580        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13581
13582        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
13583        mHandler.sendMessage(msg);
13584    }
13585
13586    /**
13587     * Get the verification agent timeout.
13588     *
13589     * @return verification timeout in milliseconds
13590     */
13591    private long getVerificationTimeout() {
13592        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
13593                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
13594                DEFAULT_VERIFICATION_TIMEOUT);
13595    }
13596
13597    /**
13598     * Get the default verification agent response code.
13599     *
13600     * @return default verification response code
13601     */
13602    private int getDefaultVerificationResponse() {
13603        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13604                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
13605                DEFAULT_VERIFICATION_RESPONSE);
13606    }
13607
13608    /**
13609     * Check whether or not package verification has been enabled.
13610     *
13611     * @return true if verification should be performed
13612     */
13613    private boolean isVerificationEnabled(int userId, int installFlags) {
13614        if (!DEFAULT_VERIFY_ENABLE) {
13615            return false;
13616        }
13617        // Ephemeral apps don't get the full verification treatment
13618        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
13619            if (DEBUG_EPHEMERAL) {
13620                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
13621            }
13622            return false;
13623        }
13624
13625        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
13626
13627        // Check if installing from ADB
13628        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
13629            // Do not run verification in a test harness environment
13630            if (ActivityManager.isRunningInTestHarness()) {
13631                return false;
13632            }
13633            if (ensureVerifyAppsEnabled) {
13634                return true;
13635            }
13636            // Check if the developer does not want package verification for ADB installs
13637            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13638                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
13639                return false;
13640            }
13641        }
13642
13643        if (ensureVerifyAppsEnabled) {
13644            return true;
13645        }
13646
13647        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13648                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
13649    }
13650
13651    @Override
13652    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
13653            throws RemoteException {
13654        mContext.enforceCallingOrSelfPermission(
13655                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
13656                "Only intentfilter verification agents can verify applications");
13657
13658        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
13659        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
13660                Binder.getCallingUid(), verificationCode, failedDomains);
13661        msg.arg1 = id;
13662        msg.obj = response;
13663        mHandler.sendMessage(msg);
13664    }
13665
13666    @Override
13667    public int getIntentVerificationStatus(String packageName, int userId) {
13668        synchronized (mPackages) {
13669            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
13670        }
13671    }
13672
13673    @Override
13674    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
13675        mContext.enforceCallingOrSelfPermission(
13676                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13677
13678        boolean result = false;
13679        synchronized (mPackages) {
13680            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
13681        }
13682        if (result) {
13683            scheduleWritePackageRestrictionsLocked(userId);
13684        }
13685        return result;
13686    }
13687
13688    @Override
13689    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
13690            String packageName) {
13691        synchronized (mPackages) {
13692            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
13693        }
13694    }
13695
13696    @Override
13697    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
13698        if (TextUtils.isEmpty(packageName)) {
13699            return ParceledListSlice.emptyList();
13700        }
13701        synchronized (mPackages) {
13702            PackageParser.Package pkg = mPackages.get(packageName);
13703            if (pkg == null || pkg.activities == null) {
13704                return ParceledListSlice.emptyList();
13705            }
13706            final int count = pkg.activities.size();
13707            ArrayList<IntentFilter> result = new ArrayList<>();
13708            for (int n=0; n<count; n++) {
13709                PackageParser.Activity activity = pkg.activities.get(n);
13710                if (activity.intents != null && activity.intents.size() > 0) {
13711                    result.addAll(activity.intents);
13712                }
13713            }
13714            return new ParceledListSlice<>(result);
13715        }
13716    }
13717
13718    @Override
13719    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
13720        mContext.enforceCallingOrSelfPermission(
13721                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13722
13723        synchronized (mPackages) {
13724            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
13725            if (packageName != null) {
13726                result |= updateIntentVerificationStatus(packageName,
13727                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
13728                        userId);
13729                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
13730                        packageName, userId);
13731            }
13732            return result;
13733        }
13734    }
13735
13736    @Override
13737    public String getDefaultBrowserPackageName(int userId) {
13738        synchronized (mPackages) {
13739            return mSettings.getDefaultBrowserPackageNameLPw(userId);
13740        }
13741    }
13742
13743    /**
13744     * Get the "allow unknown sources" setting.
13745     *
13746     * @return the current "allow unknown sources" setting
13747     */
13748    private int getUnknownSourcesSettings() {
13749        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
13750                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
13751                -1);
13752    }
13753
13754    @Override
13755    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
13756        final int uid = Binder.getCallingUid();
13757        // writer
13758        synchronized (mPackages) {
13759            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
13760            if (targetPackageSetting == null) {
13761                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
13762            }
13763
13764            PackageSetting installerPackageSetting;
13765            if (installerPackageName != null) {
13766                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
13767                if (installerPackageSetting == null) {
13768                    throw new IllegalArgumentException("Unknown installer package: "
13769                            + installerPackageName);
13770                }
13771            } else {
13772                installerPackageSetting = null;
13773            }
13774
13775            Signature[] callerSignature;
13776            Object obj = mSettings.getUserIdLPr(uid);
13777            if (obj != null) {
13778                if (obj instanceof SharedUserSetting) {
13779                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
13780                } else if (obj instanceof PackageSetting) {
13781                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
13782                } else {
13783                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
13784                }
13785            } else {
13786                throw new SecurityException("Unknown calling UID: " + uid);
13787            }
13788
13789            // Verify: can't set installerPackageName to a package that is
13790            // not signed with the same cert as the caller.
13791            if (installerPackageSetting != null) {
13792                if (compareSignatures(callerSignature,
13793                        installerPackageSetting.signatures.mSignatures)
13794                        != PackageManager.SIGNATURE_MATCH) {
13795                    throw new SecurityException(
13796                            "Caller does not have same cert as new installer package "
13797                            + installerPackageName);
13798                }
13799            }
13800
13801            // Verify: if target already has an installer package, it must
13802            // be signed with the same cert as the caller.
13803            if (targetPackageSetting.installerPackageName != null) {
13804                PackageSetting setting = mSettings.mPackages.get(
13805                        targetPackageSetting.installerPackageName);
13806                // If the currently set package isn't valid, then it's always
13807                // okay to change it.
13808                if (setting != null) {
13809                    if (compareSignatures(callerSignature,
13810                            setting.signatures.mSignatures)
13811                            != PackageManager.SIGNATURE_MATCH) {
13812                        throw new SecurityException(
13813                                "Caller does not have same cert as old installer package "
13814                                + targetPackageSetting.installerPackageName);
13815                    }
13816                }
13817            }
13818
13819            // Okay!
13820            targetPackageSetting.installerPackageName = installerPackageName;
13821            if (installerPackageName != null) {
13822                mSettings.mInstallerPackages.add(installerPackageName);
13823            }
13824            scheduleWriteSettingsLocked();
13825        }
13826    }
13827
13828    @Override
13829    public void setApplicationCategoryHint(String packageName, int categoryHint,
13830            String callerPackageName) {
13831        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
13832                callerPackageName);
13833        synchronized (mPackages) {
13834            PackageSetting ps = mSettings.mPackages.get(packageName);
13835            if (ps == null) {
13836                throw new IllegalArgumentException("Unknown target package " + packageName);
13837            }
13838
13839            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
13840                throw new IllegalArgumentException("Calling package " + callerPackageName
13841                        + " is not installer for " + packageName);
13842            }
13843
13844            if (ps.categoryHint != categoryHint) {
13845                ps.categoryHint = categoryHint;
13846                scheduleWriteSettingsLocked();
13847            }
13848        }
13849    }
13850
13851    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
13852        // Queue up an async operation since the package installation may take a little while.
13853        mHandler.post(new Runnable() {
13854            public void run() {
13855                mHandler.removeCallbacks(this);
13856                 // Result object to be returned
13857                PackageInstalledInfo res = new PackageInstalledInfo();
13858                res.setReturnCode(currentStatus);
13859                res.uid = -1;
13860                res.pkg = null;
13861                res.removedInfo = null;
13862                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13863                    args.doPreInstall(res.returnCode);
13864                    synchronized (mInstallLock) {
13865                        installPackageTracedLI(args, res);
13866                    }
13867                    args.doPostInstall(res.returnCode, res.uid);
13868                }
13869
13870                // A restore should be performed at this point if (a) the install
13871                // succeeded, (b) the operation is not an update, and (c) the new
13872                // package has not opted out of backup participation.
13873                final boolean update = res.removedInfo != null
13874                        && res.removedInfo.removedPackage != null;
13875                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
13876                boolean doRestore = !update
13877                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
13878
13879                // Set up the post-install work request bookkeeping.  This will be used
13880                // and cleaned up by the post-install event handling regardless of whether
13881                // there's a restore pass performed.  Token values are >= 1.
13882                int token;
13883                if (mNextInstallToken < 0) mNextInstallToken = 1;
13884                token = mNextInstallToken++;
13885
13886                PostInstallData data = new PostInstallData(args, res);
13887                mRunningInstalls.put(token, data);
13888                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
13889
13890                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
13891                    // Pass responsibility to the Backup Manager.  It will perform a
13892                    // restore if appropriate, then pass responsibility back to the
13893                    // Package Manager to run the post-install observer callbacks
13894                    // and broadcasts.
13895                    IBackupManager bm = IBackupManager.Stub.asInterface(
13896                            ServiceManager.getService(Context.BACKUP_SERVICE));
13897                    if (bm != null) {
13898                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
13899                                + " to BM for possible restore");
13900                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
13901                        try {
13902                            // TODO: http://b/22388012
13903                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
13904                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
13905                            } else {
13906                                doRestore = false;
13907                            }
13908                        } catch (RemoteException e) {
13909                            // can't happen; the backup manager is local
13910                        } catch (Exception e) {
13911                            Slog.e(TAG, "Exception trying to enqueue restore", e);
13912                            doRestore = false;
13913                        }
13914                    } else {
13915                        Slog.e(TAG, "Backup Manager not found!");
13916                        doRestore = false;
13917                    }
13918                }
13919
13920                if (!doRestore) {
13921                    // No restore possible, or the Backup Manager was mysteriously not
13922                    // available -- just fire the post-install work request directly.
13923                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
13924
13925                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
13926
13927                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
13928                    mHandler.sendMessage(msg);
13929                }
13930            }
13931        });
13932    }
13933
13934    /**
13935     * Callback from PackageSettings whenever an app is first transitioned out of the
13936     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
13937     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
13938     * here whether the app is the target of an ongoing install, and only send the
13939     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
13940     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
13941     * handling.
13942     */
13943    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
13944        // Serialize this with the rest of the install-process message chain.  In the
13945        // restore-at-install case, this Runnable will necessarily run before the
13946        // POST_INSTALL message is processed, so the contents of mRunningInstalls
13947        // are coherent.  In the non-restore case, the app has already completed install
13948        // and been launched through some other means, so it is not in a problematic
13949        // state for observers to see the FIRST_LAUNCH signal.
13950        mHandler.post(new Runnable() {
13951            @Override
13952            public void run() {
13953                for (int i = 0; i < mRunningInstalls.size(); i++) {
13954                    final PostInstallData data = mRunningInstalls.valueAt(i);
13955                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13956                        continue;
13957                    }
13958                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
13959                        // right package; but is it for the right user?
13960                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
13961                            if (userId == data.res.newUsers[uIndex]) {
13962                                if (DEBUG_BACKUP) {
13963                                    Slog.i(TAG, "Package " + pkgName
13964                                            + " being restored so deferring FIRST_LAUNCH");
13965                                }
13966                                return;
13967                            }
13968                        }
13969                    }
13970                }
13971                // didn't find it, so not being restored
13972                if (DEBUG_BACKUP) {
13973                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
13974                }
13975                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
13976            }
13977        });
13978    }
13979
13980    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
13981        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
13982                installerPkg, null, userIds);
13983    }
13984
13985    private abstract class HandlerParams {
13986        private static final int MAX_RETRIES = 4;
13987
13988        /**
13989         * Number of times startCopy() has been attempted and had a non-fatal
13990         * error.
13991         */
13992        private int mRetries = 0;
13993
13994        /** User handle for the user requesting the information or installation. */
13995        private final UserHandle mUser;
13996        String traceMethod;
13997        int traceCookie;
13998
13999        HandlerParams(UserHandle user) {
14000            mUser = user;
14001        }
14002
14003        UserHandle getUser() {
14004            return mUser;
14005        }
14006
14007        HandlerParams setTraceMethod(String traceMethod) {
14008            this.traceMethod = traceMethod;
14009            return this;
14010        }
14011
14012        HandlerParams setTraceCookie(int traceCookie) {
14013            this.traceCookie = traceCookie;
14014            return this;
14015        }
14016
14017        final boolean startCopy() {
14018            boolean res;
14019            try {
14020                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14021
14022                if (++mRetries > MAX_RETRIES) {
14023                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14024                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14025                    handleServiceError();
14026                    return false;
14027                } else {
14028                    handleStartCopy();
14029                    res = true;
14030                }
14031            } catch (RemoteException e) {
14032                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14033                mHandler.sendEmptyMessage(MCS_RECONNECT);
14034                res = false;
14035            }
14036            handleReturnCode();
14037            return res;
14038        }
14039
14040        final void serviceError() {
14041            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14042            handleServiceError();
14043            handleReturnCode();
14044        }
14045
14046        abstract void handleStartCopy() throws RemoteException;
14047        abstract void handleServiceError();
14048        abstract void handleReturnCode();
14049    }
14050
14051    class MeasureParams extends HandlerParams {
14052        private final PackageStats mStats;
14053        private boolean mSuccess;
14054
14055        private final IPackageStatsObserver mObserver;
14056
14057        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
14058            super(new UserHandle(stats.userHandle));
14059            mObserver = observer;
14060            mStats = stats;
14061        }
14062
14063        @Override
14064        public String toString() {
14065            return "MeasureParams{"
14066                + Integer.toHexString(System.identityHashCode(this))
14067                + " " + mStats.packageName + "}";
14068        }
14069
14070        @Override
14071        void handleStartCopy() throws RemoteException {
14072            synchronized (mInstallLock) {
14073                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
14074            }
14075
14076            if (mSuccess) {
14077                boolean mounted = false;
14078                try {
14079                    final String status = Environment.getExternalStorageState();
14080                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
14081                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
14082                } catch (Exception e) {
14083                }
14084
14085                if (mounted) {
14086                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
14087
14088                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
14089                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
14090
14091                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
14092                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
14093
14094                    // Always subtract cache size, since it's a subdirectory
14095                    mStats.externalDataSize -= mStats.externalCacheSize;
14096
14097                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
14098                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
14099
14100                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
14101                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
14102                }
14103            }
14104        }
14105
14106        @Override
14107        void handleReturnCode() {
14108            if (mObserver != null) {
14109                try {
14110                    mObserver.onGetStatsCompleted(mStats, mSuccess);
14111                } catch (RemoteException e) {
14112                    Slog.i(TAG, "Observer no longer exists.");
14113                }
14114            }
14115        }
14116
14117        @Override
14118        void handleServiceError() {
14119            Slog.e(TAG, "Could not measure application " + mStats.packageName
14120                            + " external storage");
14121        }
14122    }
14123
14124    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
14125            throws RemoteException {
14126        long result = 0;
14127        for (File path : paths) {
14128            result += mcs.calculateDirectorySize(path.getAbsolutePath());
14129        }
14130        return result;
14131    }
14132
14133    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14134        for (File path : paths) {
14135            try {
14136                mcs.clearDirectory(path.getAbsolutePath());
14137            } catch (RemoteException e) {
14138            }
14139        }
14140    }
14141
14142    static class OriginInfo {
14143        /**
14144         * Location where install is coming from, before it has been
14145         * copied/renamed into place. This could be a single monolithic APK
14146         * file, or a cluster directory. This location may be untrusted.
14147         */
14148        final File file;
14149        final String cid;
14150
14151        /**
14152         * Flag indicating that {@link #file} or {@link #cid} has already been
14153         * staged, meaning downstream users don't need to defensively copy the
14154         * contents.
14155         */
14156        final boolean staged;
14157
14158        /**
14159         * Flag indicating that {@link #file} or {@link #cid} is an already
14160         * installed app that is being moved.
14161         */
14162        final boolean existing;
14163
14164        final String resolvedPath;
14165        final File resolvedFile;
14166
14167        static OriginInfo fromNothing() {
14168            return new OriginInfo(null, null, false, false);
14169        }
14170
14171        static OriginInfo fromUntrustedFile(File file) {
14172            return new OriginInfo(file, null, false, false);
14173        }
14174
14175        static OriginInfo fromExistingFile(File file) {
14176            return new OriginInfo(file, null, false, true);
14177        }
14178
14179        static OriginInfo fromStagedFile(File file) {
14180            return new OriginInfo(file, null, true, false);
14181        }
14182
14183        static OriginInfo fromStagedContainer(String cid) {
14184            return new OriginInfo(null, cid, true, false);
14185        }
14186
14187        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
14188            this.file = file;
14189            this.cid = cid;
14190            this.staged = staged;
14191            this.existing = existing;
14192
14193            if (cid != null) {
14194                resolvedPath = PackageHelper.getSdDir(cid);
14195                resolvedFile = new File(resolvedPath);
14196            } else if (file != null) {
14197                resolvedPath = file.getAbsolutePath();
14198                resolvedFile = file;
14199            } else {
14200                resolvedPath = null;
14201                resolvedFile = null;
14202            }
14203        }
14204    }
14205
14206    static class MoveInfo {
14207        final int moveId;
14208        final String fromUuid;
14209        final String toUuid;
14210        final String packageName;
14211        final String dataAppName;
14212        final int appId;
14213        final String seinfo;
14214        final int targetSdkVersion;
14215
14216        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14217                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14218            this.moveId = moveId;
14219            this.fromUuid = fromUuid;
14220            this.toUuid = toUuid;
14221            this.packageName = packageName;
14222            this.dataAppName = dataAppName;
14223            this.appId = appId;
14224            this.seinfo = seinfo;
14225            this.targetSdkVersion = targetSdkVersion;
14226        }
14227    }
14228
14229    static class VerificationInfo {
14230        /** A constant used to indicate that a uid value is not present. */
14231        public static final int NO_UID = -1;
14232
14233        /** URI referencing where the package was downloaded from. */
14234        final Uri originatingUri;
14235
14236        /** HTTP referrer URI associated with the originatingURI. */
14237        final Uri referrer;
14238
14239        /** UID of the application that the install request originated from. */
14240        final int originatingUid;
14241
14242        /** UID of application requesting the install */
14243        final int installerUid;
14244
14245        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14246            this.originatingUri = originatingUri;
14247            this.referrer = referrer;
14248            this.originatingUid = originatingUid;
14249            this.installerUid = installerUid;
14250        }
14251    }
14252
14253    class InstallParams extends HandlerParams {
14254        final OriginInfo origin;
14255        final MoveInfo move;
14256        final IPackageInstallObserver2 observer;
14257        int installFlags;
14258        final String installerPackageName;
14259        final String volumeUuid;
14260        private InstallArgs mArgs;
14261        private int mRet;
14262        final String packageAbiOverride;
14263        final String[] grantedRuntimePermissions;
14264        final VerificationInfo verificationInfo;
14265        final Certificate[][] certificates;
14266        final int installReason;
14267
14268        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14269                int installFlags, String installerPackageName, String volumeUuid,
14270                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
14271                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
14272            super(user);
14273            this.origin = origin;
14274            this.move = move;
14275            this.observer = observer;
14276            this.installFlags = installFlags;
14277            this.installerPackageName = installerPackageName;
14278            this.volumeUuid = volumeUuid;
14279            this.verificationInfo = verificationInfo;
14280            this.packageAbiOverride = packageAbiOverride;
14281            this.grantedRuntimePermissions = grantedPermissions;
14282            this.certificates = certificates;
14283            this.installReason = installReason;
14284        }
14285
14286        @Override
14287        public String toString() {
14288            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
14289                    + " file=" + origin.file + " cid=" + origin.cid + "}";
14290        }
14291
14292        private int installLocationPolicy(PackageInfoLite pkgLite) {
14293            String packageName = pkgLite.packageName;
14294            int installLocation = pkgLite.installLocation;
14295            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14296            // reader
14297            synchronized (mPackages) {
14298                // Currently installed package which the new package is attempting to replace or
14299                // null if no such package is installed.
14300                PackageParser.Package installedPkg = mPackages.get(packageName);
14301                // Package which currently owns the data which the new package will own if installed.
14302                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
14303                // will be null whereas dataOwnerPkg will contain information about the package
14304                // which was uninstalled while keeping its data.
14305                PackageParser.Package dataOwnerPkg = installedPkg;
14306                if (dataOwnerPkg  == null) {
14307                    PackageSetting ps = mSettings.mPackages.get(packageName);
14308                    if (ps != null) {
14309                        dataOwnerPkg = ps.pkg;
14310                    }
14311                }
14312
14313                if (dataOwnerPkg != null) {
14314                    // If installed, the package will get access to data left on the device by its
14315                    // predecessor. As a security measure, this is permited only if this is not a
14316                    // version downgrade or if the predecessor package is marked as debuggable and
14317                    // a downgrade is explicitly requested.
14318                    //
14319                    // On debuggable platform builds, downgrades are permitted even for
14320                    // non-debuggable packages to make testing easier. Debuggable platform builds do
14321                    // not offer security guarantees and thus it's OK to disable some security
14322                    // mechanisms to make debugging/testing easier on those builds. However, even on
14323                    // debuggable builds downgrades of packages are permitted only if requested via
14324                    // installFlags. This is because we aim to keep the behavior of debuggable
14325                    // platform builds as close as possible to the behavior of non-debuggable
14326                    // platform builds.
14327                    final boolean downgradeRequested =
14328                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
14329                    final boolean packageDebuggable =
14330                                (dataOwnerPkg.applicationInfo.flags
14331                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
14332                    final boolean downgradePermitted =
14333                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
14334                    if (!downgradePermitted) {
14335                        try {
14336                            checkDowngrade(dataOwnerPkg, pkgLite);
14337                        } catch (PackageManagerException e) {
14338                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
14339                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
14340                        }
14341                    }
14342                }
14343
14344                if (installedPkg != null) {
14345                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14346                        // Check for updated system application.
14347                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14348                            if (onSd) {
14349                                Slog.w(TAG, "Cannot install update to system app on sdcard");
14350                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
14351                            }
14352                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14353                        } else {
14354                            if (onSd) {
14355                                // Install flag overrides everything.
14356                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14357                            }
14358                            // If current upgrade specifies particular preference
14359                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
14360                                // Application explicitly specified internal.
14361                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14362                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
14363                                // App explictly prefers external. Let policy decide
14364                            } else {
14365                                // Prefer previous location
14366                                if (isExternal(installedPkg)) {
14367                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14368                                }
14369                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
14370                            }
14371                        }
14372                    } else {
14373                        // Invalid install. Return error code
14374                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
14375                    }
14376                }
14377            }
14378            // All the special cases have been taken care of.
14379            // Return result based on recommended install location.
14380            if (onSd) {
14381                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
14382            }
14383            return pkgLite.recommendedInstallLocation;
14384        }
14385
14386        /*
14387         * Invoke remote method to get package information and install
14388         * location values. Override install location based on default
14389         * policy if needed and then create install arguments based
14390         * on the install location.
14391         */
14392        public void handleStartCopy() throws RemoteException {
14393            int ret = PackageManager.INSTALL_SUCCEEDED;
14394
14395            // If we're already staged, we've firmly committed to an install location
14396            if (origin.staged) {
14397                if (origin.file != null) {
14398                    installFlags |= PackageManager.INSTALL_INTERNAL;
14399                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14400                } else if (origin.cid != null) {
14401                    installFlags |= PackageManager.INSTALL_EXTERNAL;
14402                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
14403                } else {
14404                    throw new IllegalStateException("Invalid stage location");
14405                }
14406            }
14407
14408            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14409            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
14410            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14411            PackageInfoLite pkgLite = null;
14412
14413            if (onInt && onSd) {
14414                // Check if both bits are set.
14415                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
14416                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14417            } else if (onSd && ephemeral) {
14418                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
14419                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14420            } else {
14421                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
14422                        packageAbiOverride);
14423
14424                if (DEBUG_EPHEMERAL && ephemeral) {
14425                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
14426                }
14427
14428                /*
14429                 * If we have too little free space, try to free cache
14430                 * before giving up.
14431                 */
14432                if (!origin.staged && pkgLite.recommendedInstallLocation
14433                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14434                    // TODO: focus freeing disk space on the target device
14435                    final StorageManager storage = StorageManager.from(mContext);
14436                    final long lowThreshold = storage.getStorageLowBytes(
14437                            Environment.getDataDirectory());
14438
14439                    final long sizeBytes = mContainerService.calculateInstalledSize(
14440                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
14441
14442                    try {
14443                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0);
14444                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
14445                                installFlags, packageAbiOverride);
14446                    } catch (InstallerException e) {
14447                        Slog.w(TAG, "Failed to free cache", e);
14448                    }
14449
14450                    /*
14451                     * The cache free must have deleted the file we
14452                     * downloaded to install.
14453                     *
14454                     * TODO: fix the "freeCache" call to not delete
14455                     *       the file we care about.
14456                     */
14457                    if (pkgLite.recommendedInstallLocation
14458                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14459                        pkgLite.recommendedInstallLocation
14460                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
14461                    }
14462                }
14463            }
14464
14465            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14466                int loc = pkgLite.recommendedInstallLocation;
14467                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
14468                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
14469                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
14470                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
14471                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
14472                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14473                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
14474                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
14475                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
14476                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
14477                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
14478                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
14479                } else {
14480                    // Override with defaults if needed.
14481                    loc = installLocationPolicy(pkgLite);
14482                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
14483                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
14484                    } else if (!onSd && !onInt) {
14485                        // Override install location with flags
14486                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
14487                            // Set the flag to install on external media.
14488                            installFlags |= PackageManager.INSTALL_EXTERNAL;
14489                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
14490                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
14491                            if (DEBUG_EPHEMERAL) {
14492                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
14493                            }
14494                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
14495                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
14496                                    |PackageManager.INSTALL_INTERNAL);
14497                        } else {
14498                            // Make sure the flag for installing on external
14499                            // media is unset
14500                            installFlags |= PackageManager.INSTALL_INTERNAL;
14501                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
14502                        }
14503                    }
14504                }
14505            }
14506
14507            final InstallArgs args = createInstallArgs(this);
14508            mArgs = args;
14509
14510            if (ret == PackageManager.INSTALL_SUCCEEDED) {
14511                // TODO: http://b/22976637
14512                // Apps installed for "all" users use the device owner to verify the app
14513                UserHandle verifierUser = getUser();
14514                if (verifierUser == UserHandle.ALL) {
14515                    verifierUser = UserHandle.SYSTEM;
14516                }
14517
14518                /*
14519                 * Determine if we have any installed package verifiers. If we
14520                 * do, then we'll defer to them to verify the packages.
14521                 */
14522                final int requiredUid = mRequiredVerifierPackage == null ? -1
14523                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
14524                                verifierUser.getIdentifier());
14525                if (!origin.existing && requiredUid != -1
14526                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
14527                    final Intent verification = new Intent(
14528                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
14529                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
14530                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
14531                            PACKAGE_MIME_TYPE);
14532                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14533
14534                    // Query all live verifiers based on current user state
14535                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
14536                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
14537
14538                    if (DEBUG_VERIFY) {
14539                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
14540                                + verification.toString() + " with " + pkgLite.verifiers.length
14541                                + " optional verifiers");
14542                    }
14543
14544                    final int verificationId = mPendingVerificationToken++;
14545
14546                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14547
14548                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
14549                            installerPackageName);
14550
14551                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
14552                            installFlags);
14553
14554                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
14555                            pkgLite.packageName);
14556
14557                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
14558                            pkgLite.versionCode);
14559
14560                    if (verificationInfo != null) {
14561                        if (verificationInfo.originatingUri != null) {
14562                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
14563                                    verificationInfo.originatingUri);
14564                        }
14565                        if (verificationInfo.referrer != null) {
14566                            verification.putExtra(Intent.EXTRA_REFERRER,
14567                                    verificationInfo.referrer);
14568                        }
14569                        if (verificationInfo.originatingUid >= 0) {
14570                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
14571                                    verificationInfo.originatingUid);
14572                        }
14573                        if (verificationInfo.installerUid >= 0) {
14574                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
14575                                    verificationInfo.installerUid);
14576                        }
14577                    }
14578
14579                    final PackageVerificationState verificationState = new PackageVerificationState(
14580                            requiredUid, args);
14581
14582                    mPendingVerification.append(verificationId, verificationState);
14583
14584                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
14585                            receivers, verificationState);
14586
14587                    /*
14588                     * If any sufficient verifiers were listed in the package
14589                     * manifest, attempt to ask them.
14590                     */
14591                    if (sufficientVerifiers != null) {
14592                        final int N = sufficientVerifiers.size();
14593                        if (N == 0) {
14594                            Slog.i(TAG, "Additional verifiers required, but none installed.");
14595                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
14596                        } else {
14597                            for (int i = 0; i < N; i++) {
14598                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
14599
14600                                final Intent sufficientIntent = new Intent(verification);
14601                                sufficientIntent.setComponent(verifierComponent);
14602                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
14603                            }
14604                        }
14605                    }
14606
14607                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
14608                            mRequiredVerifierPackage, receivers);
14609                    if (ret == PackageManager.INSTALL_SUCCEEDED
14610                            && mRequiredVerifierPackage != null) {
14611                        Trace.asyncTraceBegin(
14612                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
14613                        /*
14614                         * Send the intent to the required verification agent,
14615                         * but only start the verification timeout after the
14616                         * target BroadcastReceivers have run.
14617                         */
14618                        verification.setComponent(requiredVerifierComponent);
14619                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
14620                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14621                                new BroadcastReceiver() {
14622                                    @Override
14623                                    public void onReceive(Context context, Intent intent) {
14624                                        final Message msg = mHandler
14625                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
14626                                        msg.arg1 = verificationId;
14627                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
14628                                    }
14629                                }, null, 0, null, null);
14630
14631                        /*
14632                         * We don't want the copy to proceed until verification
14633                         * succeeds, so null out this field.
14634                         */
14635                        mArgs = null;
14636                    }
14637                } else {
14638                    /*
14639                     * No package verification is enabled, so immediately start
14640                     * the remote call to initiate copy using temporary file.
14641                     */
14642                    ret = args.copyApk(mContainerService, true);
14643                }
14644            }
14645
14646            mRet = ret;
14647        }
14648
14649        @Override
14650        void handleReturnCode() {
14651            // If mArgs is null, then MCS couldn't be reached. When it
14652            // reconnects, it will try again to install. At that point, this
14653            // will succeed.
14654            if (mArgs != null) {
14655                processPendingInstall(mArgs, mRet);
14656            }
14657        }
14658
14659        @Override
14660        void handleServiceError() {
14661            mArgs = createInstallArgs(this);
14662            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14663        }
14664
14665        public boolean isForwardLocked() {
14666            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14667        }
14668    }
14669
14670    /**
14671     * Used during creation of InstallArgs
14672     *
14673     * @param installFlags package installation flags
14674     * @return true if should be installed on external storage
14675     */
14676    private static boolean installOnExternalAsec(int installFlags) {
14677        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
14678            return false;
14679        }
14680        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14681            return true;
14682        }
14683        return false;
14684    }
14685
14686    /**
14687     * Used during creation of InstallArgs
14688     *
14689     * @param installFlags package installation flags
14690     * @return true if should be installed as forward locked
14691     */
14692    private static boolean installForwardLocked(int installFlags) {
14693        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14694    }
14695
14696    private InstallArgs createInstallArgs(InstallParams params) {
14697        if (params.move != null) {
14698            return new MoveInstallArgs(params);
14699        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
14700            return new AsecInstallArgs(params);
14701        } else {
14702            return new FileInstallArgs(params);
14703        }
14704    }
14705
14706    /**
14707     * Create args that describe an existing installed package. Typically used
14708     * when cleaning up old installs, or used as a move source.
14709     */
14710    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
14711            String resourcePath, String[] instructionSets) {
14712        final boolean isInAsec;
14713        if (installOnExternalAsec(installFlags)) {
14714            /* Apps on SD card are always in ASEC containers. */
14715            isInAsec = true;
14716        } else if (installForwardLocked(installFlags)
14717                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
14718            /*
14719             * Forward-locked apps are only in ASEC containers if they're the
14720             * new style
14721             */
14722            isInAsec = true;
14723        } else {
14724            isInAsec = false;
14725        }
14726
14727        if (isInAsec) {
14728            return new AsecInstallArgs(codePath, instructionSets,
14729                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
14730        } else {
14731            return new FileInstallArgs(codePath, resourcePath, instructionSets);
14732        }
14733    }
14734
14735    static abstract class InstallArgs {
14736        /** @see InstallParams#origin */
14737        final OriginInfo origin;
14738        /** @see InstallParams#move */
14739        final MoveInfo move;
14740
14741        final IPackageInstallObserver2 observer;
14742        // Always refers to PackageManager flags only
14743        final int installFlags;
14744        final String installerPackageName;
14745        final String volumeUuid;
14746        final UserHandle user;
14747        final String abiOverride;
14748        final String[] installGrantPermissions;
14749        /** If non-null, drop an async trace when the install completes */
14750        final String traceMethod;
14751        final int traceCookie;
14752        final Certificate[][] certificates;
14753        final int installReason;
14754
14755        // The list of instruction sets supported by this app. This is currently
14756        // only used during the rmdex() phase to clean up resources. We can get rid of this
14757        // if we move dex files under the common app path.
14758        /* nullable */ String[] instructionSets;
14759
14760        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14761                int installFlags, String installerPackageName, String volumeUuid,
14762                UserHandle user, String[] instructionSets,
14763                String abiOverride, String[] installGrantPermissions,
14764                String traceMethod, int traceCookie, Certificate[][] certificates,
14765                int installReason) {
14766            this.origin = origin;
14767            this.move = move;
14768            this.installFlags = installFlags;
14769            this.observer = observer;
14770            this.installerPackageName = installerPackageName;
14771            this.volumeUuid = volumeUuid;
14772            this.user = user;
14773            this.instructionSets = instructionSets;
14774            this.abiOverride = abiOverride;
14775            this.installGrantPermissions = installGrantPermissions;
14776            this.traceMethod = traceMethod;
14777            this.traceCookie = traceCookie;
14778            this.certificates = certificates;
14779            this.installReason = installReason;
14780        }
14781
14782        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
14783        abstract int doPreInstall(int status);
14784
14785        /**
14786         * Rename package into final resting place. All paths on the given
14787         * scanned package should be updated to reflect the rename.
14788         */
14789        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
14790        abstract int doPostInstall(int status, int uid);
14791
14792        /** @see PackageSettingBase#codePathString */
14793        abstract String getCodePath();
14794        /** @see PackageSettingBase#resourcePathString */
14795        abstract String getResourcePath();
14796
14797        // Need installer lock especially for dex file removal.
14798        abstract void cleanUpResourcesLI();
14799        abstract boolean doPostDeleteLI(boolean delete);
14800
14801        /**
14802         * Called before the source arguments are copied. This is used mostly
14803         * for MoveParams when it needs to read the source file to put it in the
14804         * destination.
14805         */
14806        int doPreCopy() {
14807            return PackageManager.INSTALL_SUCCEEDED;
14808        }
14809
14810        /**
14811         * Called after the source arguments are copied. This is used mostly for
14812         * MoveParams when it needs to read the source file to put it in the
14813         * destination.
14814         */
14815        int doPostCopy(int uid) {
14816            return PackageManager.INSTALL_SUCCEEDED;
14817        }
14818
14819        protected boolean isFwdLocked() {
14820            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
14821        }
14822
14823        protected boolean isExternalAsec() {
14824            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
14825        }
14826
14827        protected boolean isEphemeral() {
14828            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14829        }
14830
14831        UserHandle getUser() {
14832            return user;
14833        }
14834    }
14835
14836    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
14837        if (!allCodePaths.isEmpty()) {
14838            if (instructionSets == null) {
14839                throw new IllegalStateException("instructionSet == null");
14840            }
14841            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
14842            for (String codePath : allCodePaths) {
14843                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
14844                    try {
14845                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
14846                    } catch (InstallerException ignored) {
14847                    }
14848                }
14849            }
14850        }
14851    }
14852
14853    /**
14854     * Logic to handle installation of non-ASEC applications, including copying
14855     * and renaming logic.
14856     */
14857    class FileInstallArgs extends InstallArgs {
14858        private File codeFile;
14859        private File resourceFile;
14860
14861        // Example topology:
14862        // /data/app/com.example/base.apk
14863        // /data/app/com.example/split_foo.apk
14864        // /data/app/com.example/lib/arm/libfoo.so
14865        // /data/app/com.example/lib/arm64/libfoo.so
14866        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
14867
14868        /** New install */
14869        FileInstallArgs(InstallParams params) {
14870            super(params.origin, params.move, params.observer, params.installFlags,
14871                    params.installerPackageName, params.volumeUuid,
14872                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
14873                    params.grantedRuntimePermissions,
14874                    params.traceMethod, params.traceCookie, params.certificates,
14875                    params.installReason);
14876            if (isFwdLocked()) {
14877                throw new IllegalArgumentException("Forward locking only supported in ASEC");
14878            }
14879        }
14880
14881        /** Existing install */
14882        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
14883            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
14884                    null, null, null, 0, null /*certificates*/,
14885                    PackageManager.INSTALL_REASON_UNKNOWN);
14886            this.codeFile = (codePath != null) ? new File(codePath) : null;
14887            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
14888        }
14889
14890        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14891            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
14892            try {
14893                return doCopyApk(imcs, temp);
14894            } finally {
14895                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14896            }
14897        }
14898
14899        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
14900            if (origin.staged) {
14901                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
14902                codeFile = origin.file;
14903                resourceFile = origin.file;
14904                return PackageManager.INSTALL_SUCCEEDED;
14905            }
14906
14907            try {
14908                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
14909                final File tempDir =
14910                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
14911                codeFile = tempDir;
14912                resourceFile = tempDir;
14913            } catch (IOException e) {
14914                Slog.w(TAG, "Failed to create copy file: " + e);
14915                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
14916            }
14917
14918            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
14919                @Override
14920                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
14921                    if (!FileUtils.isValidExtFilename(name)) {
14922                        throw new IllegalArgumentException("Invalid filename: " + name);
14923                    }
14924                    try {
14925                        final File file = new File(codeFile, name);
14926                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
14927                                O_RDWR | O_CREAT, 0644);
14928                        Os.chmod(file.getAbsolutePath(), 0644);
14929                        return new ParcelFileDescriptor(fd);
14930                    } catch (ErrnoException e) {
14931                        throw new RemoteException("Failed to open: " + e.getMessage());
14932                    }
14933                }
14934            };
14935
14936            int ret = PackageManager.INSTALL_SUCCEEDED;
14937            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
14938            if (ret != PackageManager.INSTALL_SUCCEEDED) {
14939                Slog.e(TAG, "Failed to copy package");
14940                return ret;
14941            }
14942
14943            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
14944            NativeLibraryHelper.Handle handle = null;
14945            try {
14946                handle = NativeLibraryHelper.Handle.create(codeFile);
14947                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
14948                        abiOverride);
14949            } catch (IOException e) {
14950                Slog.e(TAG, "Copying native libraries failed", e);
14951                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
14952            } finally {
14953                IoUtils.closeQuietly(handle);
14954            }
14955
14956            return ret;
14957        }
14958
14959        int doPreInstall(int status) {
14960            if (status != PackageManager.INSTALL_SUCCEEDED) {
14961                cleanUp();
14962            }
14963            return status;
14964        }
14965
14966        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
14967            if (status != PackageManager.INSTALL_SUCCEEDED) {
14968                cleanUp();
14969                return false;
14970            }
14971
14972            final File targetDir = codeFile.getParentFile();
14973            final File beforeCodeFile = codeFile;
14974            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
14975
14976            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
14977            try {
14978                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
14979            } catch (ErrnoException e) {
14980                Slog.w(TAG, "Failed to rename", e);
14981                return false;
14982            }
14983
14984            if (!SELinux.restoreconRecursive(afterCodeFile)) {
14985                Slog.w(TAG, "Failed to restorecon");
14986                return false;
14987            }
14988
14989            // Reflect the rename internally
14990            codeFile = afterCodeFile;
14991            resourceFile = afterCodeFile;
14992
14993            // Reflect the rename in scanned details
14994            pkg.setCodePath(afterCodeFile.getAbsolutePath());
14995            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
14996                    afterCodeFile, pkg.baseCodePath));
14997            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
14998                    afterCodeFile, pkg.splitCodePaths));
14999
15000            // Reflect the rename in app info
15001            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15002            pkg.setApplicationInfoCodePath(pkg.codePath);
15003            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15004            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15005            pkg.setApplicationInfoResourcePath(pkg.codePath);
15006            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15007            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15008
15009            return true;
15010        }
15011
15012        int doPostInstall(int status, int uid) {
15013            if (status != PackageManager.INSTALL_SUCCEEDED) {
15014                cleanUp();
15015            }
15016            return status;
15017        }
15018
15019        @Override
15020        String getCodePath() {
15021            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15022        }
15023
15024        @Override
15025        String getResourcePath() {
15026            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15027        }
15028
15029        private boolean cleanUp() {
15030            if (codeFile == null || !codeFile.exists()) {
15031                return false;
15032            }
15033
15034            removeCodePathLI(codeFile);
15035
15036            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15037                resourceFile.delete();
15038            }
15039
15040            return true;
15041        }
15042
15043        void cleanUpResourcesLI() {
15044            // Try enumerating all code paths before deleting
15045            List<String> allCodePaths = Collections.EMPTY_LIST;
15046            if (codeFile != null && codeFile.exists()) {
15047                try {
15048                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15049                    allCodePaths = pkg.getAllCodePaths();
15050                } catch (PackageParserException e) {
15051                    // Ignored; we tried our best
15052                }
15053            }
15054
15055            cleanUp();
15056            removeDexFiles(allCodePaths, instructionSets);
15057        }
15058
15059        boolean doPostDeleteLI(boolean delete) {
15060            // XXX err, shouldn't we respect the delete flag?
15061            cleanUpResourcesLI();
15062            return true;
15063        }
15064    }
15065
15066    private boolean isAsecExternal(String cid) {
15067        final String asecPath = PackageHelper.getSdFilesystem(cid);
15068        return !asecPath.startsWith(mAsecInternalPath);
15069    }
15070
15071    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15072            PackageManagerException {
15073        if (copyRet < 0) {
15074            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15075                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15076                throw new PackageManagerException(copyRet, message);
15077            }
15078        }
15079    }
15080
15081    /**
15082     * Extract the StorageManagerService "container ID" from the full code path of an
15083     * .apk.
15084     */
15085    static String cidFromCodePath(String fullCodePath) {
15086        int eidx = fullCodePath.lastIndexOf("/");
15087        String subStr1 = fullCodePath.substring(0, eidx);
15088        int sidx = subStr1.lastIndexOf("/");
15089        return subStr1.substring(sidx+1, eidx);
15090    }
15091
15092    /**
15093     * Logic to handle installation of ASEC applications, including copying and
15094     * renaming logic.
15095     */
15096    class AsecInstallArgs extends InstallArgs {
15097        static final String RES_FILE_NAME = "pkg.apk";
15098        static final String PUBLIC_RES_FILE_NAME = "res.zip";
15099
15100        String cid;
15101        String packagePath;
15102        String resourcePath;
15103
15104        /** New install */
15105        AsecInstallArgs(InstallParams params) {
15106            super(params.origin, params.move, params.observer, params.installFlags,
15107                    params.installerPackageName, params.volumeUuid,
15108                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15109                    params.grantedRuntimePermissions,
15110                    params.traceMethod, params.traceCookie, params.certificates,
15111                    params.installReason);
15112        }
15113
15114        /** Existing install */
15115        AsecInstallArgs(String fullCodePath, String[] instructionSets,
15116                        boolean isExternal, boolean isForwardLocked) {
15117            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
15118                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15119                    instructionSets, null, null, null, 0, null /*certificates*/,
15120                    PackageManager.INSTALL_REASON_UNKNOWN);
15121            // Hackily pretend we're still looking at a full code path
15122            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
15123                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
15124            }
15125
15126            // Extract cid from fullCodePath
15127            int eidx = fullCodePath.lastIndexOf("/");
15128            String subStr1 = fullCodePath.substring(0, eidx);
15129            int sidx = subStr1.lastIndexOf("/");
15130            cid = subStr1.substring(sidx+1, eidx);
15131            setMountPath(subStr1);
15132        }
15133
15134        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
15135            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
15136                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
15137                    instructionSets, null, null, null, 0, null /*certificates*/,
15138                    PackageManager.INSTALL_REASON_UNKNOWN);
15139            this.cid = cid;
15140            setMountPath(PackageHelper.getSdDir(cid));
15141        }
15142
15143        void createCopyFile() {
15144            cid = mInstallerService.allocateExternalStageCidLegacy();
15145        }
15146
15147        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15148            if (origin.staged && origin.cid != null) {
15149                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
15150                cid = origin.cid;
15151                setMountPath(PackageHelper.getSdDir(cid));
15152                return PackageManager.INSTALL_SUCCEEDED;
15153            }
15154
15155            if (temp) {
15156                createCopyFile();
15157            } else {
15158                /*
15159                 * Pre-emptively destroy the container since it's destroyed if
15160                 * copying fails due to it existing anyway.
15161                 */
15162                PackageHelper.destroySdDir(cid);
15163            }
15164
15165            final String newMountPath = imcs.copyPackageToContainer(
15166                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
15167                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
15168
15169            if (newMountPath != null) {
15170                setMountPath(newMountPath);
15171                return PackageManager.INSTALL_SUCCEEDED;
15172            } else {
15173                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15174            }
15175        }
15176
15177        @Override
15178        String getCodePath() {
15179            return packagePath;
15180        }
15181
15182        @Override
15183        String getResourcePath() {
15184            return resourcePath;
15185        }
15186
15187        int doPreInstall(int status) {
15188            if (status != PackageManager.INSTALL_SUCCEEDED) {
15189                // Destroy container
15190                PackageHelper.destroySdDir(cid);
15191            } else {
15192                boolean mounted = PackageHelper.isContainerMounted(cid);
15193                if (!mounted) {
15194                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
15195                            Process.SYSTEM_UID);
15196                    if (newMountPath != null) {
15197                        setMountPath(newMountPath);
15198                    } else {
15199                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15200                    }
15201                }
15202            }
15203            return status;
15204        }
15205
15206        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15207            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
15208            String newMountPath = null;
15209            if (PackageHelper.isContainerMounted(cid)) {
15210                // Unmount the container
15211                if (!PackageHelper.unMountSdDir(cid)) {
15212                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
15213                    return false;
15214                }
15215            }
15216            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15217                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
15218                        " which might be stale. Will try to clean up.");
15219                // Clean up the stale container and proceed to recreate.
15220                if (!PackageHelper.destroySdDir(newCacheId)) {
15221                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
15222                    return false;
15223                }
15224                // Successfully cleaned up stale container. Try to rename again.
15225                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
15226                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
15227                            + " inspite of cleaning it up.");
15228                    return false;
15229                }
15230            }
15231            if (!PackageHelper.isContainerMounted(newCacheId)) {
15232                Slog.w(TAG, "Mounting container " + newCacheId);
15233                newMountPath = PackageHelper.mountSdDir(newCacheId,
15234                        getEncryptKey(), Process.SYSTEM_UID);
15235            } else {
15236                newMountPath = PackageHelper.getSdDir(newCacheId);
15237            }
15238            if (newMountPath == null) {
15239                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
15240                return false;
15241            }
15242            Log.i(TAG, "Succesfully renamed " + cid +
15243                    " to " + newCacheId +
15244                    " at new path: " + newMountPath);
15245            cid = newCacheId;
15246
15247            final File beforeCodeFile = new File(packagePath);
15248            setMountPath(newMountPath);
15249            final File afterCodeFile = new File(packagePath);
15250
15251            // Reflect the rename in scanned details
15252            pkg.setCodePath(afterCodeFile.getAbsolutePath());
15253            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15254                    afterCodeFile, pkg.baseCodePath));
15255            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15256                    afterCodeFile, pkg.splitCodePaths));
15257
15258            // Reflect the rename in app info
15259            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15260            pkg.setApplicationInfoCodePath(pkg.codePath);
15261            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15262            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15263            pkg.setApplicationInfoResourcePath(pkg.codePath);
15264            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15265            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15266
15267            return true;
15268        }
15269
15270        private void setMountPath(String mountPath) {
15271            final File mountFile = new File(mountPath);
15272
15273            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
15274            if (monolithicFile.exists()) {
15275                packagePath = monolithicFile.getAbsolutePath();
15276                if (isFwdLocked()) {
15277                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
15278                } else {
15279                    resourcePath = packagePath;
15280                }
15281            } else {
15282                packagePath = mountFile.getAbsolutePath();
15283                resourcePath = packagePath;
15284            }
15285        }
15286
15287        int doPostInstall(int status, int uid) {
15288            if (status != PackageManager.INSTALL_SUCCEEDED) {
15289                cleanUp();
15290            } else {
15291                final int groupOwner;
15292                final String protectedFile;
15293                if (isFwdLocked()) {
15294                    groupOwner = UserHandle.getSharedAppGid(uid);
15295                    protectedFile = RES_FILE_NAME;
15296                } else {
15297                    groupOwner = -1;
15298                    protectedFile = null;
15299                }
15300
15301                if (uid < Process.FIRST_APPLICATION_UID
15302                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
15303                    Slog.e(TAG, "Failed to finalize " + cid);
15304                    PackageHelper.destroySdDir(cid);
15305                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15306                }
15307
15308                boolean mounted = PackageHelper.isContainerMounted(cid);
15309                if (!mounted) {
15310                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
15311                }
15312            }
15313            return status;
15314        }
15315
15316        private void cleanUp() {
15317            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
15318
15319            // Destroy secure container
15320            PackageHelper.destroySdDir(cid);
15321        }
15322
15323        private List<String> getAllCodePaths() {
15324            final File codeFile = new File(getCodePath());
15325            if (codeFile != null && codeFile.exists()) {
15326                try {
15327                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15328                    return pkg.getAllCodePaths();
15329                } catch (PackageParserException e) {
15330                    // Ignored; we tried our best
15331                }
15332            }
15333            return Collections.EMPTY_LIST;
15334        }
15335
15336        void cleanUpResourcesLI() {
15337            // Enumerate all code paths before deleting
15338            cleanUpResourcesLI(getAllCodePaths());
15339        }
15340
15341        private void cleanUpResourcesLI(List<String> allCodePaths) {
15342            cleanUp();
15343            removeDexFiles(allCodePaths, instructionSets);
15344        }
15345
15346        String getPackageName() {
15347            return getAsecPackageName(cid);
15348        }
15349
15350        boolean doPostDeleteLI(boolean delete) {
15351            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
15352            final List<String> allCodePaths = getAllCodePaths();
15353            boolean mounted = PackageHelper.isContainerMounted(cid);
15354            if (mounted) {
15355                // Unmount first
15356                if (PackageHelper.unMountSdDir(cid)) {
15357                    mounted = false;
15358                }
15359            }
15360            if (!mounted && delete) {
15361                cleanUpResourcesLI(allCodePaths);
15362            }
15363            return !mounted;
15364        }
15365
15366        @Override
15367        int doPreCopy() {
15368            if (isFwdLocked()) {
15369                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
15370                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
15371                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15372                }
15373            }
15374
15375            return PackageManager.INSTALL_SUCCEEDED;
15376        }
15377
15378        @Override
15379        int doPostCopy(int uid) {
15380            if (isFwdLocked()) {
15381                if (uid < Process.FIRST_APPLICATION_UID
15382                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
15383                                RES_FILE_NAME)) {
15384                    Slog.e(TAG, "Failed to finalize " + cid);
15385                    PackageHelper.destroySdDir(cid);
15386                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15387                }
15388            }
15389
15390            return PackageManager.INSTALL_SUCCEEDED;
15391        }
15392    }
15393
15394    /**
15395     * Logic to handle movement of existing installed applications.
15396     */
15397    class MoveInstallArgs extends InstallArgs {
15398        private File codeFile;
15399        private File resourceFile;
15400
15401        /** New install */
15402        MoveInstallArgs(InstallParams params) {
15403            super(params.origin, params.move, params.observer, params.installFlags,
15404                    params.installerPackageName, params.volumeUuid,
15405                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15406                    params.grantedRuntimePermissions,
15407                    params.traceMethod, params.traceCookie, params.certificates,
15408                    params.installReason);
15409        }
15410
15411        int copyApk(IMediaContainerService imcs, boolean temp) {
15412            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15413                    + move.fromUuid + " to " + move.toUuid);
15414            synchronized (mInstaller) {
15415                try {
15416                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15417                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15418                } catch (InstallerException e) {
15419                    Slog.w(TAG, "Failed to move app", e);
15420                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15421                }
15422            }
15423
15424            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15425            resourceFile = codeFile;
15426            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15427
15428            return PackageManager.INSTALL_SUCCEEDED;
15429        }
15430
15431        int doPreInstall(int status) {
15432            if (status != PackageManager.INSTALL_SUCCEEDED) {
15433                cleanUp(move.toUuid);
15434            }
15435            return status;
15436        }
15437
15438        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15439            if (status != PackageManager.INSTALL_SUCCEEDED) {
15440                cleanUp(move.toUuid);
15441                return false;
15442            }
15443
15444            // Reflect the move in app info
15445            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15446            pkg.setApplicationInfoCodePath(pkg.codePath);
15447            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15448            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15449            pkg.setApplicationInfoResourcePath(pkg.codePath);
15450            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15451            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15452
15453            return true;
15454        }
15455
15456        int doPostInstall(int status, int uid) {
15457            if (status == PackageManager.INSTALL_SUCCEEDED) {
15458                cleanUp(move.fromUuid);
15459            } else {
15460                cleanUp(move.toUuid);
15461            }
15462            return status;
15463        }
15464
15465        @Override
15466        String getCodePath() {
15467            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15468        }
15469
15470        @Override
15471        String getResourcePath() {
15472            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15473        }
15474
15475        private boolean cleanUp(String volumeUuid) {
15476            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15477                    move.dataAppName);
15478            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15479            final int[] userIds = sUserManager.getUserIds();
15480            synchronized (mInstallLock) {
15481                // Clean up both app data and code
15482                // All package moves are frozen until finished
15483                for (int userId : userIds) {
15484                    try {
15485                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15486                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15487                    } catch (InstallerException e) {
15488                        Slog.w(TAG, String.valueOf(e));
15489                    }
15490                }
15491                removeCodePathLI(codeFile);
15492            }
15493            return true;
15494        }
15495
15496        void cleanUpResourcesLI() {
15497            throw new UnsupportedOperationException();
15498        }
15499
15500        boolean doPostDeleteLI(boolean delete) {
15501            throw new UnsupportedOperationException();
15502        }
15503    }
15504
15505    static String getAsecPackageName(String packageCid) {
15506        int idx = packageCid.lastIndexOf("-");
15507        if (idx == -1) {
15508            return packageCid;
15509        }
15510        return packageCid.substring(0, idx);
15511    }
15512
15513    // Utility method used to create code paths based on package name and available index.
15514    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15515        String idxStr = "";
15516        int idx = 1;
15517        // Fall back to default value of idx=1 if prefix is not
15518        // part of oldCodePath
15519        if (oldCodePath != null) {
15520            String subStr = oldCodePath;
15521            // Drop the suffix right away
15522            if (suffix != null && subStr.endsWith(suffix)) {
15523                subStr = subStr.substring(0, subStr.length() - suffix.length());
15524            }
15525            // If oldCodePath already contains prefix find out the
15526            // ending index to either increment or decrement.
15527            int sidx = subStr.lastIndexOf(prefix);
15528            if (sidx != -1) {
15529                subStr = subStr.substring(sidx + prefix.length());
15530                if (subStr != null) {
15531                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15532                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15533                    }
15534                    try {
15535                        idx = Integer.parseInt(subStr);
15536                        if (idx <= 1) {
15537                            idx++;
15538                        } else {
15539                            idx--;
15540                        }
15541                    } catch(NumberFormatException e) {
15542                    }
15543                }
15544            }
15545        }
15546        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15547        return prefix + idxStr;
15548    }
15549
15550    private File getNextCodePath(File targetDir, String packageName) {
15551        File result;
15552        SecureRandom random = new SecureRandom();
15553        byte[] bytes = new byte[16];
15554        do {
15555            random.nextBytes(bytes);
15556            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15557            result = new File(targetDir, packageName + "-" + suffix);
15558        } while (result.exists());
15559        return result;
15560    }
15561
15562    // Utility method that returns the relative package path with respect
15563    // to the installation directory. Like say for /data/data/com.test-1.apk
15564    // string com.test-1 is returned.
15565    static String deriveCodePathName(String codePath) {
15566        if (codePath == null) {
15567            return null;
15568        }
15569        final File codeFile = new File(codePath);
15570        final String name = codeFile.getName();
15571        if (codeFile.isDirectory()) {
15572            return name;
15573        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15574            final int lastDot = name.lastIndexOf('.');
15575            return name.substring(0, lastDot);
15576        } else {
15577            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15578            return null;
15579        }
15580    }
15581
15582    static class PackageInstalledInfo {
15583        String name;
15584        int uid;
15585        // The set of users that originally had this package installed.
15586        int[] origUsers;
15587        // The set of users that now have this package installed.
15588        int[] newUsers;
15589        PackageParser.Package pkg;
15590        int returnCode;
15591        String returnMsg;
15592        PackageRemovedInfo removedInfo;
15593        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15594
15595        public void setError(int code, String msg) {
15596            setReturnCode(code);
15597            setReturnMessage(msg);
15598            Slog.w(TAG, msg);
15599        }
15600
15601        public void setError(String msg, PackageParserException e) {
15602            setReturnCode(e.error);
15603            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15604            Slog.w(TAG, msg, e);
15605        }
15606
15607        public void setError(String msg, PackageManagerException e) {
15608            returnCode = e.error;
15609            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15610            Slog.w(TAG, msg, e);
15611        }
15612
15613        public void setReturnCode(int returnCode) {
15614            this.returnCode = returnCode;
15615            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15616            for (int i = 0; i < childCount; i++) {
15617                addedChildPackages.valueAt(i).returnCode = returnCode;
15618            }
15619        }
15620
15621        private void setReturnMessage(String returnMsg) {
15622            this.returnMsg = returnMsg;
15623            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15624            for (int i = 0; i < childCount; i++) {
15625                addedChildPackages.valueAt(i).returnMsg = returnMsg;
15626            }
15627        }
15628
15629        // In some error cases we want to convey more info back to the observer
15630        String origPackage;
15631        String origPermission;
15632    }
15633
15634    /*
15635     * Install a non-existing package.
15636     */
15637    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
15638            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
15639            PackageInstalledInfo res, int installReason) {
15640        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
15641
15642        // Remember this for later, in case we need to rollback this install
15643        String pkgName = pkg.packageName;
15644
15645        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
15646
15647        synchronized(mPackages) {
15648            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
15649            if (renamedPackage != null) {
15650                // A package with the same name is already installed, though
15651                // it has been renamed to an older name.  The package we
15652                // are trying to install should be installed as an update to
15653                // the existing one, but that has not been requested, so bail.
15654                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15655                        + " without first uninstalling package running as "
15656                        + renamedPackage);
15657                return;
15658            }
15659            if (mPackages.containsKey(pkgName)) {
15660                // Don't allow installation over an existing package with the same name.
15661                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
15662                        + " without first uninstalling.");
15663                return;
15664            }
15665        }
15666
15667        try {
15668            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
15669                    System.currentTimeMillis(), user);
15670
15671            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
15672
15673            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15674                prepareAppDataAfterInstallLIF(newPackage);
15675
15676            } else {
15677                // Remove package from internal structures, but keep around any
15678                // data that might have already existed
15679                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
15680                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
15681            }
15682        } catch (PackageManagerException e) {
15683            res.setError("Package couldn't be installed in " + pkg.codePath, e);
15684        }
15685
15686        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15687    }
15688
15689    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
15690        // Can't rotate keys during boot or if sharedUser.
15691        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
15692                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
15693            return false;
15694        }
15695        // app is using upgradeKeySets; make sure all are valid
15696        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15697        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
15698        for (int i = 0; i < upgradeKeySets.length; i++) {
15699            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
15700                Slog.wtf(TAG, "Package "
15701                         + (oldPs.name != null ? oldPs.name : "<null>")
15702                         + " contains upgrade-key-set reference to unknown key-set: "
15703                         + upgradeKeySets[i]
15704                         + " reverting to signatures check.");
15705                return false;
15706            }
15707        }
15708        return true;
15709    }
15710
15711    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
15712        // Upgrade keysets are being used.  Determine if new package has a superset of the
15713        // required keys.
15714        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
15715        KeySetManagerService ksms = mSettings.mKeySetManagerService;
15716        for (int i = 0; i < upgradeKeySets.length; i++) {
15717            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
15718            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
15719                return true;
15720            }
15721        }
15722        return false;
15723    }
15724
15725    private static void updateDigest(MessageDigest digest, File file) throws IOException {
15726        try (DigestInputStream digestStream =
15727                new DigestInputStream(new FileInputStream(file), digest)) {
15728            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
15729        }
15730    }
15731
15732    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
15733            UserHandle user, String installerPackageName, PackageInstalledInfo res,
15734            int installReason) {
15735        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
15736
15737        final PackageParser.Package oldPackage;
15738        final String pkgName = pkg.packageName;
15739        final int[] allUsers;
15740        final int[] installedUsers;
15741
15742        synchronized(mPackages) {
15743            oldPackage = mPackages.get(pkgName);
15744            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
15745
15746            // don't allow upgrade to target a release SDK from a pre-release SDK
15747            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
15748                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15749            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
15750                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
15751            if (oldTargetsPreRelease
15752                    && !newTargetsPreRelease
15753                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
15754                Slog.w(TAG, "Can't install package targeting released sdk");
15755                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
15756                return;
15757            }
15758
15759            // don't allow an upgrade from full to ephemeral
15760            final boolean oldIsEphemeral = oldPackage.applicationInfo.isInstantApp();
15761            if (isEphemeral && !oldIsEphemeral) {
15762                // can't downgrade from full to ephemeral
15763                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
15764                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
15765                return;
15766            }
15767
15768            // verify signatures are valid
15769            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15770            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15771                if (!checkUpgradeKeySetLP(ps, pkg)) {
15772                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15773                            "New package not signed by keys specified by upgrade-keysets: "
15774                                    + pkgName);
15775                    return;
15776                }
15777            } else {
15778                // default to original signature matching
15779                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
15780                        != PackageManager.SIGNATURE_MATCH) {
15781                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
15782                            "New package has a different signature: " + pkgName);
15783                    return;
15784                }
15785            }
15786
15787            // don't allow a system upgrade unless the upgrade hash matches
15788            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
15789                byte[] digestBytes = null;
15790                try {
15791                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
15792                    updateDigest(digest, new File(pkg.baseCodePath));
15793                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
15794                        for (String path : pkg.splitCodePaths) {
15795                            updateDigest(digest, new File(path));
15796                        }
15797                    }
15798                    digestBytes = digest.digest();
15799                } catch (NoSuchAlgorithmException | IOException e) {
15800                    res.setError(INSTALL_FAILED_INVALID_APK,
15801                            "Could not compute hash: " + pkgName);
15802                    return;
15803                }
15804                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
15805                    res.setError(INSTALL_FAILED_INVALID_APK,
15806                            "New package fails restrict-update check: " + pkgName);
15807                    return;
15808                }
15809                // retain upgrade restriction
15810                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
15811            }
15812
15813            // Check for shared user id changes
15814            String invalidPackageName =
15815                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
15816            if (invalidPackageName != null) {
15817                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
15818                        "Package " + invalidPackageName + " tried to change user "
15819                                + oldPackage.mSharedUserId);
15820                return;
15821            }
15822
15823            // In case of rollback, remember per-user/profile install state
15824            allUsers = sUserManager.getUserIds();
15825            installedUsers = ps.queryInstalledUsers(allUsers, true);
15826        }
15827
15828        // Update what is removed
15829        res.removedInfo = new PackageRemovedInfo();
15830        res.removedInfo.uid = oldPackage.applicationInfo.uid;
15831        res.removedInfo.removedPackage = oldPackage.packageName;
15832        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
15833        res.removedInfo.isUpdate = true;
15834        res.removedInfo.origUsers = installedUsers;
15835        final PackageSetting ps = mSettings.getPackageLPr(pkgName);
15836        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
15837        for (int i = 0; i < installedUsers.length; i++) {
15838            final int userId = installedUsers[i];
15839            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
15840        }
15841
15842        final int childCount = (oldPackage.childPackages != null)
15843                ? oldPackage.childPackages.size() : 0;
15844        for (int i = 0; i < childCount; i++) {
15845            boolean childPackageUpdated = false;
15846            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
15847            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
15848            if (res.addedChildPackages != null) {
15849                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15850                if (childRes != null) {
15851                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
15852                    childRes.removedInfo.removedPackage = childPkg.packageName;
15853                    childRes.removedInfo.isUpdate = true;
15854                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
15855                    childPackageUpdated = true;
15856                }
15857            }
15858            if (!childPackageUpdated) {
15859                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
15860                childRemovedRes.removedPackage = childPkg.packageName;
15861                childRemovedRes.isUpdate = false;
15862                childRemovedRes.dataRemoved = true;
15863                synchronized (mPackages) {
15864                    if (childPs != null) {
15865                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
15866                    }
15867                }
15868                if (res.removedInfo.removedChildPackages == null) {
15869                    res.removedInfo.removedChildPackages = new ArrayMap<>();
15870                }
15871                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
15872            }
15873        }
15874
15875        boolean sysPkg = (isSystemApp(oldPackage));
15876        if (sysPkg) {
15877            // Set the system/privileged flags as needed
15878            final boolean privileged =
15879                    (oldPackage.applicationInfo.privateFlags
15880                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15881            final int systemPolicyFlags = policyFlags
15882                    | PackageParser.PARSE_IS_SYSTEM
15883                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
15884
15885            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
15886                    user, allUsers, installerPackageName, res, installReason);
15887        } else {
15888            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
15889                    user, allUsers, installerPackageName, res, installReason);
15890        }
15891    }
15892
15893    public List<String> getPreviousCodePaths(String packageName) {
15894        final PackageSetting ps = mSettings.mPackages.get(packageName);
15895        final List<String> result = new ArrayList<String>();
15896        if (ps != null && ps.oldCodePaths != null) {
15897            result.addAll(ps.oldCodePaths);
15898        }
15899        return result;
15900    }
15901
15902    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
15903            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
15904            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
15905            int installReason) {
15906        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
15907                + deletedPackage);
15908
15909        String pkgName = deletedPackage.packageName;
15910        boolean deletedPkg = true;
15911        boolean addedPkg = false;
15912        boolean updatedSettings = false;
15913        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
15914        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
15915                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
15916
15917        final long origUpdateTime = (pkg.mExtras != null)
15918                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
15919
15920        // First delete the existing package while retaining the data directory
15921        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15922                res.removedInfo, true, pkg)) {
15923            // If the existing package wasn't successfully deleted
15924            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
15925            deletedPkg = false;
15926        } else {
15927            // Successfully deleted the old package; proceed with replace.
15928
15929            // If deleted package lived in a container, give users a chance to
15930            // relinquish resources before killing.
15931            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
15932                if (DEBUG_INSTALL) {
15933                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
15934                }
15935                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
15936                final ArrayList<String> pkgList = new ArrayList<String>(1);
15937                pkgList.add(deletedPackage.applicationInfo.packageName);
15938                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
15939            }
15940
15941            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
15942                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
15943            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
15944
15945            try {
15946                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
15947                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
15948                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
15949                        installReason);
15950
15951                // Update the in-memory copy of the previous code paths.
15952                PackageSetting ps = mSettings.mPackages.get(pkgName);
15953                if (!killApp) {
15954                    if (ps.oldCodePaths == null) {
15955                        ps.oldCodePaths = new ArraySet<>();
15956                    }
15957                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
15958                    if (deletedPackage.splitCodePaths != null) {
15959                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
15960                    }
15961                } else {
15962                    ps.oldCodePaths = null;
15963                }
15964                if (ps.childPackageNames != null) {
15965                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
15966                        final String childPkgName = ps.childPackageNames.get(i);
15967                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
15968                        childPs.oldCodePaths = ps.oldCodePaths;
15969                    }
15970                }
15971                prepareAppDataAfterInstallLIF(newPackage);
15972                addedPkg = true;
15973            } catch (PackageManagerException e) {
15974                res.setError("Package couldn't be installed in " + pkg.codePath, e);
15975            }
15976        }
15977
15978        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15979            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
15980
15981            // Revert all internal state mutations and added folders for the failed install
15982            if (addedPkg) {
15983                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
15984                        res.removedInfo, true, null);
15985            }
15986
15987            // Restore the old package
15988            if (deletedPkg) {
15989                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
15990                File restoreFile = new File(deletedPackage.codePath);
15991                // Parse old package
15992                boolean oldExternal = isExternal(deletedPackage);
15993                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
15994                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
15995                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
15996                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
15997                try {
15998                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
15999                            null);
16000                } catch (PackageManagerException e) {
16001                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16002                            + e.getMessage());
16003                    return;
16004                }
16005
16006                synchronized (mPackages) {
16007                    // Ensure the installer package name up to date
16008                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16009
16010                    // Update permissions for restored package
16011                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16012
16013                    mSettings.writeLPr();
16014                }
16015
16016                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16017            }
16018        } else {
16019            synchronized (mPackages) {
16020                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16021                if (ps != null) {
16022                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16023                    if (res.removedInfo.removedChildPackages != null) {
16024                        final int childCount = res.removedInfo.removedChildPackages.size();
16025                        // Iterate in reverse as we may modify the collection
16026                        for (int i = childCount - 1; i >= 0; i--) {
16027                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16028                            if (res.addedChildPackages.containsKey(childPackageName)) {
16029                                res.removedInfo.removedChildPackages.removeAt(i);
16030                            } else {
16031                                PackageRemovedInfo childInfo = res.removedInfo
16032                                        .removedChildPackages.valueAt(i);
16033                                childInfo.removedForAllUsers = mPackages.get(
16034                                        childInfo.removedPackage) == null;
16035                            }
16036                        }
16037                    }
16038                }
16039            }
16040        }
16041    }
16042
16043    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16044            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
16045            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16046            int installReason) {
16047        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16048                + ", old=" + deletedPackage);
16049
16050        final boolean disabledSystem;
16051
16052        // Remove existing system package
16053        removePackageLI(deletedPackage, true);
16054
16055        synchronized (mPackages) {
16056            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16057        }
16058        if (!disabledSystem) {
16059            // We didn't need to disable the .apk as a current system package,
16060            // which means we are replacing another update that is already
16061            // installed.  We need to make sure to delete the older one's .apk.
16062            res.removedInfo.args = createInstallArgsForExisting(0,
16063                    deletedPackage.applicationInfo.getCodePath(),
16064                    deletedPackage.applicationInfo.getResourcePath(),
16065                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16066        } else {
16067            res.removedInfo.args = null;
16068        }
16069
16070        // Successfully disabled the old package. Now proceed with re-installation
16071        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16072                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16073        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
16074
16075        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16076        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16077                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16078
16079        PackageParser.Package newPackage = null;
16080        try {
16081            // Add the package to the internal data structures
16082            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
16083
16084            // Set the update and install times
16085            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16086            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16087                    System.currentTimeMillis());
16088
16089            // Update the package dynamic state if succeeded
16090            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16091                // Now that the install succeeded make sure we remove data
16092                // directories for any child package the update removed.
16093                final int deletedChildCount = (deletedPackage.childPackages != null)
16094                        ? deletedPackage.childPackages.size() : 0;
16095                final int newChildCount = (newPackage.childPackages != null)
16096                        ? newPackage.childPackages.size() : 0;
16097                for (int i = 0; i < deletedChildCount; i++) {
16098                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16099                    boolean childPackageDeleted = true;
16100                    for (int j = 0; j < newChildCount; j++) {
16101                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16102                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16103                            childPackageDeleted = false;
16104                            break;
16105                        }
16106                    }
16107                    if (childPackageDeleted) {
16108                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16109                                deletedChildPkg.packageName);
16110                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16111                            PackageRemovedInfo removedChildRes = res.removedInfo
16112                                    .removedChildPackages.get(deletedChildPkg.packageName);
16113                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16114                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16115                        }
16116                    }
16117                }
16118
16119                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16120                        installReason);
16121                prepareAppDataAfterInstallLIF(newPackage);
16122            }
16123        } catch (PackageManagerException e) {
16124            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16125            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16126        }
16127
16128        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16129            // Re installation failed. Restore old information
16130            // Remove new pkg information
16131            if (newPackage != null) {
16132                removeInstalledPackageLI(newPackage, true);
16133            }
16134            // Add back the old system package
16135            try {
16136                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16137            } catch (PackageManagerException e) {
16138                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16139            }
16140
16141            synchronized (mPackages) {
16142                if (disabledSystem) {
16143                    enableSystemPackageLPw(deletedPackage);
16144                }
16145
16146                // Ensure the installer package name up to date
16147                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16148
16149                // Update permissions for restored package
16150                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
16151
16152                mSettings.writeLPr();
16153            }
16154
16155            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16156                    + " after failed upgrade");
16157        }
16158    }
16159
16160    /**
16161     * Checks whether the parent or any of the child packages have a change shared
16162     * user. For a package to be a valid update the shred users of the parent and
16163     * the children should match. We may later support changing child shared users.
16164     * @param oldPkg The updated package.
16165     * @param newPkg The update package.
16166     * @return The shared user that change between the versions.
16167     */
16168    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16169            PackageParser.Package newPkg) {
16170        // Check parent shared user
16171        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16172            return newPkg.packageName;
16173        }
16174        // Check child shared users
16175        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16176        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16177        for (int i = 0; i < newChildCount; i++) {
16178            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16179            // If this child was present, did it have the same shared user?
16180            for (int j = 0; j < oldChildCount; j++) {
16181                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16182                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16183                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16184                    return newChildPkg.packageName;
16185                }
16186            }
16187        }
16188        return null;
16189    }
16190
16191    private void removeNativeBinariesLI(PackageSetting ps) {
16192        // Remove the lib path for the parent package
16193        if (ps != null) {
16194            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16195            // Remove the lib path for the child packages
16196            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16197            for (int i = 0; i < childCount; i++) {
16198                PackageSetting childPs = null;
16199                synchronized (mPackages) {
16200                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16201                }
16202                if (childPs != null) {
16203                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16204                            .legacyNativeLibraryPathString);
16205                }
16206            }
16207        }
16208    }
16209
16210    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16211        // Enable the parent package
16212        mSettings.enableSystemPackageLPw(pkg.packageName);
16213        // Enable the child packages
16214        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16215        for (int i = 0; i < childCount; i++) {
16216            PackageParser.Package childPkg = pkg.childPackages.get(i);
16217            mSettings.enableSystemPackageLPw(childPkg.packageName);
16218        }
16219    }
16220
16221    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16222            PackageParser.Package newPkg) {
16223        // Disable the parent package (parent always replaced)
16224        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16225        // Disable the child packages
16226        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16227        for (int i = 0; i < childCount; i++) {
16228            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16229            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16230            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16231        }
16232        return disabled;
16233    }
16234
16235    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16236            String installerPackageName) {
16237        // Enable the parent package
16238        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16239        // Enable the child packages
16240        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16241        for (int i = 0; i < childCount; i++) {
16242            PackageParser.Package childPkg = pkg.childPackages.get(i);
16243            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16244        }
16245    }
16246
16247    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
16248        // Collect all used permissions in the UID
16249        ArraySet<String> usedPermissions = new ArraySet<>();
16250        final int packageCount = su.packages.size();
16251        for (int i = 0; i < packageCount; i++) {
16252            PackageSetting ps = su.packages.valueAt(i);
16253            if (ps.pkg == null) {
16254                continue;
16255            }
16256            final int requestedPermCount = ps.pkg.requestedPermissions.size();
16257            for (int j = 0; j < requestedPermCount; j++) {
16258                String permission = ps.pkg.requestedPermissions.get(j);
16259                BasePermission bp = mSettings.mPermissions.get(permission);
16260                if (bp != null) {
16261                    usedPermissions.add(permission);
16262                }
16263            }
16264        }
16265
16266        PermissionsState permissionsState = su.getPermissionsState();
16267        // Prune install permissions
16268        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
16269        final int installPermCount = installPermStates.size();
16270        for (int i = installPermCount - 1; i >= 0;  i--) {
16271            PermissionState permissionState = installPermStates.get(i);
16272            if (!usedPermissions.contains(permissionState.getName())) {
16273                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16274                if (bp != null) {
16275                    permissionsState.revokeInstallPermission(bp);
16276                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
16277                            PackageManager.MASK_PERMISSION_FLAGS, 0);
16278                }
16279            }
16280        }
16281
16282        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
16283
16284        // Prune runtime permissions
16285        for (int userId : allUserIds) {
16286            List<PermissionState> runtimePermStates = permissionsState
16287                    .getRuntimePermissionStates(userId);
16288            final int runtimePermCount = runtimePermStates.size();
16289            for (int i = runtimePermCount - 1; i >= 0; i--) {
16290                PermissionState permissionState = runtimePermStates.get(i);
16291                if (!usedPermissions.contains(permissionState.getName())) {
16292                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
16293                    if (bp != null) {
16294                        permissionsState.revokeRuntimePermission(bp, userId);
16295                        permissionsState.updatePermissionFlags(bp, userId,
16296                                PackageManager.MASK_PERMISSION_FLAGS, 0);
16297                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
16298                                runtimePermissionChangedUserIds, userId);
16299                    }
16300                }
16301            }
16302        }
16303
16304        return runtimePermissionChangedUserIds;
16305    }
16306
16307    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16308            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16309        // Update the parent package setting
16310        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16311                res, user, installReason);
16312        // Update the child packages setting
16313        final int childCount = (newPackage.childPackages != null)
16314                ? newPackage.childPackages.size() : 0;
16315        for (int i = 0; i < childCount; i++) {
16316            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16317            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16318            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16319                    childRes.origUsers, childRes, user, installReason);
16320        }
16321    }
16322
16323    private void updateSettingsInternalLI(PackageParser.Package newPackage,
16324            String installerPackageName, int[] allUsers, int[] installedForUsers,
16325            PackageInstalledInfo res, UserHandle user, int installReason) {
16326        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16327
16328        String pkgName = newPackage.packageName;
16329        synchronized (mPackages) {
16330            //write settings. the installStatus will be incomplete at this stage.
16331            //note that the new package setting would have already been
16332            //added to mPackages. It hasn't been persisted yet.
16333            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
16334            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16335            mSettings.writeLPr();
16336            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16337        }
16338
16339        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
16340        synchronized (mPackages) {
16341            updatePermissionsLPw(newPackage.packageName, newPackage,
16342                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
16343                            ? UPDATE_PERMISSIONS_ALL : 0));
16344            // For system-bundled packages, we assume that installing an upgraded version
16345            // of the package implies that the user actually wants to run that new code,
16346            // so we enable the package.
16347            PackageSetting ps = mSettings.mPackages.get(pkgName);
16348            final int userId = user.getIdentifier();
16349            if (ps != null) {
16350                if (isSystemApp(newPackage)) {
16351                    if (DEBUG_INSTALL) {
16352                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16353                    }
16354                    // Enable system package for requested users
16355                    if (res.origUsers != null) {
16356                        for (int origUserId : res.origUsers) {
16357                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16358                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16359                                        origUserId, installerPackageName);
16360                            }
16361                        }
16362                    }
16363                    // Also convey the prior install/uninstall state
16364                    if (allUsers != null && installedForUsers != null) {
16365                        for (int currentUserId : allUsers) {
16366                            final boolean installed = ArrayUtils.contains(
16367                                    installedForUsers, currentUserId);
16368                            if (DEBUG_INSTALL) {
16369                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16370                            }
16371                            ps.setInstalled(installed, currentUserId);
16372                        }
16373                        // these install state changes will be persisted in the
16374                        // upcoming call to mSettings.writeLPr().
16375                    }
16376                }
16377                // It's implied that when a user requests installation, they want the app to be
16378                // installed and enabled.
16379                if (userId != UserHandle.USER_ALL) {
16380                    ps.setInstalled(true, userId);
16381                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16382                }
16383
16384                // When replacing an existing package, preserve the original install reason for all
16385                // users that had the package installed before.
16386                final Set<Integer> previousUserIds = new ArraySet<>();
16387                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16388                    final int installReasonCount = res.removedInfo.installReasons.size();
16389                    for (int i = 0; i < installReasonCount; i++) {
16390                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16391                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16392                        ps.setInstallReason(previousInstallReason, previousUserId);
16393                        previousUserIds.add(previousUserId);
16394                    }
16395                }
16396
16397                // Set install reason for users that are having the package newly installed.
16398                if (userId == UserHandle.USER_ALL) {
16399                    for (int currentUserId : sUserManager.getUserIds()) {
16400                        if (!previousUserIds.contains(currentUserId)) {
16401                            ps.setInstallReason(installReason, currentUserId);
16402                        }
16403                    }
16404                } else if (!previousUserIds.contains(userId)) {
16405                    ps.setInstallReason(installReason, userId);
16406                }
16407            }
16408            res.name = pkgName;
16409            res.uid = newPackage.applicationInfo.uid;
16410            res.pkg = newPackage;
16411            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
16412            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16413            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16414            //to update install status
16415            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16416            mSettings.writeLPr();
16417            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16418        }
16419
16420        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16421    }
16422
16423    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16424        try {
16425            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16426            installPackageLI(args, res);
16427        } finally {
16428            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16429        }
16430    }
16431
16432    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16433        final int installFlags = args.installFlags;
16434        final String installerPackageName = args.installerPackageName;
16435        final String volumeUuid = args.volumeUuid;
16436        final File tmpPackageFile = new File(args.getCodePath());
16437        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16438        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16439                || (args.volumeUuid != null));
16440        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
16441        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16442        boolean replace = false;
16443        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16444        if (args.move != null) {
16445            // moving a complete application; perform an initial scan on the new install location
16446            scanFlags |= SCAN_INITIAL;
16447        }
16448        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16449            scanFlags |= SCAN_DONT_KILL_APP;
16450        }
16451
16452        // Result object to be returned
16453        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16454
16455        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16456
16457        // Sanity check
16458        if (ephemeral && (forwardLocked || onExternal)) {
16459            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16460                    + " external=" + onExternal);
16461            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
16462            return;
16463        }
16464
16465        // Retrieve PackageSettings and parse package
16466        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16467                | PackageParser.PARSE_ENFORCE_CODE
16468                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16469                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16470                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
16471                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16472        PackageParser pp = new PackageParser();
16473        pp.setSeparateProcesses(mSeparateProcesses);
16474        pp.setDisplayMetrics(mMetrics);
16475
16476        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16477        final PackageParser.Package pkg;
16478        try {
16479            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16480        } catch (PackageParserException e) {
16481            res.setError("Failed parse during installPackageLI", e);
16482            return;
16483        } finally {
16484            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16485        }
16486
16487        // Ephemeral apps must have target SDK >= O.
16488        // TODO: Update conditional and error message when O gets locked down
16489        if (ephemeral && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
16490            res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID,
16491                    "Ephemeral apps must have target SDK version of at least O");
16492            return;
16493        }
16494
16495        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16496            // Static shared libraries have synthetic package names
16497            renameStaticSharedLibraryPackage(pkg);
16498
16499            // No static shared libs on external storage
16500            if (onExternal) {
16501                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16502                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16503                        "Packages declaring static-shared libs cannot be updated");
16504                return;
16505            }
16506        }
16507
16508        // If we are installing a clustered package add results for the children
16509        if (pkg.childPackages != null) {
16510            synchronized (mPackages) {
16511                final int childCount = pkg.childPackages.size();
16512                for (int i = 0; i < childCount; i++) {
16513                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16514                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16515                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16516                    childRes.pkg = childPkg;
16517                    childRes.name = childPkg.packageName;
16518                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16519                    if (childPs != null) {
16520                        childRes.origUsers = childPs.queryInstalledUsers(
16521                                sUserManager.getUserIds(), true);
16522                    }
16523                    if ((mPackages.containsKey(childPkg.packageName))) {
16524                        childRes.removedInfo = new PackageRemovedInfo();
16525                        childRes.removedInfo.removedPackage = childPkg.packageName;
16526                    }
16527                    if (res.addedChildPackages == null) {
16528                        res.addedChildPackages = new ArrayMap<>();
16529                    }
16530                    res.addedChildPackages.put(childPkg.packageName, childRes);
16531                }
16532            }
16533        }
16534
16535        // If package doesn't declare API override, mark that we have an install
16536        // time CPU ABI override.
16537        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16538            pkg.cpuAbiOverride = args.abiOverride;
16539        }
16540
16541        String pkgName = res.name = pkg.packageName;
16542        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16543            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16544                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16545                return;
16546            }
16547        }
16548
16549        try {
16550            // either use what we've been given or parse directly from the APK
16551            if (args.certificates != null) {
16552                try {
16553                    PackageParser.populateCertificates(pkg, args.certificates);
16554                } catch (PackageParserException e) {
16555                    // there was something wrong with the certificates we were given;
16556                    // try to pull them from the APK
16557                    PackageParser.collectCertificates(pkg, parseFlags);
16558                }
16559            } else {
16560                PackageParser.collectCertificates(pkg, parseFlags);
16561            }
16562        } catch (PackageParserException e) {
16563            res.setError("Failed collect during installPackageLI", e);
16564            return;
16565        }
16566
16567        // Get rid of all references to package scan path via parser.
16568        pp = null;
16569        String oldCodePath = null;
16570        boolean systemApp = false;
16571        synchronized (mPackages) {
16572            // Check if installing already existing package
16573            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16574                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16575                if (pkg.mOriginalPackages != null
16576                        && pkg.mOriginalPackages.contains(oldName)
16577                        && mPackages.containsKey(oldName)) {
16578                    // This package is derived from an original package,
16579                    // and this device has been updating from that original
16580                    // name.  We must continue using the original name, so
16581                    // rename the new package here.
16582                    pkg.setPackageName(oldName);
16583                    pkgName = pkg.packageName;
16584                    replace = true;
16585                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16586                            + oldName + " pkgName=" + pkgName);
16587                } else if (mPackages.containsKey(pkgName)) {
16588                    // This package, under its official name, already exists
16589                    // on the device; we should replace it.
16590                    replace = true;
16591                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16592                }
16593
16594                // Child packages are installed through the parent package
16595                if (pkg.parentPackage != null) {
16596                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16597                            "Package " + pkg.packageName + " is child of package "
16598                                    + pkg.parentPackage.parentPackage + ". Child packages "
16599                                    + "can be updated only through the parent package.");
16600                    return;
16601                }
16602
16603                if (replace) {
16604                    // Prevent apps opting out from runtime permissions
16605                    PackageParser.Package oldPackage = mPackages.get(pkgName);
16606                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
16607                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
16608                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
16609                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
16610                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
16611                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
16612                                        + " doesn't support runtime permissions but the old"
16613                                        + " target SDK " + oldTargetSdk + " does.");
16614                        return;
16615                    }
16616
16617                    // Prevent installing of child packages
16618                    if (oldPackage.parentPackage != null) {
16619                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16620                                "Package " + pkg.packageName + " is child of package "
16621                                        + oldPackage.parentPackage + ". Child packages "
16622                                        + "can be updated only through the parent package.");
16623                        return;
16624                    }
16625                }
16626            }
16627
16628            PackageSetting ps = mSettings.mPackages.get(pkgName);
16629            if (ps != null) {
16630                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
16631
16632                // Static shared libs have same package with different versions where
16633                // we internally use a synthetic package name to allow multiple versions
16634                // of the same package, therefore we need to compare signatures against
16635                // the package setting for the latest library version.
16636                PackageSetting signatureCheckPs = ps;
16637                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16638                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
16639                    if (libraryEntry != null) {
16640                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
16641                    }
16642                }
16643
16644                // Quick sanity check that we're signed correctly if updating;
16645                // we'll check this again later when scanning, but we want to
16646                // bail early here before tripping over redefined permissions.
16647                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
16648                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
16649                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
16650                                + pkg.packageName + " upgrade keys do not match the "
16651                                + "previously installed version");
16652                        return;
16653                    }
16654                } else {
16655                    try {
16656                        verifySignaturesLP(signatureCheckPs, pkg);
16657                    } catch (PackageManagerException e) {
16658                        res.setError(e.error, e.getMessage());
16659                        return;
16660                    }
16661                }
16662
16663                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
16664                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
16665                    systemApp = (ps.pkg.applicationInfo.flags &
16666                            ApplicationInfo.FLAG_SYSTEM) != 0;
16667                }
16668                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16669            }
16670
16671            // Check whether the newly-scanned package wants to define an already-defined perm
16672            int N = pkg.permissions.size();
16673            for (int i = N-1; i >= 0; i--) {
16674                PackageParser.Permission perm = pkg.permissions.get(i);
16675                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
16676                if (bp != null) {
16677                    // If the defining package is signed with our cert, it's okay.  This
16678                    // also includes the "updating the same package" case, of course.
16679                    // "updating same package" could also involve key-rotation.
16680                    final boolean sigsOk;
16681                    if (bp.sourcePackage.equals(pkg.packageName)
16682                            && (bp.packageSetting instanceof PackageSetting)
16683                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
16684                                    scanFlags))) {
16685                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
16686                    } else {
16687                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
16688                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
16689                    }
16690                    if (!sigsOk) {
16691                        // If the owning package is the system itself, we log but allow
16692                        // install to proceed; we fail the install on all other permission
16693                        // redefinitions.
16694                        if (!bp.sourcePackage.equals("android")) {
16695                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
16696                                    + pkg.packageName + " attempting to redeclare permission "
16697                                    + perm.info.name + " already owned by " + bp.sourcePackage);
16698                            res.origPermission = perm.info.name;
16699                            res.origPackage = bp.sourcePackage;
16700                            return;
16701                        } else {
16702                            Slog.w(TAG, "Package " + pkg.packageName
16703                                    + " attempting to redeclare system permission "
16704                                    + perm.info.name + "; ignoring new declaration");
16705                            pkg.permissions.remove(i);
16706                        }
16707                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
16708                        // Prevent apps to change protection level to dangerous from any other
16709                        // type as this would allow a privilege escalation where an app adds a
16710                        // normal/signature permission in other app's group and later redefines
16711                        // it as dangerous leading to the group auto-grant.
16712                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
16713                                == PermissionInfo.PROTECTION_DANGEROUS) {
16714                            if (bp != null && !bp.isRuntime()) {
16715                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
16716                                        + "non-runtime permission " + perm.info.name
16717                                        + " to runtime; keeping old protection level");
16718                                perm.info.protectionLevel = bp.protectionLevel;
16719                            }
16720                        }
16721                    }
16722                }
16723            }
16724        }
16725
16726        if (systemApp) {
16727            if (onExternal) {
16728                // Abort update; system app can't be replaced with app on sdcard
16729                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16730                        "Cannot install updates to system apps on sdcard");
16731                return;
16732            } else if (ephemeral) {
16733                // Abort update; system app can't be replaced with an ephemeral app
16734                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
16735                        "Cannot update a system app with an ephemeral app");
16736                return;
16737            }
16738        }
16739
16740        if (args.move != null) {
16741            // We did an in-place move, so dex is ready to roll
16742            scanFlags |= SCAN_NO_DEX;
16743            scanFlags |= SCAN_MOVE;
16744
16745            synchronized (mPackages) {
16746                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16747                if (ps == null) {
16748                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
16749                            "Missing settings for moved package " + pkgName);
16750                }
16751
16752                // We moved the entire application as-is, so bring over the
16753                // previously derived ABI information.
16754                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
16755                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
16756            }
16757
16758        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
16759            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
16760            scanFlags |= SCAN_NO_DEX;
16761
16762            try {
16763                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
16764                    args.abiOverride : pkg.cpuAbiOverride);
16765                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
16766                        true /*extractLibs*/, mAppLib32InstallDir);
16767            } catch (PackageManagerException pme) {
16768                Slog.e(TAG, "Error deriving application ABI", pme);
16769                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
16770                return;
16771            }
16772
16773            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
16774            // Do not run PackageDexOptimizer through the local performDexOpt
16775            // method because `pkg` may not be in `mPackages` yet.
16776            //
16777            // Also, don't fail application installs if the dexopt step fails.
16778            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
16779                    null /* instructionSets */, false /* checkProfiles */,
16780                    getCompilerFilterForReason(REASON_INSTALL),
16781                    getOrCreateCompilerPackageStats(pkg));
16782            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16783
16784            // Notify BackgroundDexOptJobService that the package has been changed.
16785            // If this is an update of a package which used to fail to compile,
16786            // BDOS will remove it from its blacklist.
16787            // TODO: Layering violation
16788            BackgroundDexOptJobService.notifyPackageChanged(pkg.packageName);
16789        }
16790
16791        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
16792            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
16793            return;
16794        }
16795
16796        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
16797
16798        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
16799                "installPackageLI")) {
16800            if (replace) {
16801                if (pkg.applicationInfo.isStaticSharedLibrary()) {
16802                    // Static libs have a synthetic package name containing the version
16803                    // and cannot be updated as an update would get a new package name,
16804                    // unless this is the exact same version code which is useful for
16805                    // development.
16806                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
16807                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
16808                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
16809                                + "static-shared libs cannot be updated");
16810                        return;
16811                    }
16812                }
16813                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
16814                        installerPackageName, res, args.installReason);
16815            } else {
16816                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
16817                        args.user, installerPackageName, volumeUuid, res, args.installReason);
16818            }
16819        }
16820        synchronized (mPackages) {
16821            final PackageSetting ps = mSettings.mPackages.get(pkgName);
16822            if (ps != null) {
16823                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16824            }
16825
16826            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16827            for (int i = 0; i < childCount; i++) {
16828                PackageParser.Package childPkg = pkg.childPackages.get(i);
16829                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16830                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16831                if (childPs != null) {
16832                    childRes.newUsers = childPs.queryInstalledUsers(
16833                            sUserManager.getUserIds(), true);
16834                }
16835            }
16836        }
16837    }
16838
16839    private void startIntentFilterVerifications(int userId, boolean replacing,
16840            PackageParser.Package pkg) {
16841        if (mIntentFilterVerifierComponent == null) {
16842            Slog.w(TAG, "No IntentFilter verification will not be done as "
16843                    + "there is no IntentFilterVerifier available!");
16844            return;
16845        }
16846
16847        final int verifierUid = getPackageUid(
16848                mIntentFilterVerifierComponent.getPackageName(),
16849                MATCH_DEBUG_TRIAGED_MISSING,
16850                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
16851
16852        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16853        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
16854        mHandler.sendMessage(msg);
16855
16856        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16857        for (int i = 0; i < childCount; i++) {
16858            PackageParser.Package childPkg = pkg.childPackages.get(i);
16859            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
16860            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
16861            mHandler.sendMessage(msg);
16862        }
16863    }
16864
16865    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
16866            PackageParser.Package pkg) {
16867        int size = pkg.activities.size();
16868        if (size == 0) {
16869            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16870                    "No activity, so no need to verify any IntentFilter!");
16871            return;
16872        }
16873
16874        final boolean hasDomainURLs = hasDomainURLs(pkg);
16875        if (!hasDomainURLs) {
16876            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16877                    "No domain URLs, so no need to verify any IntentFilter!");
16878            return;
16879        }
16880
16881        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
16882                + " if any IntentFilter from the " + size
16883                + " Activities needs verification ...");
16884
16885        int count = 0;
16886        final String packageName = pkg.packageName;
16887
16888        synchronized (mPackages) {
16889            // If this is a new install and we see that we've already run verification for this
16890            // package, we have nothing to do: it means the state was restored from backup.
16891            if (!replacing) {
16892                IntentFilterVerificationInfo ivi =
16893                        mSettings.getIntentFilterVerificationLPr(packageName);
16894                if (ivi != null) {
16895                    if (DEBUG_DOMAIN_VERIFICATION) {
16896                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
16897                                + ivi.getStatusString());
16898                    }
16899                    return;
16900                }
16901            }
16902
16903            // If any filters need to be verified, then all need to be.
16904            boolean needToVerify = false;
16905            for (PackageParser.Activity a : pkg.activities) {
16906                for (ActivityIntentInfo filter : a.intents) {
16907                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
16908                        if (DEBUG_DOMAIN_VERIFICATION) {
16909                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
16910                        }
16911                        needToVerify = true;
16912                        break;
16913                    }
16914                }
16915            }
16916
16917            if (needToVerify) {
16918                final int verificationId = mIntentFilterVerificationToken++;
16919                for (PackageParser.Activity a : pkg.activities) {
16920                    for (ActivityIntentInfo filter : a.intents) {
16921                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
16922                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
16923                                    "Verification needed for IntentFilter:" + filter.toString());
16924                            mIntentFilterVerifier.addOneIntentFilterVerification(
16925                                    verifierUid, userId, verificationId, filter, packageName);
16926                            count++;
16927                        }
16928                    }
16929                }
16930            }
16931        }
16932
16933        if (count > 0) {
16934            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
16935                    + " IntentFilter verification" + (count > 1 ? "s" : "")
16936                    +  " for userId:" + userId);
16937            mIntentFilterVerifier.startVerifications(userId);
16938        } else {
16939            if (DEBUG_DOMAIN_VERIFICATION) {
16940                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
16941            }
16942        }
16943    }
16944
16945    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
16946        final ComponentName cn  = filter.activity.getComponentName();
16947        final String packageName = cn.getPackageName();
16948
16949        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
16950                packageName);
16951        if (ivi == null) {
16952            return true;
16953        }
16954        int status = ivi.getStatus();
16955        switch (status) {
16956            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
16957            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
16958                return true;
16959
16960            default:
16961                // Nothing to do
16962                return false;
16963        }
16964    }
16965
16966    private static boolean isMultiArch(ApplicationInfo info) {
16967        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
16968    }
16969
16970    private static boolean isExternal(PackageParser.Package pkg) {
16971        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16972    }
16973
16974    private static boolean isExternal(PackageSetting ps) {
16975        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
16976    }
16977
16978    private static boolean isEphemeral(PackageParser.Package pkg) {
16979        return pkg.applicationInfo.isInstantApp();
16980    }
16981
16982    private static boolean isEphemeral(PackageSetting ps) {
16983        return ps.pkg != null && isEphemeral(ps.pkg);
16984    }
16985
16986    private static boolean isSystemApp(PackageParser.Package pkg) {
16987        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
16988    }
16989
16990    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
16991        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16992    }
16993
16994    private static boolean hasDomainURLs(PackageParser.Package pkg) {
16995        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
16996    }
16997
16998    private static boolean isSystemApp(PackageSetting ps) {
16999        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17000    }
17001
17002    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17003        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17004    }
17005
17006    private int packageFlagsToInstallFlags(PackageSetting ps) {
17007        int installFlags = 0;
17008        if (isEphemeral(ps)) {
17009            installFlags |= PackageManager.INSTALL_EPHEMERAL;
17010        }
17011        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17012            // This existing package was an external ASEC install when we have
17013            // the external flag without a UUID
17014            installFlags |= PackageManager.INSTALL_EXTERNAL;
17015        }
17016        if (ps.isForwardLocked()) {
17017            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17018        }
17019        return installFlags;
17020    }
17021
17022    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
17023        if (isExternal(pkg)) {
17024            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17025                return StorageManager.UUID_PRIMARY_PHYSICAL;
17026            } else {
17027                return pkg.volumeUuid;
17028            }
17029        } else {
17030            return StorageManager.UUID_PRIVATE_INTERNAL;
17031        }
17032    }
17033
17034    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17035        if (isExternal(pkg)) {
17036            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17037                return mSettings.getExternalVersion();
17038            } else {
17039                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17040            }
17041        } else {
17042            return mSettings.getInternalVersion();
17043        }
17044    }
17045
17046    private void deleteTempPackageFiles() {
17047        final FilenameFilter filter = new FilenameFilter() {
17048            public boolean accept(File dir, String name) {
17049                return name.startsWith("vmdl") && name.endsWith(".tmp");
17050            }
17051        };
17052        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
17053            file.delete();
17054        }
17055    }
17056
17057    @Override
17058    public void deletePackageAsUser(String packageName, int versionCode,
17059            IPackageDeleteObserver observer, int userId, int flags) {
17060        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17061                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17062    }
17063
17064    @Override
17065    public void deletePackageVersioned(VersionedPackage versionedPackage,
17066            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17067        mContext.enforceCallingOrSelfPermission(
17068                android.Manifest.permission.DELETE_PACKAGES, null);
17069        Preconditions.checkNotNull(versionedPackage);
17070        Preconditions.checkNotNull(observer);
17071        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
17072                PackageManager.VERSION_CODE_HIGHEST,
17073                Integer.MAX_VALUE, "versionCode must be >= -1");
17074
17075        final String packageName = versionedPackage.getPackageName();
17076        // TODO: We will change version code to long, so in the new API it is long
17077        final int versionCode = (int) versionedPackage.getVersionCode();
17078        final String internalPackageName;
17079        synchronized (mPackages) {
17080            // Normalize package name to handle renamed packages and static libs
17081            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
17082                    // TODO: We will change version code to long, so in the new API it is long
17083                    (int) versionedPackage.getVersionCode());
17084        }
17085
17086        final int uid = Binder.getCallingUid();
17087        if (!isOrphaned(internalPackageName)
17088                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17089            try {
17090                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17091                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17092                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17093                observer.onUserActionRequired(intent);
17094            } catch (RemoteException re) {
17095            }
17096            return;
17097        }
17098        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17099        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17100        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17101            mContext.enforceCallingOrSelfPermission(
17102                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17103                    "deletePackage for user " + userId);
17104        }
17105
17106        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17107            try {
17108                observer.onPackageDeleted(packageName,
17109                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17110            } catch (RemoteException re) {
17111            }
17112            return;
17113        }
17114
17115        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17116            try {
17117                observer.onPackageDeleted(packageName,
17118                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17119            } catch (RemoteException re) {
17120            }
17121            return;
17122        }
17123
17124        if (DEBUG_REMOVE) {
17125            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17126                    + " deleteAllUsers: " + deleteAllUsers + " version="
17127                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17128                    ? "VERSION_CODE_HIGHEST" : versionCode));
17129        }
17130        // Queue up an async operation since the package deletion may take a little while.
17131        mHandler.post(new Runnable() {
17132            public void run() {
17133                mHandler.removeCallbacks(this);
17134                int returnCode;
17135                if (!deleteAllUsers) {
17136                    returnCode = deletePackageX(internalPackageName, versionCode,
17137                            userId, deleteFlags);
17138                } else {
17139                    int[] blockUninstallUserIds = getBlockUninstallForUsers(
17140                            internalPackageName, users);
17141                    // If nobody is blocking uninstall, proceed with delete for all users
17142                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17143                        returnCode = deletePackageX(internalPackageName, versionCode,
17144                                userId, deleteFlags);
17145                    } else {
17146                        // Otherwise uninstall individually for users with blockUninstalls=false
17147                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17148                        for (int userId : users) {
17149                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17150                                returnCode = deletePackageX(internalPackageName, versionCode,
17151                                        userId, userFlags);
17152                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17153                                    Slog.w(TAG, "Package delete failed for user " + userId
17154                                            + ", returnCode " + returnCode);
17155                                }
17156                            }
17157                        }
17158                        // The app has only been marked uninstalled for certain users.
17159                        // We still need to report that delete was blocked
17160                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17161                    }
17162                }
17163                try {
17164                    observer.onPackageDeleted(packageName, returnCode, null);
17165                } catch (RemoteException e) {
17166                    Log.i(TAG, "Observer no longer exists.");
17167                } //end catch
17168            } //end run
17169        });
17170    }
17171
17172    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17173        if (pkg.staticSharedLibName != null) {
17174            return pkg.manifestPackageName;
17175        }
17176        return pkg.packageName;
17177    }
17178
17179    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
17180        // Handle renamed packages
17181        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17182        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17183
17184        // Is this a static library?
17185        SparseArray<SharedLibraryEntry> versionedLib =
17186                mStaticLibsByDeclaringPackage.get(packageName);
17187        if (versionedLib == null || versionedLib.size() <= 0) {
17188            return packageName;
17189        }
17190
17191        // Figure out which lib versions the caller can see
17192        SparseIntArray versionsCallerCanSee = null;
17193        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17194        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17195                && callingAppId != Process.ROOT_UID) {
17196            versionsCallerCanSee = new SparseIntArray();
17197            String libName = versionedLib.valueAt(0).info.getName();
17198            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17199            if (uidPackages != null) {
17200                for (String uidPackage : uidPackages) {
17201                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17202                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17203                    if (libIdx >= 0) {
17204                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
17205                        versionsCallerCanSee.append(libVersion, libVersion);
17206                    }
17207                }
17208            }
17209        }
17210
17211        // Caller can see nothing - done
17212        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17213            return packageName;
17214        }
17215
17216        // Find the version the caller can see and the app version code
17217        SharedLibraryEntry highestVersion = null;
17218        final int versionCount = versionedLib.size();
17219        for (int i = 0; i < versionCount; i++) {
17220            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17221            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17222                    libEntry.info.getVersion()) < 0) {
17223                continue;
17224            }
17225            // TODO: We will change version code to long, so in the new API it is long
17226            final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode();
17227            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17228                if (libVersionCode == versionCode) {
17229                    return libEntry.apk;
17230                }
17231            } else if (highestVersion == null) {
17232                highestVersion = libEntry;
17233            } else if (libVersionCode  > highestVersion.info
17234                    .getDeclaringPackage().getVersionCode()) {
17235                highestVersion = libEntry;
17236            }
17237        }
17238
17239        if (highestVersion != null) {
17240            return highestVersion.apk;
17241        }
17242
17243        return packageName;
17244    }
17245
17246    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17247        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17248              || callingUid == Process.SYSTEM_UID) {
17249            return true;
17250        }
17251        final int callingUserId = UserHandle.getUserId(callingUid);
17252        // If the caller installed the pkgName, then allow it to silently uninstall.
17253        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17254            return true;
17255        }
17256
17257        // Allow package verifier to silently uninstall.
17258        if (mRequiredVerifierPackage != null &&
17259                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17260            return true;
17261        }
17262
17263        // Allow package uninstaller to silently uninstall.
17264        if (mRequiredUninstallerPackage != null &&
17265                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17266            return true;
17267        }
17268
17269        // Allow storage manager to silently uninstall.
17270        if (mStorageManagerPackage != null &&
17271                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17272            return true;
17273        }
17274        return false;
17275    }
17276
17277    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17278        int[] result = EMPTY_INT_ARRAY;
17279        for (int userId : userIds) {
17280            if (getBlockUninstallForUser(packageName, userId)) {
17281                result = ArrayUtils.appendInt(result, userId);
17282            }
17283        }
17284        return result;
17285    }
17286
17287    @Override
17288    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17289        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17290    }
17291
17292    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17293        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17294                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17295        try {
17296            if (dpm != null) {
17297                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17298                        /* callingUserOnly =*/ false);
17299                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17300                        : deviceOwnerComponentName.getPackageName();
17301                // Does the package contains the device owner?
17302                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17303                // this check is probably not needed, since DO should be registered as a device
17304                // admin on some user too. (Original bug for this: b/17657954)
17305                if (packageName.equals(deviceOwnerPackageName)) {
17306                    return true;
17307                }
17308                // Does it contain a device admin for any user?
17309                int[] users;
17310                if (userId == UserHandle.USER_ALL) {
17311                    users = sUserManager.getUserIds();
17312                } else {
17313                    users = new int[]{userId};
17314                }
17315                for (int i = 0; i < users.length; ++i) {
17316                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17317                        return true;
17318                    }
17319                }
17320            }
17321        } catch (RemoteException e) {
17322        }
17323        return false;
17324    }
17325
17326    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17327        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17328    }
17329
17330    /**
17331     *  This method is an internal method that could be get invoked either
17332     *  to delete an installed package or to clean up a failed installation.
17333     *  After deleting an installed package, a broadcast is sent to notify any
17334     *  listeners that the package has been removed. For cleaning up a failed
17335     *  installation, the broadcast is not necessary since the package's
17336     *  installation wouldn't have sent the initial broadcast either
17337     *  The key steps in deleting a package are
17338     *  deleting the package information in internal structures like mPackages,
17339     *  deleting the packages base directories through installd
17340     *  updating mSettings to reflect current status
17341     *  persisting settings for later use
17342     *  sending a broadcast if necessary
17343     */
17344    private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
17345        final PackageRemovedInfo info = new PackageRemovedInfo();
17346        final boolean res;
17347
17348        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17349                ? UserHandle.USER_ALL : userId;
17350
17351        if (isPackageDeviceAdmin(packageName, removeUser)) {
17352            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17353            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17354        }
17355
17356        PackageSetting uninstalledPs = null;
17357
17358        // for the uninstall-updates case and restricted profiles, remember the per-
17359        // user handle installed state
17360        int[] allUsers;
17361        synchronized (mPackages) {
17362            uninstalledPs = mSettings.mPackages.get(packageName);
17363            if (uninstalledPs == null) {
17364                Slog.w(TAG, "Not removing non-existent package " + packageName);
17365                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17366            }
17367
17368            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17369                    && uninstalledPs.versionCode != versionCode) {
17370                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17371                        + uninstalledPs.versionCode + " != " + versionCode);
17372                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17373            }
17374
17375            // Static shared libs can be declared by any package, so let us not
17376            // allow removing a package if it provides a lib others depend on.
17377            PackageParser.Package pkg = mPackages.get(packageName);
17378            if (pkg != null && pkg.staticSharedLibName != null) {
17379                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17380                        pkg.staticSharedLibVersion);
17381                if (libEntry != null) {
17382                    List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17383                            libEntry.info, 0, userId);
17384                    if (!ArrayUtils.isEmpty(libClientPackages)) {
17385                        Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17386                                + " hosting lib " + libEntry.info.getName() + " version "
17387                                + libEntry.info.getVersion()  + " used by " + libClientPackages);
17388                        return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17389                    }
17390                }
17391            }
17392
17393            allUsers = sUserManager.getUserIds();
17394            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17395        }
17396
17397        final int freezeUser;
17398        if (isUpdatedSystemApp(uninstalledPs)
17399                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17400            // We're downgrading a system app, which will apply to all users, so
17401            // freeze them all during the downgrade
17402            freezeUser = UserHandle.USER_ALL;
17403        } else {
17404            freezeUser = removeUser;
17405        }
17406
17407        synchronized (mInstallLock) {
17408            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17409            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17410                    deleteFlags, "deletePackageX")) {
17411                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17412                        deleteFlags | REMOVE_CHATTY, info, true, null);
17413            }
17414            synchronized (mPackages) {
17415                if (res) {
17416                    mInstantAppRegistry.onPackageUninstalledLPw(uninstalledPs.pkg,
17417                            info.removedUsers);
17418                }
17419            }
17420        }
17421
17422        if (res) {
17423            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
17424            info.sendPackageRemovedBroadcasts(killApp);
17425            info.sendSystemPackageUpdatedBroadcasts();
17426            info.sendSystemPackageAppearedBroadcasts();
17427        }
17428        // Force a gc here.
17429        Runtime.getRuntime().gc();
17430        // Delete the resources here after sending the broadcast to let
17431        // other processes clean up before deleting resources.
17432        if (info.args != null) {
17433            synchronized (mInstallLock) {
17434                info.args.doPostDeleteLI(true);
17435            }
17436        }
17437
17438        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17439    }
17440
17441    class PackageRemovedInfo {
17442        String removedPackage;
17443        int uid = -1;
17444        int removedAppId = -1;
17445        int[] origUsers;
17446        int[] removedUsers = null;
17447        SparseArray<Integer> installReasons;
17448        boolean isRemovedPackageSystemUpdate = false;
17449        boolean isUpdate;
17450        boolean dataRemoved;
17451        boolean removedForAllUsers;
17452        boolean isStaticSharedLib;
17453        // Clean up resources deleted packages.
17454        InstallArgs args = null;
17455        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
17456        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
17457
17458        void sendPackageRemovedBroadcasts(boolean killApp) {
17459            sendPackageRemovedBroadcastInternal(killApp);
17460            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
17461            for (int i = 0; i < childCount; i++) {
17462                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17463                childInfo.sendPackageRemovedBroadcastInternal(killApp);
17464            }
17465        }
17466
17467        void sendSystemPackageUpdatedBroadcasts() {
17468            if (isRemovedPackageSystemUpdate) {
17469                sendSystemPackageUpdatedBroadcastsInternal();
17470                final int childCount = (removedChildPackages != null)
17471                        ? removedChildPackages.size() : 0;
17472                for (int i = 0; i < childCount; i++) {
17473                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
17474                    if (childInfo.isRemovedPackageSystemUpdate) {
17475                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
17476                    }
17477                }
17478            }
17479        }
17480
17481        void sendSystemPackageAppearedBroadcasts() {
17482            final int packageCount = (appearedChildPackages != null)
17483                    ? appearedChildPackages.size() : 0;
17484            for (int i = 0; i < packageCount; i++) {
17485                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
17486                sendPackageAddedForNewUsers(installedInfo.name, true,
17487                        UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers);
17488            }
17489        }
17490
17491        private void sendSystemPackageUpdatedBroadcastsInternal() {
17492            Bundle extras = new Bundle(2);
17493            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
17494            extras.putBoolean(Intent.EXTRA_REPLACING, true);
17495            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
17496                    extras, 0, null, null, null);
17497            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
17498                    extras, 0, null, null, null);
17499            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
17500                    null, 0, removedPackage, null, null);
17501        }
17502
17503        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
17504            // Don't send static shared library removal broadcasts as these
17505            // libs are visible only the the apps that depend on them an one
17506            // cannot remove the library if it has a dependency.
17507            if (isStaticSharedLib) {
17508                return;
17509            }
17510            Bundle extras = new Bundle(2);
17511            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
17512            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
17513            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
17514            if (isUpdate || isRemovedPackageSystemUpdate) {
17515                extras.putBoolean(Intent.EXTRA_REPLACING, true);
17516            }
17517            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
17518            if (removedPackage != null) {
17519                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
17520                        extras, 0, null, null, removedUsers);
17521                if (dataRemoved && !isRemovedPackageSystemUpdate) {
17522                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
17523                            removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
17524                            null, null, removedUsers);
17525                }
17526            }
17527            if (removedAppId >= 0) {
17528                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
17529                        removedUsers);
17530            }
17531        }
17532    }
17533
17534    /*
17535     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
17536     * flag is not set, the data directory is removed as well.
17537     * make sure this flag is set for partially installed apps. If not its meaningless to
17538     * delete a partially installed application.
17539     */
17540    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
17541            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
17542        String packageName = ps.name;
17543        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
17544        // Retrieve object to delete permissions for shared user later on
17545        final PackageParser.Package deletedPkg;
17546        final PackageSetting deletedPs;
17547        // reader
17548        synchronized (mPackages) {
17549            deletedPkg = mPackages.get(packageName);
17550            deletedPs = mSettings.mPackages.get(packageName);
17551            if (outInfo != null) {
17552                outInfo.removedPackage = packageName;
17553                outInfo.isStaticSharedLib = deletedPkg != null
17554                        && deletedPkg.staticSharedLibName != null;
17555                outInfo.removedUsers = deletedPs != null
17556                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
17557                        : null;
17558            }
17559        }
17560
17561        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
17562
17563        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
17564            final PackageParser.Package resolvedPkg;
17565            if (deletedPkg != null) {
17566                resolvedPkg = deletedPkg;
17567            } else {
17568                // We don't have a parsed package when it lives on an ejected
17569                // adopted storage device, so fake something together
17570                resolvedPkg = new PackageParser.Package(ps.name);
17571                resolvedPkg.setVolumeUuid(ps.volumeUuid);
17572            }
17573            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
17574                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
17575            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
17576            if (outInfo != null) {
17577                outInfo.dataRemoved = true;
17578            }
17579            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
17580        }
17581
17582        int removedAppId = -1;
17583
17584        // writer
17585        synchronized (mPackages) {
17586            if (deletedPs != null) {
17587                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
17588                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
17589                    clearDefaultBrowserIfNeeded(packageName);
17590                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
17591                    removedAppId = mSettings.removePackageLPw(packageName);
17592                    if (outInfo != null) {
17593                        outInfo.removedAppId = removedAppId;
17594                    }
17595                    updatePermissionsLPw(deletedPs.name, null, 0);
17596                    if (deletedPs.sharedUser != null) {
17597                        // Remove permissions associated with package. Since runtime
17598                        // permissions are per user we have to kill the removed package
17599                        // or packages running under the shared user of the removed
17600                        // package if revoking the permissions requested only by the removed
17601                        // package is successful and this causes a change in gids.
17602                        for (int userId : UserManagerService.getInstance().getUserIds()) {
17603                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
17604                                    userId);
17605                            if (userIdToKill == UserHandle.USER_ALL
17606                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
17607                                // If gids changed for this user, kill all affected packages.
17608                                mHandler.post(new Runnable() {
17609                                    @Override
17610                                    public void run() {
17611                                        // This has to happen with no lock held.
17612                                        killApplication(deletedPs.name, deletedPs.appId,
17613                                                KILL_APP_REASON_GIDS_CHANGED);
17614                                    }
17615                                });
17616                                break;
17617                            }
17618                        }
17619                    }
17620                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
17621                }
17622                // make sure to preserve per-user disabled state if this removal was just
17623                // a downgrade of a system app to the factory package
17624                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
17625                    if (DEBUG_REMOVE) {
17626                        Slog.d(TAG, "Propagating install state across downgrade");
17627                    }
17628                    for (int userId : allUserHandles) {
17629                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17630                        if (DEBUG_REMOVE) {
17631                            Slog.d(TAG, "    user " + userId + " => " + installed);
17632                        }
17633                        ps.setInstalled(installed, userId);
17634                    }
17635                }
17636            }
17637            // can downgrade to reader
17638            if (writeSettings) {
17639                // Save settings now
17640                mSettings.writeLPr();
17641            }
17642        }
17643        if (removedAppId != -1) {
17644            // A user ID was deleted here. Go through all users and remove it
17645            // from KeyStore.
17646            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
17647        }
17648    }
17649
17650    static boolean locationIsPrivileged(File path) {
17651        try {
17652            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
17653                    .getCanonicalPath();
17654            return path.getCanonicalPath().startsWith(privilegedAppDir);
17655        } catch (IOException e) {
17656            Slog.e(TAG, "Unable to access code path " + path);
17657        }
17658        return false;
17659    }
17660
17661    /*
17662     * Tries to delete system package.
17663     */
17664    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
17665            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
17666            boolean writeSettings) {
17667        if (deletedPs.parentPackageName != null) {
17668            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
17669            return false;
17670        }
17671
17672        final boolean applyUserRestrictions
17673                = (allUserHandles != null) && (outInfo.origUsers != null);
17674        final PackageSetting disabledPs;
17675        // Confirm if the system package has been updated
17676        // An updated system app can be deleted. This will also have to restore
17677        // the system pkg from system partition
17678        // reader
17679        synchronized (mPackages) {
17680            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
17681        }
17682
17683        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
17684                + " disabledPs=" + disabledPs);
17685
17686        if (disabledPs == null) {
17687            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
17688            return false;
17689        } else if (DEBUG_REMOVE) {
17690            Slog.d(TAG, "Deleting system pkg from data partition");
17691        }
17692
17693        if (DEBUG_REMOVE) {
17694            if (applyUserRestrictions) {
17695                Slog.d(TAG, "Remembering install states:");
17696                for (int userId : allUserHandles) {
17697                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
17698                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
17699                }
17700            }
17701        }
17702
17703        // Delete the updated package
17704        outInfo.isRemovedPackageSystemUpdate = true;
17705        if (outInfo.removedChildPackages != null) {
17706            final int childCount = (deletedPs.childPackageNames != null)
17707                    ? deletedPs.childPackageNames.size() : 0;
17708            for (int i = 0; i < childCount; i++) {
17709                String childPackageName = deletedPs.childPackageNames.get(i);
17710                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
17711                        .contains(childPackageName)) {
17712                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17713                            childPackageName);
17714                    if (childInfo != null) {
17715                        childInfo.isRemovedPackageSystemUpdate = true;
17716                    }
17717                }
17718            }
17719        }
17720
17721        if (disabledPs.versionCode < deletedPs.versionCode) {
17722            // Delete data for downgrades
17723            flags &= ~PackageManager.DELETE_KEEP_DATA;
17724        } else {
17725            // Preserve data by setting flag
17726            flags |= PackageManager.DELETE_KEEP_DATA;
17727        }
17728
17729        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
17730                outInfo, writeSettings, disabledPs.pkg);
17731        if (!ret) {
17732            return false;
17733        }
17734
17735        // writer
17736        synchronized (mPackages) {
17737            // Reinstate the old system package
17738            enableSystemPackageLPw(disabledPs.pkg);
17739            // Remove any native libraries from the upgraded package.
17740            removeNativeBinariesLI(deletedPs);
17741        }
17742
17743        // Install the system package
17744        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
17745        int parseFlags = mDefParseFlags
17746                | PackageParser.PARSE_MUST_BE_APK
17747                | PackageParser.PARSE_IS_SYSTEM
17748                | PackageParser.PARSE_IS_SYSTEM_DIR;
17749        if (locationIsPrivileged(disabledPs.codePath)) {
17750            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
17751        }
17752
17753        final PackageParser.Package newPkg;
17754        try {
17755            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
17756                0 /* currentTime */, null);
17757        } catch (PackageManagerException e) {
17758            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
17759                    + e.getMessage());
17760            return false;
17761        }
17762
17763        try {
17764            // update shared libraries for the newly re-installed system package
17765            updateSharedLibrariesLPr(newPkg, null);
17766        } catch (PackageManagerException e) {
17767            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17768        }
17769
17770        prepareAppDataAfterInstallLIF(newPkg);
17771
17772        // writer
17773        synchronized (mPackages) {
17774            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
17775
17776            // Propagate the permissions state as we do not want to drop on the floor
17777            // runtime permissions. The update permissions method below will take
17778            // care of removing obsolete permissions and grant install permissions.
17779            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
17780            updatePermissionsLPw(newPkg.packageName, newPkg,
17781                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
17782
17783            if (applyUserRestrictions) {
17784                if (DEBUG_REMOVE) {
17785                    Slog.d(TAG, "Propagating install state across reinstall");
17786                }
17787                for (int userId : allUserHandles) {
17788                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
17789                    if (DEBUG_REMOVE) {
17790                        Slog.d(TAG, "    user " + userId + " => " + installed);
17791                    }
17792                    ps.setInstalled(installed, userId);
17793
17794                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17795                }
17796                // Regardless of writeSettings we need to ensure that this restriction
17797                // state propagation is persisted
17798                mSettings.writeAllUsersPackageRestrictionsLPr();
17799            }
17800            // can downgrade to reader here
17801            if (writeSettings) {
17802                mSettings.writeLPr();
17803            }
17804        }
17805        return true;
17806    }
17807
17808    private boolean deleteInstalledPackageLIF(PackageSetting ps,
17809            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
17810            PackageRemovedInfo outInfo, boolean writeSettings,
17811            PackageParser.Package replacingPackage) {
17812        synchronized (mPackages) {
17813            if (outInfo != null) {
17814                outInfo.uid = ps.appId;
17815            }
17816
17817            if (outInfo != null && outInfo.removedChildPackages != null) {
17818                final int childCount = (ps.childPackageNames != null)
17819                        ? ps.childPackageNames.size() : 0;
17820                for (int i = 0; i < childCount; i++) {
17821                    String childPackageName = ps.childPackageNames.get(i);
17822                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
17823                    if (childPs == null) {
17824                        return false;
17825                    }
17826                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
17827                            childPackageName);
17828                    if (childInfo != null) {
17829                        childInfo.uid = childPs.appId;
17830                    }
17831                }
17832            }
17833        }
17834
17835        // Delete package data from internal structures and also remove data if flag is set
17836        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
17837
17838        // Delete the child packages data
17839        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17840        for (int i = 0; i < childCount; i++) {
17841            PackageSetting childPs;
17842            synchronized (mPackages) {
17843                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17844            }
17845            if (childPs != null) {
17846                PackageRemovedInfo childOutInfo = (outInfo != null
17847                        && outInfo.removedChildPackages != null)
17848                        ? outInfo.removedChildPackages.get(childPs.name) : null;
17849                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
17850                        && (replacingPackage != null
17851                        && !replacingPackage.hasChildPackage(childPs.name))
17852                        ? flags & ~DELETE_KEEP_DATA : flags;
17853                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
17854                        deleteFlags, writeSettings);
17855            }
17856        }
17857
17858        // Delete application code and resources only for parent packages
17859        if (ps.parentPackageName == null) {
17860            if (deleteCodeAndResources && (outInfo != null)) {
17861                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
17862                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
17863                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
17864            }
17865        }
17866
17867        return true;
17868    }
17869
17870    @Override
17871    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
17872            int userId) {
17873        mContext.enforceCallingOrSelfPermission(
17874                android.Manifest.permission.DELETE_PACKAGES, null);
17875        synchronized (mPackages) {
17876            PackageSetting ps = mSettings.mPackages.get(packageName);
17877            if (ps == null) {
17878                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
17879                return false;
17880            }
17881            // Cannot block uninstall of static shared libs as they are
17882            // considered a part of the using app (emulating static linking).
17883            // Also static libs are installed always on internal storage.
17884            PackageParser.Package pkg = mPackages.get(packageName);
17885            if (pkg != null && pkg.staticSharedLibName != null) {
17886                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
17887                        + " providing static shared library: " + pkg.staticSharedLibName);
17888                return false;
17889            }
17890            if (!ps.getInstalled(userId)) {
17891                // Can't block uninstall for an app that is not installed or enabled.
17892                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
17893                return false;
17894            }
17895            ps.setBlockUninstall(blockUninstall, userId);
17896            mSettings.writePackageRestrictionsLPr(userId);
17897        }
17898        return true;
17899    }
17900
17901    @Override
17902    public boolean getBlockUninstallForUser(String packageName, int userId) {
17903        synchronized (mPackages) {
17904            PackageSetting ps = mSettings.mPackages.get(packageName);
17905            if (ps == null) {
17906                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
17907                return false;
17908            }
17909            return ps.getBlockUninstall(userId);
17910        }
17911    }
17912
17913    @Override
17914    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
17915        int callingUid = Binder.getCallingUid();
17916        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
17917            throw new SecurityException(
17918                    "setRequiredForSystemUser can only be run by the system or root");
17919        }
17920        synchronized (mPackages) {
17921            PackageSetting ps = mSettings.mPackages.get(packageName);
17922            if (ps == null) {
17923                Log.w(TAG, "Package doesn't exist: " + packageName);
17924                return false;
17925            }
17926            if (systemUserApp) {
17927                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
17928            } else {
17929                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
17930            }
17931            mSettings.writeLPr();
17932        }
17933        return true;
17934    }
17935
17936    /*
17937     * This method handles package deletion in general
17938     */
17939    private boolean deletePackageLIF(String packageName, UserHandle user,
17940            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
17941            PackageRemovedInfo outInfo, boolean writeSettings,
17942            PackageParser.Package replacingPackage) {
17943        if (packageName == null) {
17944            Slog.w(TAG, "Attempt to delete null packageName.");
17945            return false;
17946        }
17947
17948        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
17949
17950        PackageSetting ps;
17951        synchronized (mPackages) {
17952            ps = mSettings.mPackages.get(packageName);
17953            if (ps == null) {
17954                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
17955                return false;
17956            }
17957
17958            if (ps.parentPackageName != null && (!isSystemApp(ps)
17959                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
17960                if (DEBUG_REMOVE) {
17961                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
17962                            + ((user == null) ? UserHandle.USER_ALL : user));
17963                }
17964                final int removedUserId = (user != null) ? user.getIdentifier()
17965                        : UserHandle.USER_ALL;
17966                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
17967                    return false;
17968                }
17969                markPackageUninstalledForUserLPw(ps, user);
17970                scheduleWritePackageRestrictionsLocked(user);
17971                return true;
17972            }
17973        }
17974
17975        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
17976                && user.getIdentifier() != UserHandle.USER_ALL)) {
17977            // The caller is asking that the package only be deleted for a single
17978            // user.  To do this, we just mark its uninstalled state and delete
17979            // its data. If this is a system app, we only allow this to happen if
17980            // they have set the special DELETE_SYSTEM_APP which requests different
17981            // semantics than normal for uninstalling system apps.
17982            markPackageUninstalledForUserLPw(ps, user);
17983
17984            if (!isSystemApp(ps)) {
17985                // Do not uninstall the APK if an app should be cached
17986                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
17987                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
17988                    // Other user still have this package installed, so all
17989                    // we need to do is clear this user's data and save that
17990                    // it is uninstalled.
17991                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
17992                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
17993                        return false;
17994                    }
17995                    scheduleWritePackageRestrictionsLocked(user);
17996                    return true;
17997                } else {
17998                    // We need to set it back to 'installed' so the uninstall
17999                    // broadcasts will be sent correctly.
18000                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18001                    ps.setInstalled(true, user.getIdentifier());
18002                }
18003            } else {
18004                // This is a system app, so we assume that the
18005                // other users still have this package installed, so all
18006                // we need to do is clear this user's data and save that
18007                // it is uninstalled.
18008                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18009                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18010                    return false;
18011                }
18012                scheduleWritePackageRestrictionsLocked(user);
18013                return true;
18014            }
18015        }
18016
18017        // If we are deleting a composite package for all users, keep track
18018        // of result for each child.
18019        if (ps.childPackageNames != null && outInfo != null) {
18020            synchronized (mPackages) {
18021                final int childCount = ps.childPackageNames.size();
18022                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18023                for (int i = 0; i < childCount; i++) {
18024                    String childPackageName = ps.childPackageNames.get(i);
18025                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
18026                    childInfo.removedPackage = childPackageName;
18027                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18028                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18029                    if (childPs != null) {
18030                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18031                    }
18032                }
18033            }
18034        }
18035
18036        boolean ret = false;
18037        if (isSystemApp(ps)) {
18038            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18039            // When an updated system application is deleted we delete the existing resources
18040            // as well and fall back to existing code in system partition
18041            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18042        } else {
18043            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18044            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18045                    outInfo, writeSettings, replacingPackage);
18046        }
18047
18048        // Take a note whether we deleted the package for all users
18049        if (outInfo != null) {
18050            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18051            if (outInfo.removedChildPackages != null) {
18052                synchronized (mPackages) {
18053                    final int childCount = outInfo.removedChildPackages.size();
18054                    for (int i = 0; i < childCount; i++) {
18055                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18056                        if (childInfo != null) {
18057                            childInfo.removedForAllUsers = mPackages.get(
18058                                    childInfo.removedPackage) == null;
18059                        }
18060                    }
18061                }
18062            }
18063            // If we uninstalled an update to a system app there may be some
18064            // child packages that appeared as they are declared in the system
18065            // app but were not declared in the update.
18066            if (isSystemApp(ps)) {
18067                synchronized (mPackages) {
18068                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18069                    final int childCount = (updatedPs.childPackageNames != null)
18070                            ? updatedPs.childPackageNames.size() : 0;
18071                    for (int i = 0; i < childCount; i++) {
18072                        String childPackageName = updatedPs.childPackageNames.get(i);
18073                        if (outInfo.removedChildPackages == null
18074                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18075                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18076                            if (childPs == null) {
18077                                continue;
18078                            }
18079                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18080                            installRes.name = childPackageName;
18081                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18082                            installRes.pkg = mPackages.get(childPackageName);
18083                            installRes.uid = childPs.pkg.applicationInfo.uid;
18084                            if (outInfo.appearedChildPackages == null) {
18085                                outInfo.appearedChildPackages = new ArrayMap<>();
18086                            }
18087                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18088                        }
18089                    }
18090                }
18091            }
18092        }
18093
18094        return ret;
18095    }
18096
18097    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18098        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18099                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18100        for (int nextUserId : userIds) {
18101            if (DEBUG_REMOVE) {
18102                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18103            }
18104            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18105                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
18106                    false /*hidden*/, false /*suspended*/, null, null, null,
18107                    false /*blockUninstall*/,
18108                    ps.readUserState(nextUserId).domainVerificationStatus, 0,
18109                    PackageManager.INSTALL_REASON_UNKNOWN);
18110        }
18111    }
18112
18113    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18114            PackageRemovedInfo outInfo) {
18115        final PackageParser.Package pkg;
18116        synchronized (mPackages) {
18117            pkg = mPackages.get(ps.name);
18118        }
18119
18120        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18121                : new int[] {userId};
18122        for (int nextUserId : userIds) {
18123            if (DEBUG_REMOVE) {
18124                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18125                        + nextUserId);
18126            }
18127
18128            destroyAppDataLIF(pkg, userId,
18129                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18130            destroyAppProfilesLIF(pkg, userId);
18131            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18132            schedulePackageCleaning(ps.name, nextUserId, false);
18133            synchronized (mPackages) {
18134                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18135                    scheduleWritePackageRestrictionsLocked(nextUserId);
18136                }
18137                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18138            }
18139        }
18140
18141        if (outInfo != null) {
18142            outInfo.removedPackage = ps.name;
18143            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18144            outInfo.removedAppId = ps.appId;
18145            outInfo.removedUsers = userIds;
18146        }
18147
18148        return true;
18149    }
18150
18151    private final class ClearStorageConnection implements ServiceConnection {
18152        IMediaContainerService mContainerService;
18153
18154        @Override
18155        public void onServiceConnected(ComponentName name, IBinder service) {
18156            synchronized (this) {
18157                mContainerService = IMediaContainerService.Stub
18158                        .asInterface(Binder.allowBlocking(service));
18159                notifyAll();
18160            }
18161        }
18162
18163        @Override
18164        public void onServiceDisconnected(ComponentName name) {
18165        }
18166    }
18167
18168    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18169        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18170
18171        final boolean mounted;
18172        if (Environment.isExternalStorageEmulated()) {
18173            mounted = true;
18174        } else {
18175            final String status = Environment.getExternalStorageState();
18176
18177            mounted = status.equals(Environment.MEDIA_MOUNTED)
18178                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18179        }
18180
18181        if (!mounted) {
18182            return;
18183        }
18184
18185        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18186        int[] users;
18187        if (userId == UserHandle.USER_ALL) {
18188            users = sUserManager.getUserIds();
18189        } else {
18190            users = new int[] { userId };
18191        }
18192        final ClearStorageConnection conn = new ClearStorageConnection();
18193        if (mContext.bindServiceAsUser(
18194                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18195            try {
18196                for (int curUser : users) {
18197                    long timeout = SystemClock.uptimeMillis() + 5000;
18198                    synchronized (conn) {
18199                        long now;
18200                        while (conn.mContainerService == null &&
18201                                (now = SystemClock.uptimeMillis()) < timeout) {
18202                            try {
18203                                conn.wait(timeout - now);
18204                            } catch (InterruptedException e) {
18205                            }
18206                        }
18207                    }
18208                    if (conn.mContainerService == null) {
18209                        return;
18210                    }
18211
18212                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18213                    clearDirectory(conn.mContainerService,
18214                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18215                    if (allData) {
18216                        clearDirectory(conn.mContainerService,
18217                                userEnv.buildExternalStorageAppDataDirs(packageName));
18218                        clearDirectory(conn.mContainerService,
18219                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18220                    }
18221                }
18222            } finally {
18223                mContext.unbindService(conn);
18224            }
18225        }
18226    }
18227
18228    @Override
18229    public void clearApplicationProfileData(String packageName) {
18230        enforceSystemOrRoot("Only the system can clear all profile data");
18231
18232        final PackageParser.Package pkg;
18233        synchronized (mPackages) {
18234            pkg = mPackages.get(packageName);
18235        }
18236
18237        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18238            synchronized (mInstallLock) {
18239                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18240                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
18241                        true /* removeBaseMarker */);
18242            }
18243        }
18244    }
18245
18246    @Override
18247    public void clearApplicationUserData(final String packageName,
18248            final IPackageDataObserver observer, final int userId) {
18249        mContext.enforceCallingOrSelfPermission(
18250                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18251
18252        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18253                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18254
18255        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18256            throw new SecurityException("Cannot clear data for a protected package: "
18257                    + packageName);
18258        }
18259        // Queue up an async operation since the package deletion may take a little while.
18260        mHandler.post(new Runnable() {
18261            public void run() {
18262                mHandler.removeCallbacks(this);
18263                final boolean succeeded;
18264                try (PackageFreezer freezer = freezePackage(packageName,
18265                        "clearApplicationUserData")) {
18266                    synchronized (mInstallLock) {
18267                        succeeded = clearApplicationUserDataLIF(packageName, userId);
18268                    }
18269                    clearExternalStorageDataSync(packageName, userId, true);
18270                    synchronized (mPackages) {
18271                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18272                                packageName, userId);
18273                    }
18274                }
18275                if (succeeded) {
18276                    // invoke DeviceStorageMonitor's update method to clear any notifications
18277                    DeviceStorageMonitorInternal dsm = LocalServices
18278                            .getService(DeviceStorageMonitorInternal.class);
18279                    if (dsm != null) {
18280                        dsm.checkMemory();
18281                    }
18282                }
18283                if(observer != null) {
18284                    try {
18285                        observer.onRemoveCompleted(packageName, succeeded);
18286                    } catch (RemoteException e) {
18287                        Log.i(TAG, "Observer no longer exists.");
18288                    }
18289                } //end if observer
18290            } //end run
18291        });
18292    }
18293
18294    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
18295        if (packageName == null) {
18296            Slog.w(TAG, "Attempt to delete null packageName.");
18297            return false;
18298        }
18299
18300        // Try finding details about the requested package
18301        PackageParser.Package pkg;
18302        synchronized (mPackages) {
18303            pkg = mPackages.get(packageName);
18304            if (pkg == null) {
18305                final PackageSetting ps = mSettings.mPackages.get(packageName);
18306                if (ps != null) {
18307                    pkg = ps.pkg;
18308                }
18309            }
18310
18311            if (pkg == null) {
18312                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18313                return false;
18314            }
18315
18316            PackageSetting ps = (PackageSetting) pkg.mExtras;
18317            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18318        }
18319
18320        clearAppDataLIF(pkg, userId,
18321                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18322
18323        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18324        removeKeystoreDataIfNeeded(userId, appId);
18325
18326        UserManagerInternal umInternal = getUserManagerInternal();
18327        final int flags;
18328        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
18329            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18330        } else if (umInternal.isUserRunning(userId)) {
18331            flags = StorageManager.FLAG_STORAGE_DE;
18332        } else {
18333            flags = 0;
18334        }
18335        prepareAppDataContentsLIF(pkg, userId, flags);
18336
18337        return true;
18338    }
18339
18340    /**
18341     * Reverts user permission state changes (permissions and flags) in
18342     * all packages for a given user.
18343     *
18344     * @param userId The device user for which to do a reset.
18345     */
18346    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
18347        final int packageCount = mPackages.size();
18348        for (int i = 0; i < packageCount; i++) {
18349            PackageParser.Package pkg = mPackages.valueAt(i);
18350            PackageSetting ps = (PackageSetting) pkg.mExtras;
18351            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
18352        }
18353    }
18354
18355    private void resetNetworkPolicies(int userId) {
18356        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
18357    }
18358
18359    /**
18360     * Reverts user permission state changes (permissions and flags).
18361     *
18362     * @param ps The package for which to reset.
18363     * @param userId The device user for which to do a reset.
18364     */
18365    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
18366            final PackageSetting ps, final int userId) {
18367        if (ps.pkg == null) {
18368            return;
18369        }
18370
18371        // These are flags that can change base on user actions.
18372        final int userSettableMask = FLAG_PERMISSION_USER_SET
18373                | FLAG_PERMISSION_USER_FIXED
18374                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
18375                | FLAG_PERMISSION_REVIEW_REQUIRED;
18376
18377        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
18378                | FLAG_PERMISSION_POLICY_FIXED;
18379
18380        boolean writeInstallPermissions = false;
18381        boolean writeRuntimePermissions = false;
18382
18383        final int permissionCount = ps.pkg.requestedPermissions.size();
18384        for (int i = 0; i < permissionCount; i++) {
18385            String permission = ps.pkg.requestedPermissions.get(i);
18386
18387            BasePermission bp = mSettings.mPermissions.get(permission);
18388            if (bp == null) {
18389                continue;
18390            }
18391
18392            // If shared user we just reset the state to which only this app contributed.
18393            if (ps.sharedUser != null) {
18394                boolean used = false;
18395                final int packageCount = ps.sharedUser.packages.size();
18396                for (int j = 0; j < packageCount; j++) {
18397                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
18398                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
18399                            && pkg.pkg.requestedPermissions.contains(permission)) {
18400                        used = true;
18401                        break;
18402                    }
18403                }
18404                if (used) {
18405                    continue;
18406                }
18407            }
18408
18409            PermissionsState permissionsState = ps.getPermissionsState();
18410
18411            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
18412
18413            // Always clear the user settable flags.
18414            final boolean hasInstallState = permissionsState.getInstallPermissionState(
18415                    bp.name) != null;
18416            // If permission review is enabled and this is a legacy app, mark the
18417            // permission as requiring a review as this is the initial state.
18418            int flags = 0;
18419            if (mPermissionReviewRequired
18420                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
18421                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
18422            }
18423            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
18424                if (hasInstallState) {
18425                    writeInstallPermissions = true;
18426                } else {
18427                    writeRuntimePermissions = true;
18428                }
18429            }
18430
18431            // Below is only runtime permission handling.
18432            if (!bp.isRuntime()) {
18433                continue;
18434            }
18435
18436            // Never clobber system or policy.
18437            if ((oldFlags & policyOrSystemFlags) != 0) {
18438                continue;
18439            }
18440
18441            // If this permission was granted by default, make sure it is.
18442            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
18443                if (permissionsState.grantRuntimePermission(bp, userId)
18444                        != PERMISSION_OPERATION_FAILURE) {
18445                    writeRuntimePermissions = true;
18446                }
18447            // If permission review is enabled the permissions for a legacy apps
18448            // are represented as constantly granted runtime ones, so don't revoke.
18449            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
18450                // Otherwise, reset the permission.
18451                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
18452                switch (revokeResult) {
18453                    case PERMISSION_OPERATION_SUCCESS:
18454                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
18455                        writeRuntimePermissions = true;
18456                        final int appId = ps.appId;
18457                        mHandler.post(new Runnable() {
18458                            @Override
18459                            public void run() {
18460                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
18461                            }
18462                        });
18463                    } break;
18464                }
18465            }
18466        }
18467
18468        // Synchronously write as we are taking permissions away.
18469        if (writeRuntimePermissions) {
18470            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
18471        }
18472
18473        // Synchronously write as we are taking permissions away.
18474        if (writeInstallPermissions) {
18475            mSettings.writeLPr();
18476        }
18477    }
18478
18479    /**
18480     * Remove entries from the keystore daemon. Will only remove it if the
18481     * {@code appId} is valid.
18482     */
18483    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
18484        if (appId < 0) {
18485            return;
18486        }
18487
18488        final KeyStore keyStore = KeyStore.getInstance();
18489        if (keyStore != null) {
18490            if (userId == UserHandle.USER_ALL) {
18491                for (final int individual : sUserManager.getUserIds()) {
18492                    keyStore.clearUid(UserHandle.getUid(individual, appId));
18493                }
18494            } else {
18495                keyStore.clearUid(UserHandle.getUid(userId, appId));
18496            }
18497        } else {
18498            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
18499        }
18500    }
18501
18502    @Override
18503    public void deleteApplicationCacheFiles(final String packageName,
18504            final IPackageDataObserver observer) {
18505        final int userId = UserHandle.getCallingUserId();
18506        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
18507    }
18508
18509    @Override
18510    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
18511            final IPackageDataObserver observer) {
18512        mContext.enforceCallingOrSelfPermission(
18513                android.Manifest.permission.DELETE_CACHE_FILES, null);
18514        enforceCrossUserPermission(Binder.getCallingUid(), userId,
18515                /* requireFullPermission= */ true, /* checkShell= */ false,
18516                "delete application cache files");
18517
18518        final PackageParser.Package pkg;
18519        synchronized (mPackages) {
18520            pkg = mPackages.get(packageName);
18521        }
18522
18523        // Queue up an async operation since the package deletion may take a little while.
18524        mHandler.post(new Runnable() {
18525            public void run() {
18526                synchronized (mInstallLock) {
18527                    final int flags = StorageManager.FLAG_STORAGE_DE
18528                            | StorageManager.FLAG_STORAGE_CE;
18529                    // We're only clearing cache files, so we don't care if the
18530                    // app is unfrozen and still able to run
18531                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
18532                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
18533                }
18534                clearExternalStorageDataSync(packageName, userId, false);
18535                if (observer != null) {
18536                    try {
18537                        observer.onRemoveCompleted(packageName, true);
18538                    } catch (RemoteException e) {
18539                        Log.i(TAG, "Observer no longer exists.");
18540                    }
18541                }
18542            }
18543        });
18544    }
18545
18546    @Override
18547    public void getPackageSizeInfo(final String packageName, int userHandle,
18548            final IPackageStatsObserver observer) {
18549        mContext.enforceCallingOrSelfPermission(
18550                android.Manifest.permission.GET_PACKAGE_SIZE, null);
18551        if (packageName == null) {
18552            throw new IllegalArgumentException("Attempt to get size of null packageName");
18553        }
18554
18555        PackageStats stats = new PackageStats(packageName, userHandle);
18556
18557        /*
18558         * Queue up an async operation since the package measurement may take a
18559         * little while.
18560         */
18561        Message msg = mHandler.obtainMessage(INIT_COPY);
18562        msg.obj = new MeasureParams(stats, observer);
18563        mHandler.sendMessage(msg);
18564    }
18565
18566    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
18567        final PackageSetting ps;
18568        synchronized (mPackages) {
18569            ps = mSettings.mPackages.get(packageName);
18570            if (ps == null) {
18571                Slog.w(TAG, "Failed to find settings for " + packageName);
18572                return false;
18573            }
18574        }
18575
18576        final String[] packageNames = { packageName };
18577        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
18578        final String[] codePaths = { ps.codePathString };
18579
18580        try {
18581            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
18582                    ps.appId, ceDataInodes, codePaths, stats);
18583
18584            // For now, ignore code size of packages on system partition
18585            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
18586                stats.codeSize = 0;
18587            }
18588
18589            // External clients expect these to be tracked separately
18590            stats.dataSize -= stats.cacheSize;
18591
18592        } catch (InstallerException e) {
18593            Slog.w(TAG, String.valueOf(e));
18594            return false;
18595        }
18596
18597        return true;
18598    }
18599
18600    private int getUidTargetSdkVersionLockedLPr(int uid) {
18601        Object obj = mSettings.getUserIdLPr(uid);
18602        if (obj instanceof SharedUserSetting) {
18603            final SharedUserSetting sus = (SharedUserSetting) obj;
18604            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
18605            final Iterator<PackageSetting> it = sus.packages.iterator();
18606            while (it.hasNext()) {
18607                final PackageSetting ps = it.next();
18608                if (ps.pkg != null) {
18609                    int v = ps.pkg.applicationInfo.targetSdkVersion;
18610                    if (v < vers) vers = v;
18611                }
18612            }
18613            return vers;
18614        } else if (obj instanceof PackageSetting) {
18615            final PackageSetting ps = (PackageSetting) obj;
18616            if (ps.pkg != null) {
18617                return ps.pkg.applicationInfo.targetSdkVersion;
18618            }
18619        }
18620        return Build.VERSION_CODES.CUR_DEVELOPMENT;
18621    }
18622
18623    @Override
18624    public void addPreferredActivity(IntentFilter filter, int match,
18625            ComponentName[] set, ComponentName activity, int userId) {
18626        addPreferredActivityInternal(filter, match, set, activity, true, userId,
18627                "Adding preferred");
18628    }
18629
18630    private void addPreferredActivityInternal(IntentFilter filter, int match,
18631            ComponentName[] set, ComponentName activity, boolean always, int userId,
18632            String opname) {
18633        // writer
18634        int callingUid = Binder.getCallingUid();
18635        enforceCrossUserPermission(callingUid, userId,
18636                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
18637        if (filter.countActions() == 0) {
18638            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18639            return;
18640        }
18641        synchronized (mPackages) {
18642            if (mContext.checkCallingOrSelfPermission(
18643                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18644                    != PackageManager.PERMISSION_GRANTED) {
18645                if (getUidTargetSdkVersionLockedLPr(callingUid)
18646                        < Build.VERSION_CODES.FROYO) {
18647                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
18648                            + callingUid);
18649                    return;
18650                }
18651                mContext.enforceCallingOrSelfPermission(
18652                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18653            }
18654
18655            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
18656            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
18657                    + userId + ":");
18658            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18659            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
18660            scheduleWritePackageRestrictionsLocked(userId);
18661            postPreferredActivityChangedBroadcast(userId);
18662        }
18663    }
18664
18665    private void postPreferredActivityChangedBroadcast(int userId) {
18666        mHandler.post(() -> {
18667            final IActivityManager am = ActivityManager.getService();
18668            if (am == null) {
18669                return;
18670            }
18671
18672            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
18673            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
18674            try {
18675                am.broadcastIntent(null, intent, null, null,
18676                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
18677                        null, false, false, userId);
18678            } catch (RemoteException e) {
18679            }
18680        });
18681    }
18682
18683    @Override
18684    public void replacePreferredActivity(IntentFilter filter, int match,
18685            ComponentName[] set, ComponentName activity, int userId) {
18686        if (filter.countActions() != 1) {
18687            throw new IllegalArgumentException(
18688                    "replacePreferredActivity expects filter to have only 1 action.");
18689        }
18690        if (filter.countDataAuthorities() != 0
18691                || filter.countDataPaths() != 0
18692                || filter.countDataSchemes() > 1
18693                || filter.countDataTypes() != 0) {
18694            throw new IllegalArgumentException(
18695                    "replacePreferredActivity expects filter to have no data authorities, " +
18696                    "paths, or types; and at most one scheme.");
18697        }
18698
18699        final int callingUid = Binder.getCallingUid();
18700        enforceCrossUserPermission(callingUid, userId,
18701                true /* requireFullPermission */, false /* checkShell */,
18702                "replace preferred activity");
18703        synchronized (mPackages) {
18704            if (mContext.checkCallingOrSelfPermission(
18705                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18706                    != PackageManager.PERMISSION_GRANTED) {
18707                if (getUidTargetSdkVersionLockedLPr(callingUid)
18708                        < Build.VERSION_CODES.FROYO) {
18709                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
18710                            + Binder.getCallingUid());
18711                    return;
18712                }
18713                mContext.enforceCallingOrSelfPermission(
18714                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18715            }
18716
18717            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18718            if (pir != null) {
18719                // Get all of the existing entries that exactly match this filter.
18720                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
18721                if (existing != null && existing.size() == 1) {
18722                    PreferredActivity cur = existing.get(0);
18723                    if (DEBUG_PREFERRED) {
18724                        Slog.i(TAG, "Checking replace of preferred:");
18725                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18726                        if (!cur.mPref.mAlways) {
18727                            Slog.i(TAG, "  -- CUR; not mAlways!");
18728                        } else {
18729                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
18730                            Slog.i(TAG, "  -- CUR: mSet="
18731                                    + Arrays.toString(cur.mPref.mSetComponents));
18732                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
18733                            Slog.i(TAG, "  -- NEW: mMatch="
18734                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
18735                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
18736                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
18737                        }
18738                    }
18739                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
18740                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
18741                            && cur.mPref.sameSet(set)) {
18742                        // Setting the preferred activity to what it happens to be already
18743                        if (DEBUG_PREFERRED) {
18744                            Slog.i(TAG, "Replacing with same preferred activity "
18745                                    + cur.mPref.mShortComponent + " for user "
18746                                    + userId + ":");
18747                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18748                        }
18749                        return;
18750                    }
18751                }
18752
18753                if (existing != null) {
18754                    if (DEBUG_PREFERRED) {
18755                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
18756                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18757                    }
18758                    for (int i = 0; i < existing.size(); i++) {
18759                        PreferredActivity pa = existing.get(i);
18760                        if (DEBUG_PREFERRED) {
18761                            Slog.i(TAG, "Removing existing preferred activity "
18762                                    + pa.mPref.mComponent + ":");
18763                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
18764                        }
18765                        pir.removeFilter(pa);
18766                    }
18767                }
18768            }
18769            addPreferredActivityInternal(filter, match, set, activity, true, userId,
18770                    "Replacing preferred");
18771        }
18772    }
18773
18774    @Override
18775    public void clearPackagePreferredActivities(String packageName) {
18776        final int uid = Binder.getCallingUid();
18777        // writer
18778        synchronized (mPackages) {
18779            PackageParser.Package pkg = mPackages.get(packageName);
18780            if (pkg == null || pkg.applicationInfo.uid != uid) {
18781                if (mContext.checkCallingOrSelfPermission(
18782                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
18783                        != PackageManager.PERMISSION_GRANTED) {
18784                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
18785                            < Build.VERSION_CODES.FROYO) {
18786                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
18787                                + Binder.getCallingUid());
18788                        return;
18789                    }
18790                    mContext.enforceCallingOrSelfPermission(
18791                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18792                }
18793            }
18794
18795            int user = UserHandle.getCallingUserId();
18796            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
18797                scheduleWritePackageRestrictionsLocked(user);
18798            }
18799        }
18800    }
18801
18802    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18803    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
18804        ArrayList<PreferredActivity> removed = null;
18805        boolean changed = false;
18806        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18807            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
18808            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18809            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
18810                continue;
18811            }
18812            Iterator<PreferredActivity> it = pir.filterIterator();
18813            while (it.hasNext()) {
18814                PreferredActivity pa = it.next();
18815                // Mark entry for removal only if it matches the package name
18816                // and the entry is of type "always".
18817                if (packageName == null ||
18818                        (pa.mPref.mComponent.getPackageName().equals(packageName)
18819                                && pa.mPref.mAlways)) {
18820                    if (removed == null) {
18821                        removed = new ArrayList<PreferredActivity>();
18822                    }
18823                    removed.add(pa);
18824                }
18825            }
18826            if (removed != null) {
18827                for (int j=0; j<removed.size(); j++) {
18828                    PreferredActivity pa = removed.get(j);
18829                    pir.removeFilter(pa);
18830                }
18831                changed = true;
18832            }
18833        }
18834        if (changed) {
18835            postPreferredActivityChangedBroadcast(userId);
18836        }
18837        return changed;
18838    }
18839
18840    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18841    private void clearIntentFilterVerificationsLPw(int userId) {
18842        final int packageCount = mPackages.size();
18843        for (int i = 0; i < packageCount; i++) {
18844            PackageParser.Package pkg = mPackages.valueAt(i);
18845            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
18846        }
18847    }
18848
18849    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
18850    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
18851        if (userId == UserHandle.USER_ALL) {
18852            if (mSettings.removeIntentFilterVerificationLPw(packageName,
18853                    sUserManager.getUserIds())) {
18854                for (int oneUserId : sUserManager.getUserIds()) {
18855                    scheduleWritePackageRestrictionsLocked(oneUserId);
18856                }
18857            }
18858        } else {
18859            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
18860                scheduleWritePackageRestrictionsLocked(userId);
18861            }
18862        }
18863    }
18864
18865    void clearDefaultBrowserIfNeeded(String packageName) {
18866        for (int oneUserId : sUserManager.getUserIds()) {
18867            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
18868            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
18869            if (packageName.equals(defaultBrowserPackageName)) {
18870                setDefaultBrowserPackageName(null, oneUserId);
18871            }
18872        }
18873    }
18874
18875    @Override
18876    public void resetApplicationPreferences(int userId) {
18877        mContext.enforceCallingOrSelfPermission(
18878                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
18879        final long identity = Binder.clearCallingIdentity();
18880        // writer
18881        try {
18882            synchronized (mPackages) {
18883                clearPackagePreferredActivitiesLPw(null, userId);
18884                mSettings.applyDefaultPreferredAppsLPw(this, userId);
18885                // TODO: We have to reset the default SMS and Phone. This requires
18886                // significant refactoring to keep all default apps in the package
18887                // manager (cleaner but more work) or have the services provide
18888                // callbacks to the package manager to request a default app reset.
18889                applyFactoryDefaultBrowserLPw(userId);
18890                clearIntentFilterVerificationsLPw(userId);
18891                primeDomainVerificationsLPw(userId);
18892                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
18893                scheduleWritePackageRestrictionsLocked(userId);
18894            }
18895            resetNetworkPolicies(userId);
18896        } finally {
18897            Binder.restoreCallingIdentity(identity);
18898        }
18899    }
18900
18901    @Override
18902    public int getPreferredActivities(List<IntentFilter> outFilters,
18903            List<ComponentName> outActivities, String packageName) {
18904
18905        int num = 0;
18906        final int userId = UserHandle.getCallingUserId();
18907        // reader
18908        synchronized (mPackages) {
18909            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
18910            if (pir != null) {
18911                final Iterator<PreferredActivity> it = pir.filterIterator();
18912                while (it.hasNext()) {
18913                    final PreferredActivity pa = it.next();
18914                    if (packageName == null
18915                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
18916                                    && pa.mPref.mAlways)) {
18917                        if (outFilters != null) {
18918                            outFilters.add(new IntentFilter(pa));
18919                        }
18920                        if (outActivities != null) {
18921                            outActivities.add(pa.mPref.mComponent);
18922                        }
18923                    }
18924                }
18925            }
18926        }
18927
18928        return num;
18929    }
18930
18931    @Override
18932    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
18933            int userId) {
18934        int callingUid = Binder.getCallingUid();
18935        if (callingUid != Process.SYSTEM_UID) {
18936            throw new SecurityException(
18937                    "addPersistentPreferredActivity can only be run by the system");
18938        }
18939        if (filter.countActions() == 0) {
18940            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
18941            return;
18942        }
18943        synchronized (mPackages) {
18944            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
18945                    ":");
18946            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
18947            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
18948                    new PersistentPreferredActivity(filter, activity));
18949            scheduleWritePackageRestrictionsLocked(userId);
18950            postPreferredActivityChangedBroadcast(userId);
18951        }
18952    }
18953
18954    @Override
18955    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
18956        int callingUid = Binder.getCallingUid();
18957        if (callingUid != Process.SYSTEM_UID) {
18958            throw new SecurityException(
18959                    "clearPackagePersistentPreferredActivities can only be run by the system");
18960        }
18961        ArrayList<PersistentPreferredActivity> removed = null;
18962        boolean changed = false;
18963        synchronized (mPackages) {
18964            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
18965                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
18966                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
18967                        .valueAt(i);
18968                if (userId != thisUserId) {
18969                    continue;
18970                }
18971                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
18972                while (it.hasNext()) {
18973                    PersistentPreferredActivity ppa = it.next();
18974                    // Mark entry for removal only if it matches the package name.
18975                    if (ppa.mComponent.getPackageName().equals(packageName)) {
18976                        if (removed == null) {
18977                            removed = new ArrayList<PersistentPreferredActivity>();
18978                        }
18979                        removed.add(ppa);
18980                    }
18981                }
18982                if (removed != null) {
18983                    for (int j=0; j<removed.size(); j++) {
18984                        PersistentPreferredActivity ppa = removed.get(j);
18985                        ppir.removeFilter(ppa);
18986                    }
18987                    changed = true;
18988                }
18989            }
18990
18991            if (changed) {
18992                scheduleWritePackageRestrictionsLocked(userId);
18993                postPreferredActivityChangedBroadcast(userId);
18994            }
18995        }
18996    }
18997
18998    /**
18999     * Common machinery for picking apart a restored XML blob and passing
19000     * it to a caller-supplied functor to be applied to the running system.
19001     */
19002    private void restoreFromXml(XmlPullParser parser, int userId,
19003            String expectedStartTag, BlobXmlRestorer functor)
19004            throws IOException, XmlPullParserException {
19005        int type;
19006        while ((type = parser.next()) != XmlPullParser.START_TAG
19007                && type != XmlPullParser.END_DOCUMENT) {
19008        }
19009        if (type != XmlPullParser.START_TAG) {
19010            // oops didn't find a start tag?!
19011            if (DEBUG_BACKUP) {
19012                Slog.e(TAG, "Didn't find start tag during restore");
19013            }
19014            return;
19015        }
19016Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19017        // this is supposed to be TAG_PREFERRED_BACKUP
19018        if (!expectedStartTag.equals(parser.getName())) {
19019            if (DEBUG_BACKUP) {
19020                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19021            }
19022            return;
19023        }
19024
19025        // skip interfering stuff, then we're aligned with the backing implementation
19026        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19027Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19028        functor.apply(parser, userId);
19029    }
19030
19031    private interface BlobXmlRestorer {
19032        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19033    }
19034
19035    /**
19036     * Non-Binder method, support for the backup/restore mechanism: write the
19037     * full set of preferred activities in its canonical XML format.  Returns the
19038     * XML output as a byte array, or null if there is none.
19039     */
19040    @Override
19041    public byte[] getPreferredActivityBackup(int userId) {
19042        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19043            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19044        }
19045
19046        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19047        try {
19048            final XmlSerializer serializer = new FastXmlSerializer();
19049            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19050            serializer.startDocument(null, true);
19051            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19052
19053            synchronized (mPackages) {
19054                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19055            }
19056
19057            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19058            serializer.endDocument();
19059            serializer.flush();
19060        } catch (Exception e) {
19061            if (DEBUG_BACKUP) {
19062                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19063            }
19064            return null;
19065        }
19066
19067        return dataStream.toByteArray();
19068    }
19069
19070    @Override
19071    public void restorePreferredActivities(byte[] backup, int userId) {
19072        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19073            throw new SecurityException("Only the system may call restorePreferredActivities()");
19074        }
19075
19076        try {
19077            final XmlPullParser parser = Xml.newPullParser();
19078            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19079            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19080                    new BlobXmlRestorer() {
19081                        @Override
19082                        public void apply(XmlPullParser parser, int userId)
19083                                throws XmlPullParserException, IOException {
19084                            synchronized (mPackages) {
19085                                mSettings.readPreferredActivitiesLPw(parser, userId);
19086                            }
19087                        }
19088                    } );
19089        } catch (Exception e) {
19090            if (DEBUG_BACKUP) {
19091                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19092            }
19093        }
19094    }
19095
19096    /**
19097     * Non-Binder method, support for the backup/restore mechanism: write the
19098     * default browser (etc) settings in its canonical XML format.  Returns the default
19099     * browser XML representation as a byte array, or null if there is none.
19100     */
19101    @Override
19102    public byte[] getDefaultAppsBackup(int userId) {
19103        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19104            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19105        }
19106
19107        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19108        try {
19109            final XmlSerializer serializer = new FastXmlSerializer();
19110            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19111            serializer.startDocument(null, true);
19112            serializer.startTag(null, TAG_DEFAULT_APPS);
19113
19114            synchronized (mPackages) {
19115                mSettings.writeDefaultAppsLPr(serializer, userId);
19116            }
19117
19118            serializer.endTag(null, TAG_DEFAULT_APPS);
19119            serializer.endDocument();
19120            serializer.flush();
19121        } catch (Exception e) {
19122            if (DEBUG_BACKUP) {
19123                Slog.e(TAG, "Unable to write default apps for backup", e);
19124            }
19125            return null;
19126        }
19127
19128        return dataStream.toByteArray();
19129    }
19130
19131    @Override
19132    public void restoreDefaultApps(byte[] backup, int userId) {
19133        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19134            throw new SecurityException("Only the system may call restoreDefaultApps()");
19135        }
19136
19137        try {
19138            final XmlPullParser parser = Xml.newPullParser();
19139            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19140            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19141                    new BlobXmlRestorer() {
19142                        @Override
19143                        public void apply(XmlPullParser parser, int userId)
19144                                throws XmlPullParserException, IOException {
19145                            synchronized (mPackages) {
19146                                mSettings.readDefaultAppsLPw(parser, userId);
19147                            }
19148                        }
19149                    } );
19150        } catch (Exception e) {
19151            if (DEBUG_BACKUP) {
19152                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19153            }
19154        }
19155    }
19156
19157    @Override
19158    public byte[] getIntentFilterVerificationBackup(int userId) {
19159        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19160            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19161        }
19162
19163        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19164        try {
19165            final XmlSerializer serializer = new FastXmlSerializer();
19166            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19167            serializer.startDocument(null, true);
19168            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19169
19170            synchronized (mPackages) {
19171                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19172            }
19173
19174            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19175            serializer.endDocument();
19176            serializer.flush();
19177        } catch (Exception e) {
19178            if (DEBUG_BACKUP) {
19179                Slog.e(TAG, "Unable to write default apps for backup", e);
19180            }
19181            return null;
19182        }
19183
19184        return dataStream.toByteArray();
19185    }
19186
19187    @Override
19188    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19189        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19190            throw new SecurityException("Only the system may call restorePreferredActivities()");
19191        }
19192
19193        try {
19194            final XmlPullParser parser = Xml.newPullParser();
19195            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19196            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19197                    new BlobXmlRestorer() {
19198                        @Override
19199                        public void apply(XmlPullParser parser, int userId)
19200                                throws XmlPullParserException, IOException {
19201                            synchronized (mPackages) {
19202                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19203                                mSettings.writeLPr();
19204                            }
19205                        }
19206                    } );
19207        } catch (Exception e) {
19208            if (DEBUG_BACKUP) {
19209                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19210            }
19211        }
19212    }
19213
19214    @Override
19215    public byte[] getPermissionGrantBackup(int userId) {
19216        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19217            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19218        }
19219
19220        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19221        try {
19222            final XmlSerializer serializer = new FastXmlSerializer();
19223            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19224            serializer.startDocument(null, true);
19225            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19226
19227            synchronized (mPackages) {
19228                serializeRuntimePermissionGrantsLPr(serializer, userId);
19229            }
19230
19231            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19232            serializer.endDocument();
19233            serializer.flush();
19234        } catch (Exception e) {
19235            if (DEBUG_BACKUP) {
19236                Slog.e(TAG, "Unable to write default apps for backup", e);
19237            }
19238            return null;
19239        }
19240
19241        return dataStream.toByteArray();
19242    }
19243
19244    @Override
19245    public void restorePermissionGrants(byte[] backup, int userId) {
19246        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19247            throw new SecurityException("Only the system may call restorePermissionGrants()");
19248        }
19249
19250        try {
19251            final XmlPullParser parser = Xml.newPullParser();
19252            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19253            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
19254                    new BlobXmlRestorer() {
19255                        @Override
19256                        public void apply(XmlPullParser parser, int userId)
19257                                throws XmlPullParserException, IOException {
19258                            synchronized (mPackages) {
19259                                processRestoredPermissionGrantsLPr(parser, userId);
19260                            }
19261                        }
19262                    } );
19263        } catch (Exception e) {
19264            if (DEBUG_BACKUP) {
19265                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19266            }
19267        }
19268    }
19269
19270    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
19271            throws IOException {
19272        serializer.startTag(null, TAG_ALL_GRANTS);
19273
19274        final int N = mSettings.mPackages.size();
19275        for (int i = 0; i < N; i++) {
19276            final PackageSetting ps = mSettings.mPackages.valueAt(i);
19277            boolean pkgGrantsKnown = false;
19278
19279            PermissionsState packagePerms = ps.getPermissionsState();
19280
19281            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
19282                final int grantFlags = state.getFlags();
19283                // only look at grants that are not system/policy fixed
19284                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
19285                    final boolean isGranted = state.isGranted();
19286                    // And only back up the user-twiddled state bits
19287                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
19288                        final String packageName = mSettings.mPackages.keyAt(i);
19289                        if (!pkgGrantsKnown) {
19290                            serializer.startTag(null, TAG_GRANT);
19291                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
19292                            pkgGrantsKnown = true;
19293                        }
19294
19295                        final boolean userSet =
19296                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
19297                        final boolean userFixed =
19298                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
19299                        final boolean revoke =
19300                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
19301
19302                        serializer.startTag(null, TAG_PERMISSION);
19303                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
19304                        if (isGranted) {
19305                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
19306                        }
19307                        if (userSet) {
19308                            serializer.attribute(null, ATTR_USER_SET, "true");
19309                        }
19310                        if (userFixed) {
19311                            serializer.attribute(null, ATTR_USER_FIXED, "true");
19312                        }
19313                        if (revoke) {
19314                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
19315                        }
19316                        serializer.endTag(null, TAG_PERMISSION);
19317                    }
19318                }
19319            }
19320
19321            if (pkgGrantsKnown) {
19322                serializer.endTag(null, TAG_GRANT);
19323            }
19324        }
19325
19326        serializer.endTag(null, TAG_ALL_GRANTS);
19327    }
19328
19329    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
19330            throws XmlPullParserException, IOException {
19331        String pkgName = null;
19332        int outerDepth = parser.getDepth();
19333        int type;
19334        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
19335                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
19336            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
19337                continue;
19338            }
19339
19340            final String tagName = parser.getName();
19341            if (tagName.equals(TAG_GRANT)) {
19342                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
19343                if (DEBUG_BACKUP) {
19344                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
19345                }
19346            } else if (tagName.equals(TAG_PERMISSION)) {
19347
19348                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
19349                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
19350
19351                int newFlagSet = 0;
19352                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
19353                    newFlagSet |= FLAG_PERMISSION_USER_SET;
19354                }
19355                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
19356                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
19357                }
19358                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
19359                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19360                }
19361                if (DEBUG_BACKUP) {
19362                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
19363                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
19364                }
19365                final PackageSetting ps = mSettings.mPackages.get(pkgName);
19366                if (ps != null) {
19367                    // Already installed so we apply the grant immediately
19368                    if (DEBUG_BACKUP) {
19369                        Slog.v(TAG, "        + already installed; applying");
19370                    }
19371                    PermissionsState perms = ps.getPermissionsState();
19372                    BasePermission bp = mSettings.mPermissions.get(permName);
19373                    if (bp != null) {
19374                        if (isGranted) {
19375                            perms.grantRuntimePermission(bp, userId);
19376                        }
19377                        if (newFlagSet != 0) {
19378                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
19379                        }
19380                    }
19381                } else {
19382                    // Need to wait for post-restore install to apply the grant
19383                    if (DEBUG_BACKUP) {
19384                        Slog.v(TAG, "        - not yet installed; saving for later");
19385                    }
19386                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
19387                            isGranted, newFlagSet, userId);
19388                }
19389            } else {
19390                PackageManagerService.reportSettingsProblem(Log.WARN,
19391                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
19392                XmlUtils.skipCurrentTag(parser);
19393            }
19394        }
19395
19396        scheduleWriteSettingsLocked();
19397        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19398    }
19399
19400    @Override
19401    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
19402            int sourceUserId, int targetUserId, int flags) {
19403        mContext.enforceCallingOrSelfPermission(
19404                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19405        int callingUid = Binder.getCallingUid();
19406        enforceOwnerRights(ownerPackage, callingUid);
19407        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19408        if (intentFilter.countActions() == 0) {
19409            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
19410            return;
19411        }
19412        synchronized (mPackages) {
19413            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
19414                    ownerPackage, targetUserId, flags);
19415            CrossProfileIntentResolver resolver =
19416                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19417            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
19418            // We have all those whose filter is equal. Now checking if the rest is equal as well.
19419            if (existing != null) {
19420                int size = existing.size();
19421                for (int i = 0; i < size; i++) {
19422                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
19423                        return;
19424                    }
19425                }
19426            }
19427            resolver.addFilter(newFilter);
19428            scheduleWritePackageRestrictionsLocked(sourceUserId);
19429        }
19430    }
19431
19432    @Override
19433    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
19434        mContext.enforceCallingOrSelfPermission(
19435                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
19436        int callingUid = Binder.getCallingUid();
19437        enforceOwnerRights(ownerPackage, callingUid);
19438        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
19439        synchronized (mPackages) {
19440            CrossProfileIntentResolver resolver =
19441                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
19442            ArraySet<CrossProfileIntentFilter> set =
19443                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
19444            for (CrossProfileIntentFilter filter : set) {
19445                if (filter.getOwnerPackage().equals(ownerPackage)) {
19446                    resolver.removeFilter(filter);
19447                }
19448            }
19449            scheduleWritePackageRestrictionsLocked(sourceUserId);
19450        }
19451    }
19452
19453    // Enforcing that callingUid is owning pkg on userId
19454    private void enforceOwnerRights(String pkg, int callingUid) {
19455        // The system owns everything.
19456        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
19457            return;
19458        }
19459        int callingUserId = UserHandle.getUserId(callingUid);
19460        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
19461        if (pi == null) {
19462            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
19463                    + callingUserId);
19464        }
19465        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
19466            throw new SecurityException("Calling uid " + callingUid
19467                    + " does not own package " + pkg);
19468        }
19469    }
19470
19471    @Override
19472    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
19473        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
19474    }
19475
19476    private Intent getHomeIntent() {
19477        Intent intent = new Intent(Intent.ACTION_MAIN);
19478        intent.addCategory(Intent.CATEGORY_HOME);
19479        intent.addCategory(Intent.CATEGORY_DEFAULT);
19480        return intent;
19481    }
19482
19483    private IntentFilter getHomeFilter() {
19484        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
19485        filter.addCategory(Intent.CATEGORY_HOME);
19486        filter.addCategory(Intent.CATEGORY_DEFAULT);
19487        return filter;
19488    }
19489
19490    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19491            int userId) {
19492        Intent intent  = getHomeIntent();
19493        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
19494                PackageManager.GET_META_DATA, userId);
19495        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
19496                true, false, false, userId);
19497
19498        allHomeCandidates.clear();
19499        if (list != null) {
19500            for (ResolveInfo ri : list) {
19501                allHomeCandidates.add(ri);
19502            }
19503        }
19504        return (preferred == null || preferred.activityInfo == null)
19505                ? null
19506                : new ComponentName(preferred.activityInfo.packageName,
19507                        preferred.activityInfo.name);
19508    }
19509
19510    @Override
19511    public void setHomeActivity(ComponentName comp, int userId) {
19512        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
19513        getHomeActivitiesAsUser(homeActivities, userId);
19514
19515        boolean found = false;
19516
19517        final int size = homeActivities.size();
19518        final ComponentName[] set = new ComponentName[size];
19519        for (int i = 0; i < size; i++) {
19520            final ResolveInfo candidate = homeActivities.get(i);
19521            final ActivityInfo info = candidate.activityInfo;
19522            final ComponentName activityName = new ComponentName(info.packageName, info.name);
19523            set[i] = activityName;
19524            if (!found && activityName.equals(comp)) {
19525                found = true;
19526            }
19527        }
19528        if (!found) {
19529            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
19530                    + userId);
19531        }
19532        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
19533                set, comp, userId);
19534    }
19535
19536    private @Nullable String getSetupWizardPackageName() {
19537        final Intent intent = new Intent(Intent.ACTION_MAIN);
19538        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
19539
19540        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19541                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19542                        | MATCH_DISABLED_COMPONENTS,
19543                UserHandle.myUserId());
19544        if (matches.size() == 1) {
19545            return matches.get(0).getComponentInfo().packageName;
19546        } else {
19547            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
19548                    + ": matches=" + matches);
19549            return null;
19550        }
19551    }
19552
19553    private @Nullable String getStorageManagerPackageName() {
19554        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
19555
19556        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
19557                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
19558                        | MATCH_DISABLED_COMPONENTS,
19559                UserHandle.myUserId());
19560        if (matches.size() == 1) {
19561            return matches.get(0).getComponentInfo().packageName;
19562        } else {
19563            Slog.e(TAG, "There should probably be exactly one storage manager; found "
19564                    + matches.size() + ": matches=" + matches);
19565            return null;
19566        }
19567    }
19568
19569    @Override
19570    public void setApplicationEnabledSetting(String appPackageName,
19571            int newState, int flags, int userId, String callingPackage) {
19572        if (!sUserManager.exists(userId)) return;
19573        if (callingPackage == null) {
19574            callingPackage = Integer.toString(Binder.getCallingUid());
19575        }
19576        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
19577    }
19578
19579    @Override
19580    public void setComponentEnabledSetting(ComponentName componentName,
19581            int newState, int flags, int userId) {
19582        if (!sUserManager.exists(userId)) return;
19583        setEnabledSetting(componentName.getPackageName(),
19584                componentName.getClassName(), newState, flags, userId, null);
19585    }
19586
19587    private void setEnabledSetting(final String packageName, String className, int newState,
19588            final int flags, int userId, String callingPackage) {
19589        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
19590              || newState == COMPONENT_ENABLED_STATE_ENABLED
19591              || newState == COMPONENT_ENABLED_STATE_DISABLED
19592              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19593              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
19594            throw new IllegalArgumentException("Invalid new component state: "
19595                    + newState);
19596        }
19597        PackageSetting pkgSetting;
19598        final int uid = Binder.getCallingUid();
19599        final int permission;
19600        if (uid == Process.SYSTEM_UID) {
19601            permission = PackageManager.PERMISSION_GRANTED;
19602        } else {
19603            permission = mContext.checkCallingOrSelfPermission(
19604                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19605        }
19606        enforceCrossUserPermission(uid, userId,
19607                false /* requireFullPermission */, true /* checkShell */, "set enabled");
19608        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19609        boolean sendNow = false;
19610        boolean isApp = (className == null);
19611        String componentName = isApp ? packageName : className;
19612        int packageUid = -1;
19613        ArrayList<String> components;
19614
19615        // writer
19616        synchronized (mPackages) {
19617            pkgSetting = mSettings.mPackages.get(packageName);
19618            if (pkgSetting == null) {
19619                if (className == null) {
19620                    throw new IllegalArgumentException("Unknown package: " + packageName);
19621                }
19622                throw new IllegalArgumentException(
19623                        "Unknown component: " + packageName + "/" + className);
19624            }
19625        }
19626
19627        // Limit who can change which apps
19628        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
19629            // Don't allow apps that don't have permission to modify other apps
19630            if (!allowedByPermission) {
19631                throw new SecurityException(
19632                        "Permission Denial: attempt to change component state from pid="
19633                        + Binder.getCallingPid()
19634                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
19635            }
19636            // Don't allow changing protected packages.
19637            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
19638                throw new SecurityException("Cannot disable a protected package: " + packageName);
19639            }
19640        }
19641
19642        synchronized (mPackages) {
19643            if (uid == Process.SHELL_UID
19644                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
19645                // Shell can only change whole packages between ENABLED and DISABLED_USER states
19646                // unless it is a test package.
19647                int oldState = pkgSetting.getEnabled(userId);
19648                if (className == null
19649                    &&
19650                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
19651                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
19652                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
19653                    &&
19654                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
19655                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
19656                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
19657                    // ok
19658                } else {
19659                    throw new SecurityException(
19660                            "Shell cannot change component state for " + packageName + "/"
19661                            + className + " to " + newState);
19662                }
19663            }
19664            if (className == null) {
19665                // We're dealing with an application/package level state change
19666                if (pkgSetting.getEnabled(userId) == newState) {
19667                    // Nothing to do
19668                    return;
19669                }
19670                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
19671                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
19672                    // Don't care about who enables an app.
19673                    callingPackage = null;
19674                }
19675                pkgSetting.setEnabled(newState, userId, callingPackage);
19676                // pkgSetting.pkg.mSetEnabled = newState;
19677            } else {
19678                // We're dealing with a component level state change
19679                // First, verify that this is a valid class name.
19680                PackageParser.Package pkg = pkgSetting.pkg;
19681                if (pkg == null || !pkg.hasComponentClassName(className)) {
19682                    if (pkg != null &&
19683                            pkg.applicationInfo.targetSdkVersion >=
19684                                    Build.VERSION_CODES.JELLY_BEAN) {
19685                        throw new IllegalArgumentException("Component class " + className
19686                                + " does not exist in " + packageName);
19687                    } else {
19688                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
19689                                + className + " does not exist in " + packageName);
19690                    }
19691                }
19692                switch (newState) {
19693                case COMPONENT_ENABLED_STATE_ENABLED:
19694                    if (!pkgSetting.enableComponentLPw(className, userId)) {
19695                        return;
19696                    }
19697                    break;
19698                case COMPONENT_ENABLED_STATE_DISABLED:
19699                    if (!pkgSetting.disableComponentLPw(className, userId)) {
19700                        return;
19701                    }
19702                    break;
19703                case COMPONENT_ENABLED_STATE_DEFAULT:
19704                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
19705                        return;
19706                    }
19707                    break;
19708                default:
19709                    Slog.e(TAG, "Invalid new component state: " + newState);
19710                    return;
19711                }
19712            }
19713            scheduleWritePackageRestrictionsLocked(userId);
19714            components = mPendingBroadcasts.get(userId, packageName);
19715            final boolean newPackage = components == null;
19716            if (newPackage) {
19717                components = new ArrayList<String>();
19718            }
19719            if (!components.contains(componentName)) {
19720                components.add(componentName);
19721            }
19722            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
19723                sendNow = true;
19724                // Purge entry from pending broadcast list if another one exists already
19725                // since we are sending one right away.
19726                mPendingBroadcasts.remove(userId, packageName);
19727            } else {
19728                if (newPackage) {
19729                    mPendingBroadcasts.put(userId, packageName, components);
19730                }
19731                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
19732                    // Schedule a message
19733                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
19734                }
19735            }
19736        }
19737
19738        long callingId = Binder.clearCallingIdentity();
19739        try {
19740            if (sendNow) {
19741                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
19742                sendPackageChangedBroadcast(packageName,
19743                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
19744            }
19745        } finally {
19746            Binder.restoreCallingIdentity(callingId);
19747        }
19748    }
19749
19750    @Override
19751    public void flushPackageRestrictionsAsUser(int userId) {
19752        if (!sUserManager.exists(userId)) {
19753            return;
19754        }
19755        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
19756                false /* checkShell */, "flushPackageRestrictions");
19757        synchronized (mPackages) {
19758            mSettings.writePackageRestrictionsLPr(userId);
19759            mDirtyUsers.remove(userId);
19760            if (mDirtyUsers.isEmpty()) {
19761                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
19762            }
19763        }
19764    }
19765
19766    private void sendPackageChangedBroadcast(String packageName,
19767            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
19768        if (DEBUG_INSTALL)
19769            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
19770                    + componentNames);
19771        Bundle extras = new Bundle(4);
19772        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
19773        String nameList[] = new String[componentNames.size()];
19774        componentNames.toArray(nameList);
19775        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
19776        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
19777        extras.putInt(Intent.EXTRA_UID, packageUid);
19778        // If this is not reporting a change of the overall package, then only send it
19779        // to registered receivers.  We don't want to launch a swath of apps for every
19780        // little component state change.
19781        final int flags = !componentNames.contains(packageName)
19782                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
19783        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
19784                new int[] {UserHandle.getUserId(packageUid)});
19785    }
19786
19787    @Override
19788    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
19789        if (!sUserManager.exists(userId)) return;
19790        final int uid = Binder.getCallingUid();
19791        final int permission = mContext.checkCallingOrSelfPermission(
19792                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
19793        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
19794        enforceCrossUserPermission(uid, userId,
19795                true /* requireFullPermission */, true /* checkShell */, "stop package");
19796        // writer
19797        synchronized (mPackages) {
19798            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
19799                    allowedByPermission, uid, userId)) {
19800                scheduleWritePackageRestrictionsLocked(userId);
19801            }
19802        }
19803    }
19804
19805    @Override
19806    public String getInstallerPackageName(String packageName) {
19807        // reader
19808        synchronized (mPackages) {
19809            return mSettings.getInstallerPackageNameLPr(packageName);
19810        }
19811    }
19812
19813    public boolean isOrphaned(String packageName) {
19814        // reader
19815        synchronized (mPackages) {
19816            return mSettings.isOrphaned(packageName);
19817        }
19818    }
19819
19820    @Override
19821    public int getApplicationEnabledSetting(String packageName, int userId) {
19822        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19823        int uid = Binder.getCallingUid();
19824        enforceCrossUserPermission(uid, userId,
19825                false /* requireFullPermission */, false /* checkShell */, "get enabled");
19826        // reader
19827        synchronized (mPackages) {
19828            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
19829        }
19830    }
19831
19832    @Override
19833    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
19834        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
19835        int uid = Binder.getCallingUid();
19836        enforceCrossUserPermission(uid, userId,
19837                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
19838        // reader
19839        synchronized (mPackages) {
19840            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
19841        }
19842    }
19843
19844    @Override
19845    public void enterSafeMode() {
19846        enforceSystemOrRoot("Only the system can request entering safe mode");
19847
19848        if (!mSystemReady) {
19849            mSafeMode = true;
19850        }
19851    }
19852
19853    @Override
19854    public void systemReady() {
19855        mSystemReady = true;
19856
19857        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
19858        // disabled after already being started.
19859        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
19860                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
19861
19862        // Read the compatibilty setting when the system is ready.
19863        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
19864                mContext.getContentResolver(),
19865                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
19866        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
19867        if (DEBUG_SETTINGS) {
19868            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
19869        }
19870
19871        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
19872
19873        synchronized (mPackages) {
19874            // Verify that all of the preferred activity components actually
19875            // exist.  It is possible for applications to be updated and at
19876            // that point remove a previously declared activity component that
19877            // had been set as a preferred activity.  We try to clean this up
19878            // the next time we encounter that preferred activity, but it is
19879            // possible for the user flow to never be able to return to that
19880            // situation so here we do a sanity check to make sure we haven't
19881            // left any junk around.
19882            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
19883            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19884                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19885                removed.clear();
19886                for (PreferredActivity pa : pir.filterSet()) {
19887                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
19888                        removed.add(pa);
19889                    }
19890                }
19891                if (removed.size() > 0) {
19892                    for (int r=0; r<removed.size(); r++) {
19893                        PreferredActivity pa = removed.get(r);
19894                        Slog.w(TAG, "Removing dangling preferred activity: "
19895                                + pa.mPref.mComponent);
19896                        pir.removeFilter(pa);
19897                    }
19898                    mSettings.writePackageRestrictionsLPr(
19899                            mSettings.mPreferredActivities.keyAt(i));
19900                }
19901            }
19902
19903            for (int userId : UserManagerService.getInstance().getUserIds()) {
19904                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
19905                    grantPermissionsUserIds = ArrayUtils.appendInt(
19906                            grantPermissionsUserIds, userId);
19907                }
19908            }
19909        }
19910        sUserManager.systemReady();
19911
19912        // If we upgraded grant all default permissions before kicking off.
19913        for (int userId : grantPermissionsUserIds) {
19914            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
19915        }
19916
19917        // If we did not grant default permissions, we preload from this the
19918        // default permission exceptions lazily to ensure we don't hit the
19919        // disk on a new user creation.
19920        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
19921            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
19922        }
19923
19924        // Kick off any messages waiting for system ready
19925        if (mPostSystemReadyMessages != null) {
19926            for (Message msg : mPostSystemReadyMessages) {
19927                msg.sendToTarget();
19928            }
19929            mPostSystemReadyMessages = null;
19930        }
19931
19932        // Watch for external volumes that come and go over time
19933        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19934        storage.registerListener(mStorageListener);
19935
19936        mInstallerService.systemReady();
19937        mPackageDexOptimizer.systemReady();
19938
19939        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
19940                StorageManagerInternal.class);
19941        StorageManagerInternal.addExternalStoragePolicy(
19942                new StorageManagerInternal.ExternalStorageMountPolicy() {
19943            @Override
19944            public int getMountMode(int uid, String packageName) {
19945                if (Process.isIsolated(uid)) {
19946                    return Zygote.MOUNT_EXTERNAL_NONE;
19947                }
19948                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
19949                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
19950                }
19951                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
19952                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
19953                }
19954                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
19955                    return Zygote.MOUNT_EXTERNAL_READ;
19956                }
19957                return Zygote.MOUNT_EXTERNAL_WRITE;
19958            }
19959
19960            @Override
19961            public boolean hasExternalStorage(int uid, String packageName) {
19962                return true;
19963            }
19964        });
19965
19966        // Now that we're mostly running, clean up stale users and apps
19967        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
19968        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
19969    }
19970
19971    @Override
19972    public boolean isSafeMode() {
19973        return mSafeMode;
19974    }
19975
19976    @Override
19977    public boolean hasSystemUidErrors() {
19978        return mHasSystemUidErrors;
19979    }
19980
19981    static String arrayToString(int[] array) {
19982        StringBuffer buf = new StringBuffer(128);
19983        buf.append('[');
19984        if (array != null) {
19985            for (int i=0; i<array.length; i++) {
19986                if (i > 0) buf.append(", ");
19987                buf.append(array[i]);
19988            }
19989        }
19990        buf.append(']');
19991        return buf.toString();
19992    }
19993
19994    static class DumpState {
19995        public static final int DUMP_LIBS = 1 << 0;
19996        public static final int DUMP_FEATURES = 1 << 1;
19997        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
19998        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
19999        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
20000        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
20001        public static final int DUMP_PERMISSIONS = 1 << 6;
20002        public static final int DUMP_PACKAGES = 1 << 7;
20003        public static final int DUMP_SHARED_USERS = 1 << 8;
20004        public static final int DUMP_MESSAGES = 1 << 9;
20005        public static final int DUMP_PROVIDERS = 1 << 10;
20006        public static final int DUMP_VERIFIERS = 1 << 11;
20007        public static final int DUMP_PREFERRED = 1 << 12;
20008        public static final int DUMP_PREFERRED_XML = 1 << 13;
20009        public static final int DUMP_KEYSETS = 1 << 14;
20010        public static final int DUMP_VERSION = 1 << 15;
20011        public static final int DUMP_INSTALLS = 1 << 16;
20012        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
20013        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
20014        public static final int DUMP_FROZEN = 1 << 19;
20015        public static final int DUMP_DEXOPT = 1 << 20;
20016        public static final int DUMP_COMPILER_STATS = 1 << 21;
20017
20018        public static final int OPTION_SHOW_FILTERS = 1 << 0;
20019
20020        private int mTypes;
20021
20022        private int mOptions;
20023
20024        private boolean mTitlePrinted;
20025
20026        private SharedUserSetting mSharedUser;
20027
20028        public boolean isDumping(int type) {
20029            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
20030                return true;
20031            }
20032
20033            return (mTypes & type) != 0;
20034        }
20035
20036        public void setDump(int type) {
20037            mTypes |= type;
20038        }
20039
20040        public boolean isOptionEnabled(int option) {
20041            return (mOptions & option) != 0;
20042        }
20043
20044        public void setOptionEnabled(int option) {
20045            mOptions |= option;
20046        }
20047
20048        public boolean onTitlePrinted() {
20049            final boolean printed = mTitlePrinted;
20050            mTitlePrinted = true;
20051            return printed;
20052        }
20053
20054        public boolean getTitlePrinted() {
20055            return mTitlePrinted;
20056        }
20057
20058        public void setTitlePrinted(boolean enabled) {
20059            mTitlePrinted = enabled;
20060        }
20061
20062        public SharedUserSetting getSharedUser() {
20063            return mSharedUser;
20064        }
20065
20066        public void setSharedUser(SharedUserSetting user) {
20067            mSharedUser = user;
20068        }
20069    }
20070
20071    @Override
20072    public void onShellCommand(FileDescriptor in, FileDescriptor out,
20073            FileDescriptor err, String[] args, ShellCallback callback,
20074            ResultReceiver resultReceiver) {
20075        (new PackageManagerShellCommand(this)).exec(
20076                this, in, out, err, args, callback, resultReceiver);
20077    }
20078
20079    @Override
20080    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
20081        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
20082                != PackageManager.PERMISSION_GRANTED) {
20083            pw.println("Permission Denial: can't dump ActivityManager from from pid="
20084                    + Binder.getCallingPid()
20085                    + ", uid=" + Binder.getCallingUid()
20086                    + " without permission "
20087                    + android.Manifest.permission.DUMP);
20088            return;
20089        }
20090
20091        DumpState dumpState = new DumpState();
20092        boolean fullPreferred = false;
20093        boolean checkin = false;
20094
20095        String packageName = null;
20096        ArraySet<String> permissionNames = null;
20097
20098        int opti = 0;
20099        while (opti < args.length) {
20100            String opt = args[opti];
20101            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
20102                break;
20103            }
20104            opti++;
20105
20106            if ("-a".equals(opt)) {
20107                // Right now we only know how to print all.
20108            } else if ("-h".equals(opt)) {
20109                pw.println("Package manager dump options:");
20110                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
20111                pw.println("    --checkin: dump for a checkin");
20112                pw.println("    -f: print details of intent filters");
20113                pw.println("    -h: print this help");
20114                pw.println("  cmd may be one of:");
20115                pw.println("    l[ibraries]: list known shared libraries");
20116                pw.println("    f[eatures]: list device features");
20117                pw.println("    k[eysets]: print known keysets");
20118                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
20119                pw.println("    perm[issions]: dump permissions");
20120                pw.println("    permission [name ...]: dump declaration and use of given permission");
20121                pw.println("    pref[erred]: print preferred package settings");
20122                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
20123                pw.println("    prov[iders]: dump content providers");
20124                pw.println("    p[ackages]: dump installed packages");
20125                pw.println("    s[hared-users]: dump shared user IDs");
20126                pw.println("    m[essages]: print collected runtime messages");
20127                pw.println("    v[erifiers]: print package verifier info");
20128                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
20129                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
20130                pw.println("    version: print database version info");
20131                pw.println("    write: write current settings now");
20132                pw.println("    installs: details about install sessions");
20133                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
20134                pw.println("    dexopt: dump dexopt state");
20135                pw.println("    compiler-stats: dump compiler statistics");
20136                pw.println("    <package.name>: info about given package");
20137                return;
20138            } else if ("--checkin".equals(opt)) {
20139                checkin = true;
20140            } else if ("-f".equals(opt)) {
20141                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20142            } else {
20143                pw.println("Unknown argument: " + opt + "; use -h for help");
20144            }
20145        }
20146
20147        // Is the caller requesting to dump a particular piece of data?
20148        if (opti < args.length) {
20149            String cmd = args[opti];
20150            opti++;
20151            // Is this a package name?
20152            if ("android".equals(cmd) || cmd.contains(".")) {
20153                packageName = cmd;
20154                // When dumping a single package, we always dump all of its
20155                // filter information since the amount of data will be reasonable.
20156                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
20157            } else if ("check-permission".equals(cmd)) {
20158                if (opti >= args.length) {
20159                    pw.println("Error: check-permission missing permission argument");
20160                    return;
20161                }
20162                String perm = args[opti];
20163                opti++;
20164                if (opti >= args.length) {
20165                    pw.println("Error: check-permission missing package argument");
20166                    return;
20167                }
20168
20169                String pkg = args[opti];
20170                opti++;
20171                int user = UserHandle.getUserId(Binder.getCallingUid());
20172                if (opti < args.length) {
20173                    try {
20174                        user = Integer.parseInt(args[opti]);
20175                    } catch (NumberFormatException e) {
20176                        pw.println("Error: check-permission user argument is not a number: "
20177                                + args[opti]);
20178                        return;
20179                    }
20180                }
20181
20182                // Normalize package name to handle renamed packages and static libs
20183                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
20184
20185                pw.println(checkPermission(perm, pkg, user));
20186                return;
20187            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
20188                dumpState.setDump(DumpState.DUMP_LIBS);
20189            } else if ("f".equals(cmd) || "features".equals(cmd)) {
20190                dumpState.setDump(DumpState.DUMP_FEATURES);
20191            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
20192                if (opti >= args.length) {
20193                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
20194                            | DumpState.DUMP_SERVICE_RESOLVERS
20195                            | DumpState.DUMP_RECEIVER_RESOLVERS
20196                            | DumpState.DUMP_CONTENT_RESOLVERS);
20197                } else {
20198                    while (opti < args.length) {
20199                        String name = args[opti];
20200                        if ("a".equals(name) || "activity".equals(name)) {
20201                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
20202                        } else if ("s".equals(name) || "service".equals(name)) {
20203                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
20204                        } else if ("r".equals(name) || "receiver".equals(name)) {
20205                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
20206                        } else if ("c".equals(name) || "content".equals(name)) {
20207                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
20208                        } else {
20209                            pw.println("Error: unknown resolver table type: " + name);
20210                            return;
20211                        }
20212                        opti++;
20213                    }
20214                }
20215            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
20216                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
20217            } else if ("permission".equals(cmd)) {
20218                if (opti >= args.length) {
20219                    pw.println("Error: permission requires permission name");
20220                    return;
20221                }
20222                permissionNames = new ArraySet<>();
20223                while (opti < args.length) {
20224                    permissionNames.add(args[opti]);
20225                    opti++;
20226                }
20227                dumpState.setDump(DumpState.DUMP_PERMISSIONS
20228                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
20229            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
20230                dumpState.setDump(DumpState.DUMP_PREFERRED);
20231            } else if ("preferred-xml".equals(cmd)) {
20232                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
20233                if (opti < args.length && "--full".equals(args[opti])) {
20234                    fullPreferred = true;
20235                    opti++;
20236                }
20237            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
20238                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
20239            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
20240                dumpState.setDump(DumpState.DUMP_PACKAGES);
20241            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
20242                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
20243            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
20244                dumpState.setDump(DumpState.DUMP_PROVIDERS);
20245            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
20246                dumpState.setDump(DumpState.DUMP_MESSAGES);
20247            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
20248                dumpState.setDump(DumpState.DUMP_VERIFIERS);
20249            } else if ("i".equals(cmd) || "ifv".equals(cmd)
20250                    || "intent-filter-verifiers".equals(cmd)) {
20251                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
20252            } else if ("version".equals(cmd)) {
20253                dumpState.setDump(DumpState.DUMP_VERSION);
20254            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
20255                dumpState.setDump(DumpState.DUMP_KEYSETS);
20256            } else if ("installs".equals(cmd)) {
20257                dumpState.setDump(DumpState.DUMP_INSTALLS);
20258            } else if ("frozen".equals(cmd)) {
20259                dumpState.setDump(DumpState.DUMP_FROZEN);
20260            } else if ("dexopt".equals(cmd)) {
20261                dumpState.setDump(DumpState.DUMP_DEXOPT);
20262            } else if ("compiler-stats".equals(cmd)) {
20263                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
20264            } else if ("write".equals(cmd)) {
20265                synchronized (mPackages) {
20266                    mSettings.writeLPr();
20267                    pw.println("Settings written.");
20268                    return;
20269                }
20270            }
20271        }
20272
20273        if (checkin) {
20274            pw.println("vers,1");
20275        }
20276
20277        // reader
20278        synchronized (mPackages) {
20279            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
20280                if (!checkin) {
20281                    if (dumpState.onTitlePrinted())
20282                        pw.println();
20283                    pw.println("Database versions:");
20284                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
20285                }
20286            }
20287
20288            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
20289                if (!checkin) {
20290                    if (dumpState.onTitlePrinted())
20291                        pw.println();
20292                    pw.println("Verifiers:");
20293                    pw.print("  Required: ");
20294                    pw.print(mRequiredVerifierPackage);
20295                    pw.print(" (uid=");
20296                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20297                            UserHandle.USER_SYSTEM));
20298                    pw.println(")");
20299                } else if (mRequiredVerifierPackage != null) {
20300                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
20301                    pw.print(",");
20302                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
20303                            UserHandle.USER_SYSTEM));
20304                }
20305            }
20306
20307            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
20308                    packageName == null) {
20309                if (mIntentFilterVerifierComponent != null) {
20310                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
20311                    if (!checkin) {
20312                        if (dumpState.onTitlePrinted())
20313                            pw.println();
20314                        pw.println("Intent Filter Verifier:");
20315                        pw.print("  Using: ");
20316                        pw.print(verifierPackageName);
20317                        pw.print(" (uid=");
20318                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20319                                UserHandle.USER_SYSTEM));
20320                        pw.println(")");
20321                    } else if (verifierPackageName != null) {
20322                        pw.print("ifv,"); pw.print(verifierPackageName);
20323                        pw.print(",");
20324                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
20325                                UserHandle.USER_SYSTEM));
20326                    }
20327                } else {
20328                    pw.println();
20329                    pw.println("No Intent Filter Verifier available!");
20330                }
20331            }
20332
20333            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
20334                boolean printedHeader = false;
20335                final Iterator<String> it = mSharedLibraries.keySet().iterator();
20336                while (it.hasNext()) {
20337                    String libName = it.next();
20338                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
20339                    if (versionedLib == null) {
20340                        continue;
20341                    }
20342                    final int versionCount = versionedLib.size();
20343                    for (int i = 0; i < versionCount; i++) {
20344                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
20345                        if (!checkin) {
20346                            if (!printedHeader) {
20347                                if (dumpState.onTitlePrinted())
20348                                    pw.println();
20349                                pw.println("Libraries:");
20350                                printedHeader = true;
20351                            }
20352                            pw.print("  ");
20353                        } else {
20354                            pw.print("lib,");
20355                        }
20356                        pw.print(libEntry.info.getName());
20357                        if (libEntry.info.isStatic()) {
20358                            pw.print(" version=" + libEntry.info.getVersion());
20359                        }
20360                        if (!checkin) {
20361                            pw.print(" -> ");
20362                        }
20363                        if (libEntry.path != null) {
20364                            pw.print(" (jar) ");
20365                            pw.print(libEntry.path);
20366                        } else {
20367                            pw.print(" (apk) ");
20368                            pw.print(libEntry.apk);
20369                        }
20370                        pw.println();
20371                    }
20372                }
20373            }
20374
20375            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
20376                if (dumpState.onTitlePrinted())
20377                    pw.println();
20378                if (!checkin) {
20379                    pw.println("Features:");
20380                }
20381
20382                for (FeatureInfo feat : mAvailableFeatures.values()) {
20383                    if (checkin) {
20384                        pw.print("feat,");
20385                        pw.print(feat.name);
20386                        pw.print(",");
20387                        pw.println(feat.version);
20388                    } else {
20389                        pw.print("  ");
20390                        pw.print(feat.name);
20391                        if (feat.version > 0) {
20392                            pw.print(" version=");
20393                            pw.print(feat.version);
20394                        }
20395                        pw.println();
20396                    }
20397                }
20398            }
20399
20400            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
20401                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
20402                        : "Activity Resolver Table:", "  ", packageName,
20403                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20404                    dumpState.setTitlePrinted(true);
20405                }
20406            }
20407            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
20408                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
20409                        : "Receiver Resolver Table:", "  ", packageName,
20410                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20411                    dumpState.setTitlePrinted(true);
20412                }
20413            }
20414            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
20415                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
20416                        : "Service Resolver Table:", "  ", packageName,
20417                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20418                    dumpState.setTitlePrinted(true);
20419                }
20420            }
20421            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
20422                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
20423                        : "Provider Resolver Table:", "  ", packageName,
20424                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
20425                    dumpState.setTitlePrinted(true);
20426                }
20427            }
20428
20429            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
20430                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20431                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20432                    int user = mSettings.mPreferredActivities.keyAt(i);
20433                    if (pir.dump(pw,
20434                            dumpState.getTitlePrinted()
20435                                ? "\nPreferred Activities User " + user + ":"
20436                                : "Preferred Activities User " + user + ":", "  ",
20437                            packageName, true, false)) {
20438                        dumpState.setTitlePrinted(true);
20439                    }
20440                }
20441            }
20442
20443            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
20444                pw.flush();
20445                FileOutputStream fout = new FileOutputStream(fd);
20446                BufferedOutputStream str = new BufferedOutputStream(fout);
20447                XmlSerializer serializer = new FastXmlSerializer();
20448                try {
20449                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
20450                    serializer.startDocument(null, true);
20451                    serializer.setFeature(
20452                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
20453                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
20454                    serializer.endDocument();
20455                    serializer.flush();
20456                } catch (IllegalArgumentException e) {
20457                    pw.println("Failed writing: " + e);
20458                } catch (IllegalStateException e) {
20459                    pw.println("Failed writing: " + e);
20460                } catch (IOException e) {
20461                    pw.println("Failed writing: " + e);
20462                }
20463            }
20464
20465            if (!checkin
20466                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
20467                    && packageName == null) {
20468                pw.println();
20469                int count = mSettings.mPackages.size();
20470                if (count == 0) {
20471                    pw.println("No applications!");
20472                    pw.println();
20473                } else {
20474                    final String prefix = "  ";
20475                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
20476                    if (allPackageSettings.size() == 0) {
20477                        pw.println("No domain preferred apps!");
20478                        pw.println();
20479                    } else {
20480                        pw.println("App verification status:");
20481                        pw.println();
20482                        count = 0;
20483                        for (PackageSetting ps : allPackageSettings) {
20484                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
20485                            if (ivi == null || ivi.getPackageName() == null) continue;
20486                            pw.println(prefix + "Package: " + ivi.getPackageName());
20487                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
20488                            pw.println(prefix + "Status:  " + ivi.getStatusString());
20489                            pw.println();
20490                            count++;
20491                        }
20492                        if (count == 0) {
20493                            pw.println(prefix + "No app verification established.");
20494                            pw.println();
20495                        }
20496                        for (int userId : sUserManager.getUserIds()) {
20497                            pw.println("App linkages for user " + userId + ":");
20498                            pw.println();
20499                            count = 0;
20500                            for (PackageSetting ps : allPackageSettings) {
20501                                final long status = ps.getDomainVerificationStatusForUser(userId);
20502                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
20503                                        && !DEBUG_DOMAIN_VERIFICATION) {
20504                                    continue;
20505                                }
20506                                pw.println(prefix + "Package: " + ps.name);
20507                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
20508                                String statusStr = IntentFilterVerificationInfo.
20509                                        getStatusStringFromValue(status);
20510                                pw.println(prefix + "Status:  " + statusStr);
20511                                pw.println();
20512                                count++;
20513                            }
20514                            if (count == 0) {
20515                                pw.println(prefix + "No configured app linkages.");
20516                                pw.println();
20517                            }
20518                        }
20519                    }
20520                }
20521            }
20522
20523            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
20524                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
20525                if (packageName == null && permissionNames == null) {
20526                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
20527                        if (iperm == 0) {
20528                            if (dumpState.onTitlePrinted())
20529                                pw.println();
20530                            pw.println("AppOp Permissions:");
20531                        }
20532                        pw.print("  AppOp Permission ");
20533                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
20534                        pw.println(":");
20535                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
20536                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
20537                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
20538                        }
20539                    }
20540                }
20541            }
20542
20543            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
20544                boolean printedSomething = false;
20545                for (PackageParser.Provider p : mProviders.mProviders.values()) {
20546                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20547                        continue;
20548                    }
20549                    if (!printedSomething) {
20550                        if (dumpState.onTitlePrinted())
20551                            pw.println();
20552                        pw.println("Registered ContentProviders:");
20553                        printedSomething = true;
20554                    }
20555                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
20556                    pw.print("    "); pw.println(p.toString());
20557                }
20558                printedSomething = false;
20559                for (Map.Entry<String, PackageParser.Provider> entry :
20560                        mProvidersByAuthority.entrySet()) {
20561                    PackageParser.Provider p = entry.getValue();
20562                    if (packageName != null && !packageName.equals(p.info.packageName)) {
20563                        continue;
20564                    }
20565                    if (!printedSomething) {
20566                        if (dumpState.onTitlePrinted())
20567                            pw.println();
20568                        pw.println("ContentProvider Authorities:");
20569                        printedSomething = true;
20570                    }
20571                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
20572                    pw.print("    "); pw.println(p.toString());
20573                    if (p.info != null && p.info.applicationInfo != null) {
20574                        final String appInfo = p.info.applicationInfo.toString();
20575                        pw.print("      applicationInfo="); pw.println(appInfo);
20576                    }
20577                }
20578            }
20579
20580            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
20581                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
20582            }
20583
20584            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
20585                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
20586            }
20587
20588            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
20589                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
20590            }
20591
20592            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
20593                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
20594            }
20595
20596            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
20597                // XXX should handle packageName != null by dumping only install data that
20598                // the given package is involved with.
20599                if (dumpState.onTitlePrinted()) pw.println();
20600                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
20601            }
20602
20603            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
20604                // XXX should handle packageName != null by dumping only install data that
20605                // the given package is involved with.
20606                if (dumpState.onTitlePrinted()) pw.println();
20607
20608                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20609                ipw.println();
20610                ipw.println("Frozen packages:");
20611                ipw.increaseIndent();
20612                if (mFrozenPackages.size() == 0) {
20613                    ipw.println("(none)");
20614                } else {
20615                    for (int i = 0; i < mFrozenPackages.size(); i++) {
20616                        ipw.println(mFrozenPackages.valueAt(i));
20617                    }
20618                }
20619                ipw.decreaseIndent();
20620            }
20621
20622            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
20623                if (dumpState.onTitlePrinted()) pw.println();
20624                dumpDexoptStateLPr(pw, packageName);
20625            }
20626
20627            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
20628                if (dumpState.onTitlePrinted()) pw.println();
20629                dumpCompilerStatsLPr(pw, packageName);
20630            }
20631
20632            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
20633                if (dumpState.onTitlePrinted()) pw.println();
20634                mSettings.dumpReadMessagesLPr(pw, dumpState);
20635
20636                pw.println();
20637                pw.println("Package warning messages:");
20638                BufferedReader in = null;
20639                String line = null;
20640                try {
20641                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20642                    while ((line = in.readLine()) != null) {
20643                        if (line.contains("ignored: updated version")) continue;
20644                        pw.println(line);
20645                    }
20646                } catch (IOException ignored) {
20647                } finally {
20648                    IoUtils.closeQuietly(in);
20649                }
20650            }
20651
20652            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
20653                BufferedReader in = null;
20654                String line = null;
20655                try {
20656                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
20657                    while ((line = in.readLine()) != null) {
20658                        if (line.contains("ignored: updated version")) continue;
20659                        pw.print("msg,");
20660                        pw.println(line);
20661                    }
20662                } catch (IOException ignored) {
20663                } finally {
20664                    IoUtils.closeQuietly(in);
20665                }
20666            }
20667        }
20668    }
20669
20670    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
20671        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20672        ipw.println();
20673        ipw.println("Dexopt state:");
20674        ipw.increaseIndent();
20675        Collection<PackageParser.Package> packages = null;
20676        if (packageName != null) {
20677            PackageParser.Package targetPackage = mPackages.get(packageName);
20678            if (targetPackage != null) {
20679                packages = Collections.singletonList(targetPackage);
20680            } else {
20681                ipw.println("Unable to find package: " + packageName);
20682                return;
20683            }
20684        } else {
20685            packages = mPackages.values();
20686        }
20687
20688        for (PackageParser.Package pkg : packages) {
20689            ipw.println("[" + pkg.packageName + "]");
20690            ipw.increaseIndent();
20691            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
20692            ipw.decreaseIndent();
20693        }
20694    }
20695
20696    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
20697        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
20698        ipw.println();
20699        ipw.println("Compiler stats:");
20700        ipw.increaseIndent();
20701        Collection<PackageParser.Package> packages = null;
20702        if (packageName != null) {
20703            PackageParser.Package targetPackage = mPackages.get(packageName);
20704            if (targetPackage != null) {
20705                packages = Collections.singletonList(targetPackage);
20706            } else {
20707                ipw.println("Unable to find package: " + packageName);
20708                return;
20709            }
20710        } else {
20711            packages = mPackages.values();
20712        }
20713
20714        for (PackageParser.Package pkg : packages) {
20715            ipw.println("[" + pkg.packageName + "]");
20716            ipw.increaseIndent();
20717
20718            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
20719            if (stats == null) {
20720                ipw.println("(No recorded stats)");
20721            } else {
20722                stats.dump(ipw);
20723            }
20724            ipw.decreaseIndent();
20725        }
20726    }
20727
20728    private String dumpDomainString(String packageName) {
20729        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
20730                .getList();
20731        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
20732
20733        ArraySet<String> result = new ArraySet<>();
20734        if (iviList.size() > 0) {
20735            for (IntentFilterVerificationInfo ivi : iviList) {
20736                for (String host : ivi.getDomains()) {
20737                    result.add(host);
20738                }
20739            }
20740        }
20741        if (filters != null && filters.size() > 0) {
20742            for (IntentFilter filter : filters) {
20743                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
20744                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
20745                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
20746                    result.addAll(filter.getHostsList());
20747                }
20748            }
20749        }
20750
20751        StringBuilder sb = new StringBuilder(result.size() * 16);
20752        for (String domain : result) {
20753            if (sb.length() > 0) sb.append(" ");
20754            sb.append(domain);
20755        }
20756        return sb.toString();
20757    }
20758
20759    // ------- apps on sdcard specific code -------
20760    static final boolean DEBUG_SD_INSTALL = false;
20761
20762    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
20763
20764    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
20765
20766    private boolean mMediaMounted = false;
20767
20768    static String getEncryptKey() {
20769        try {
20770            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
20771                    SD_ENCRYPTION_KEYSTORE_NAME);
20772            if (sdEncKey == null) {
20773                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
20774                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
20775                if (sdEncKey == null) {
20776                    Slog.e(TAG, "Failed to create encryption keys");
20777                    return null;
20778                }
20779            }
20780            return sdEncKey;
20781        } catch (NoSuchAlgorithmException nsae) {
20782            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
20783            return null;
20784        } catch (IOException ioe) {
20785            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
20786            return null;
20787        }
20788    }
20789
20790    /*
20791     * Update media status on PackageManager.
20792     */
20793    @Override
20794    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
20795        int callingUid = Binder.getCallingUid();
20796        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
20797            throw new SecurityException("Media status can only be updated by the system");
20798        }
20799        // reader; this apparently protects mMediaMounted, but should probably
20800        // be a different lock in that case.
20801        synchronized (mPackages) {
20802            Log.i(TAG, "Updating external media status from "
20803                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
20804                    + (mediaStatus ? "mounted" : "unmounted"));
20805            if (DEBUG_SD_INSTALL)
20806                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
20807                        + ", mMediaMounted=" + mMediaMounted);
20808            if (mediaStatus == mMediaMounted) {
20809                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
20810                        : 0, -1);
20811                mHandler.sendMessage(msg);
20812                return;
20813            }
20814            mMediaMounted = mediaStatus;
20815        }
20816        // Queue up an async operation since the package installation may take a
20817        // little while.
20818        mHandler.post(new Runnable() {
20819            public void run() {
20820                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
20821            }
20822        });
20823    }
20824
20825    /**
20826     * Called by StorageManagerService when the initial ASECs to scan are available.
20827     * Should block until all the ASEC containers are finished being scanned.
20828     */
20829    public void scanAvailableAsecs() {
20830        updateExternalMediaStatusInner(true, false, false);
20831    }
20832
20833    /*
20834     * Collect information of applications on external media, map them against
20835     * existing containers and update information based on current mount status.
20836     * Please note that we always have to report status if reportStatus has been
20837     * set to true especially when unloading packages.
20838     */
20839    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
20840            boolean externalStorage) {
20841        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
20842        int[] uidArr = EmptyArray.INT;
20843
20844        final String[] list = PackageHelper.getSecureContainerList();
20845        if (ArrayUtils.isEmpty(list)) {
20846            Log.i(TAG, "No secure containers found");
20847        } else {
20848            // Process list of secure containers and categorize them
20849            // as active or stale based on their package internal state.
20850
20851            // reader
20852            synchronized (mPackages) {
20853                for (String cid : list) {
20854                    // Leave stages untouched for now; installer service owns them
20855                    if (PackageInstallerService.isStageName(cid)) continue;
20856
20857                    if (DEBUG_SD_INSTALL)
20858                        Log.i(TAG, "Processing container " + cid);
20859                    String pkgName = getAsecPackageName(cid);
20860                    if (pkgName == null) {
20861                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
20862                        continue;
20863                    }
20864                    if (DEBUG_SD_INSTALL)
20865                        Log.i(TAG, "Looking for pkg : " + pkgName);
20866
20867                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
20868                    if (ps == null) {
20869                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
20870                        continue;
20871                    }
20872
20873                    /*
20874                     * Skip packages that are not external if we're unmounting
20875                     * external storage.
20876                     */
20877                    if (externalStorage && !isMounted && !isExternal(ps)) {
20878                        continue;
20879                    }
20880
20881                    final AsecInstallArgs args = new AsecInstallArgs(cid,
20882                            getAppDexInstructionSets(ps), ps.isForwardLocked());
20883                    // The package status is changed only if the code path
20884                    // matches between settings and the container id.
20885                    if (ps.codePathString != null
20886                            && ps.codePathString.startsWith(args.getCodePath())) {
20887                        if (DEBUG_SD_INSTALL) {
20888                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
20889                                    + " at code path: " + ps.codePathString);
20890                        }
20891
20892                        // We do have a valid package installed on sdcard
20893                        processCids.put(args, ps.codePathString);
20894                        final int uid = ps.appId;
20895                        if (uid != -1) {
20896                            uidArr = ArrayUtils.appendInt(uidArr, uid);
20897                        }
20898                    } else {
20899                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
20900                                + ps.codePathString);
20901                    }
20902                }
20903            }
20904
20905            Arrays.sort(uidArr);
20906        }
20907
20908        // Process packages with valid entries.
20909        if (isMounted) {
20910            if (DEBUG_SD_INSTALL)
20911                Log.i(TAG, "Loading packages");
20912            loadMediaPackages(processCids, uidArr, externalStorage);
20913            startCleaningPackages();
20914            mInstallerService.onSecureContainersAvailable();
20915        } else {
20916            if (DEBUG_SD_INSTALL)
20917                Log.i(TAG, "Unloading packages");
20918            unloadMediaPackages(processCids, uidArr, reportStatus);
20919        }
20920    }
20921
20922    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20923            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
20924        final int size = infos.size();
20925        final String[] packageNames = new String[size];
20926        final int[] packageUids = new int[size];
20927        for (int i = 0; i < size; i++) {
20928            final ApplicationInfo info = infos.get(i);
20929            packageNames[i] = info.packageName;
20930            packageUids[i] = info.uid;
20931        }
20932        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
20933                finishedReceiver);
20934    }
20935
20936    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20937            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
20938        sendResourcesChangedBroadcast(mediaStatus, replacing,
20939                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
20940    }
20941
20942    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
20943            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
20944        int size = pkgList.length;
20945        if (size > 0) {
20946            // Send broadcasts here
20947            Bundle extras = new Bundle();
20948            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
20949            if (uidArr != null) {
20950                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
20951            }
20952            if (replacing) {
20953                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
20954            }
20955            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
20956                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
20957            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
20958        }
20959    }
20960
20961   /*
20962     * Look at potentially valid container ids from processCids If package
20963     * information doesn't match the one on record or package scanning fails,
20964     * the cid is added to list of removeCids. We currently don't delete stale
20965     * containers.
20966     */
20967    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
20968            boolean externalStorage) {
20969        ArrayList<String> pkgList = new ArrayList<String>();
20970        Set<AsecInstallArgs> keys = processCids.keySet();
20971
20972        for (AsecInstallArgs args : keys) {
20973            String codePath = processCids.get(args);
20974            if (DEBUG_SD_INSTALL)
20975                Log.i(TAG, "Loading container : " + args.cid);
20976            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
20977            try {
20978                // Make sure there are no container errors first.
20979                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
20980                    Slog.e(TAG, "Failed to mount cid : " + args.cid
20981                            + " when installing from sdcard");
20982                    continue;
20983                }
20984                // Check code path here.
20985                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
20986                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
20987                            + " does not match one in settings " + codePath);
20988                    continue;
20989                }
20990                // Parse package
20991                int parseFlags = mDefParseFlags;
20992                if (args.isExternalAsec()) {
20993                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
20994                }
20995                if (args.isFwdLocked()) {
20996                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
20997                }
20998
20999                synchronized (mInstallLock) {
21000                    PackageParser.Package pkg = null;
21001                    try {
21002                        // Sadly we don't know the package name yet to freeze it
21003                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
21004                                SCAN_IGNORE_FROZEN, 0, null);
21005                    } catch (PackageManagerException e) {
21006                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
21007                    }
21008                    // Scan the package
21009                    if (pkg != null) {
21010                        /*
21011                         * TODO why is the lock being held? doPostInstall is
21012                         * called in other places without the lock. This needs
21013                         * to be straightened out.
21014                         */
21015                        // writer
21016                        synchronized (mPackages) {
21017                            retCode = PackageManager.INSTALL_SUCCEEDED;
21018                            pkgList.add(pkg.packageName);
21019                            // Post process args
21020                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
21021                                    pkg.applicationInfo.uid);
21022                        }
21023                    } else {
21024                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
21025                    }
21026                }
21027
21028            } finally {
21029                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
21030                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
21031                }
21032            }
21033        }
21034        // writer
21035        synchronized (mPackages) {
21036            // If the platform SDK has changed since the last time we booted,
21037            // we need to re-grant app permission to catch any new ones that
21038            // appear. This is really a hack, and means that apps can in some
21039            // cases get permissions that the user didn't initially explicitly
21040            // allow... it would be nice to have some better way to handle
21041            // this situation.
21042            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
21043                    : mSettings.getInternalVersion();
21044            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
21045                    : StorageManager.UUID_PRIVATE_INTERNAL;
21046
21047            int updateFlags = UPDATE_PERMISSIONS_ALL;
21048            if (ver.sdkVersion != mSdkVersion) {
21049                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21050                        + mSdkVersion + "; regranting permissions for external");
21051                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21052            }
21053            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21054
21055            // Yay, everything is now upgraded
21056            ver.forceCurrent();
21057
21058            // can downgrade to reader
21059            // Persist settings
21060            mSettings.writeLPr();
21061        }
21062        // Send a broadcast to let everyone know we are done processing
21063        if (pkgList.size() > 0) {
21064            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
21065        }
21066    }
21067
21068   /*
21069     * Utility method to unload a list of specified containers
21070     */
21071    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
21072        // Just unmount all valid containers.
21073        for (AsecInstallArgs arg : cidArgs) {
21074            synchronized (mInstallLock) {
21075                arg.doPostDeleteLI(false);
21076           }
21077       }
21078   }
21079
21080    /*
21081     * Unload packages mounted on external media. This involves deleting package
21082     * data from internal structures, sending broadcasts about disabled packages,
21083     * gc'ing to free up references, unmounting all secure containers
21084     * corresponding to packages on external media, and posting a
21085     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
21086     * that we always have to post this message if status has been requested no
21087     * matter what.
21088     */
21089    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
21090            final boolean reportStatus) {
21091        if (DEBUG_SD_INSTALL)
21092            Log.i(TAG, "unloading media packages");
21093        ArrayList<String> pkgList = new ArrayList<String>();
21094        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
21095        final Set<AsecInstallArgs> keys = processCids.keySet();
21096        for (AsecInstallArgs args : keys) {
21097            String pkgName = args.getPackageName();
21098            if (DEBUG_SD_INSTALL)
21099                Log.i(TAG, "Trying to unload pkg : " + pkgName);
21100            // Delete package internally
21101            PackageRemovedInfo outInfo = new PackageRemovedInfo();
21102            synchronized (mInstallLock) {
21103                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21104                final boolean res;
21105                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
21106                        "unloadMediaPackages")) {
21107                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
21108                            null);
21109                }
21110                if (res) {
21111                    pkgList.add(pkgName);
21112                } else {
21113                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
21114                    failedList.add(args);
21115                }
21116            }
21117        }
21118
21119        // reader
21120        synchronized (mPackages) {
21121            // We didn't update the settings after removing each package;
21122            // write them now for all packages.
21123            mSettings.writeLPr();
21124        }
21125
21126        // We have to absolutely send UPDATED_MEDIA_STATUS only
21127        // after confirming that all the receivers processed the ordered
21128        // broadcast when packages get disabled, force a gc to clean things up.
21129        // and unload all the containers.
21130        if (pkgList.size() > 0) {
21131            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
21132                    new IIntentReceiver.Stub() {
21133                public void performReceive(Intent intent, int resultCode, String data,
21134                        Bundle extras, boolean ordered, boolean sticky,
21135                        int sendingUser) throws RemoteException {
21136                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
21137                            reportStatus ? 1 : 0, 1, keys);
21138                    mHandler.sendMessage(msg);
21139                }
21140            });
21141        } else {
21142            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
21143                    keys);
21144            mHandler.sendMessage(msg);
21145        }
21146    }
21147
21148    private void loadPrivatePackages(final VolumeInfo vol) {
21149        mHandler.post(new Runnable() {
21150            @Override
21151            public void run() {
21152                loadPrivatePackagesInner(vol);
21153            }
21154        });
21155    }
21156
21157    private void loadPrivatePackagesInner(VolumeInfo vol) {
21158        final String volumeUuid = vol.fsUuid;
21159        if (TextUtils.isEmpty(volumeUuid)) {
21160            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21161            return;
21162        }
21163
21164        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21165        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21166        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21167
21168        final VersionInfo ver;
21169        final List<PackageSetting> packages;
21170        synchronized (mPackages) {
21171            ver = mSettings.findOrCreateVersion(volumeUuid);
21172            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21173        }
21174
21175        for (PackageSetting ps : packages) {
21176            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21177            synchronized (mInstallLock) {
21178                final PackageParser.Package pkg;
21179                try {
21180                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21181                    loaded.add(pkg.applicationInfo);
21182
21183                } catch (PackageManagerException e) {
21184                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21185                }
21186
21187                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21188                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21189                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21190                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21191                }
21192            }
21193        }
21194
21195        // Reconcile app data for all started/unlocked users
21196        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21197        final UserManager um = mContext.getSystemService(UserManager.class);
21198        UserManagerInternal umInternal = getUserManagerInternal();
21199        for (UserInfo user : um.getUsers()) {
21200            final int flags;
21201            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21202                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21203            } else if (umInternal.isUserRunning(user.id)) {
21204                flags = StorageManager.FLAG_STORAGE_DE;
21205            } else {
21206                continue;
21207            }
21208
21209            try {
21210                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21211                synchronized (mInstallLock) {
21212                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21213                }
21214            } catch (IllegalStateException e) {
21215                // Device was probably ejected, and we'll process that event momentarily
21216                Slog.w(TAG, "Failed to prepare storage: " + e);
21217            }
21218        }
21219
21220        synchronized (mPackages) {
21221            int updateFlags = UPDATE_PERMISSIONS_ALL;
21222            if (ver.sdkVersion != mSdkVersion) {
21223                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21224                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21225                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
21226            }
21227            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
21228
21229            // Yay, everything is now upgraded
21230            ver.forceCurrent();
21231
21232            mSettings.writeLPr();
21233        }
21234
21235        for (PackageFreezer freezer : freezers) {
21236            freezer.close();
21237        }
21238
21239        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
21240        sendResourcesChangedBroadcast(true, false, loaded, null);
21241    }
21242
21243    private void unloadPrivatePackages(final VolumeInfo vol) {
21244        mHandler.post(new Runnable() {
21245            @Override
21246            public void run() {
21247                unloadPrivatePackagesInner(vol);
21248            }
21249        });
21250    }
21251
21252    private void unloadPrivatePackagesInner(VolumeInfo vol) {
21253        final String volumeUuid = vol.fsUuid;
21254        if (TextUtils.isEmpty(volumeUuid)) {
21255            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
21256            return;
21257        }
21258
21259        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
21260        synchronized (mInstallLock) {
21261        synchronized (mPackages) {
21262            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
21263            for (PackageSetting ps : packages) {
21264                if (ps.pkg == null) continue;
21265
21266                final ApplicationInfo info = ps.pkg.applicationInfo;
21267                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
21268                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
21269
21270                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
21271                        "unloadPrivatePackagesInner")) {
21272                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
21273                            false, null)) {
21274                        unloaded.add(info);
21275                    } else {
21276                        Slog.w(TAG, "Failed to unload " + ps.codePath);
21277                    }
21278                }
21279
21280                // Try very hard to release any references to this package
21281                // so we don't risk the system server being killed due to
21282                // open FDs
21283                AttributeCache.instance().removePackage(ps.name);
21284            }
21285
21286            mSettings.writeLPr();
21287        }
21288        }
21289
21290        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
21291        sendResourcesChangedBroadcast(false, false, unloaded, null);
21292
21293        // Try very hard to release any references to this path so we don't risk
21294        // the system server being killed due to open FDs
21295        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
21296
21297        for (int i = 0; i < 3; i++) {
21298            System.gc();
21299            System.runFinalization();
21300        }
21301    }
21302
21303    /**
21304     * Examine all users present on given mounted volume, and destroy data
21305     * belonging to users that are no longer valid, or whose user ID has been
21306     * recycled.
21307     */
21308    private void reconcileUsers(String volumeUuid) {
21309        final List<File> files = new ArrayList<>();
21310        Collections.addAll(files, FileUtils
21311                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
21312        Collections.addAll(files, FileUtils
21313                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
21314        Collections.addAll(files, FileUtils
21315                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
21316        Collections.addAll(files, FileUtils
21317                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
21318        Collections.addAll(files, FileUtils
21319                .listFilesOrEmpty(Environment.getDataMiscCeDirectory()));
21320        for (File file : files) {
21321            if (!file.isDirectory()) continue;
21322
21323            final int userId;
21324            final UserInfo info;
21325            try {
21326                userId = Integer.parseInt(file.getName());
21327                info = sUserManager.getUserInfo(userId);
21328            } catch (NumberFormatException e) {
21329                Slog.w(TAG, "Invalid user directory " + file);
21330                continue;
21331            }
21332
21333            boolean destroyUser = false;
21334            if (info == null) {
21335                logCriticalInfo(Log.WARN, "Destroying user directory " + file
21336                        + " because no matching user was found");
21337                destroyUser = true;
21338            } else if (!mOnlyCore) {
21339                try {
21340                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
21341                } catch (IOException e) {
21342                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
21343                            + " because we failed to enforce serial number: " + e);
21344                    destroyUser = true;
21345                }
21346            }
21347
21348            if (destroyUser) {
21349                synchronized (mInstallLock) {
21350                    mUserDataPreparer.destroyUserDataLI(volumeUuid, userId,
21351                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
21352                }
21353            }
21354        }
21355    }
21356
21357    private void assertPackageKnown(String volumeUuid, String packageName)
21358            throws PackageManagerException {
21359        synchronized (mPackages) {
21360            // Normalize package name to handle renamed packages
21361            packageName = normalizePackageNameLPr(packageName);
21362
21363            final PackageSetting ps = mSettings.mPackages.get(packageName);
21364            if (ps == null) {
21365                throw new PackageManagerException("Package " + packageName + " is unknown");
21366            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21367                throw new PackageManagerException(
21368                        "Package " + packageName + " found on unknown volume " + volumeUuid
21369                                + "; expected volume " + ps.volumeUuid);
21370            }
21371        }
21372    }
21373
21374    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
21375            throws PackageManagerException {
21376        synchronized (mPackages) {
21377            // Normalize package name to handle renamed packages
21378            packageName = normalizePackageNameLPr(packageName);
21379
21380            final PackageSetting ps = mSettings.mPackages.get(packageName);
21381            if (ps == null) {
21382                throw new PackageManagerException("Package " + packageName + " is unknown");
21383            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
21384                throw new PackageManagerException(
21385                        "Package " + packageName + " found on unknown volume " + volumeUuid
21386                                + "; expected volume " + ps.volumeUuid);
21387            } else if (!ps.getInstalled(userId)) {
21388                throw new PackageManagerException(
21389                        "Package " + packageName + " not installed for user " + userId);
21390            }
21391        }
21392    }
21393
21394    private List<String> collectAbsoluteCodePaths() {
21395        synchronized (mPackages) {
21396            List<String> codePaths = new ArrayList<>();
21397            final int packageCount = mSettings.mPackages.size();
21398            for (int i = 0; i < packageCount; i++) {
21399                final PackageSetting ps = mSettings.mPackages.valueAt(i);
21400                codePaths.add(ps.codePath.getAbsolutePath());
21401            }
21402            return codePaths;
21403        }
21404    }
21405
21406    /**
21407     * Examine all apps present on given mounted volume, and destroy apps that
21408     * aren't expected, either due to uninstallation or reinstallation on
21409     * another volume.
21410     */
21411    private void reconcileApps(String volumeUuid) {
21412        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
21413        List<File> filesToDelete = null;
21414
21415        final File[] files = FileUtils.listFilesOrEmpty(
21416                Environment.getDataAppDirectory(volumeUuid));
21417        for (File file : files) {
21418            final boolean isPackage = (isApkFile(file) || file.isDirectory())
21419                    && !PackageInstallerService.isStageName(file.getName());
21420            if (!isPackage) {
21421                // Ignore entries which are not packages
21422                continue;
21423            }
21424
21425            String absolutePath = file.getAbsolutePath();
21426
21427            boolean pathValid = false;
21428            final int absoluteCodePathCount = absoluteCodePaths.size();
21429            for (int i = 0; i < absoluteCodePathCount; i++) {
21430                String absoluteCodePath = absoluteCodePaths.get(i);
21431                if (absolutePath.startsWith(absoluteCodePath)) {
21432                    pathValid = true;
21433                    break;
21434                }
21435            }
21436
21437            if (!pathValid) {
21438                if (filesToDelete == null) {
21439                    filesToDelete = new ArrayList<>();
21440                }
21441                filesToDelete.add(file);
21442            }
21443        }
21444
21445        if (filesToDelete != null) {
21446            final int fileToDeleteCount = filesToDelete.size();
21447            for (int i = 0; i < fileToDeleteCount; i++) {
21448                File fileToDelete = filesToDelete.get(i);
21449                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
21450                synchronized (mInstallLock) {
21451                    removeCodePathLI(fileToDelete);
21452                }
21453            }
21454        }
21455    }
21456
21457    /**
21458     * Reconcile all app data for the given user.
21459     * <p>
21460     * Verifies that directories exist and that ownership and labeling is
21461     * correct for all installed apps on all mounted volumes.
21462     */
21463    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
21464        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21465        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
21466            final String volumeUuid = vol.getFsUuid();
21467            synchronized (mInstallLock) {
21468                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
21469            }
21470        }
21471    }
21472
21473    /**
21474     * Reconcile all app data on given mounted volume.
21475     * <p>
21476     * Destroys app data that isn't expected, either due to uninstallation or
21477     * reinstallation on another volume.
21478     * <p>
21479     * Verifies that directories exist and that ownership and labeling is
21480     * correct for all installed apps.
21481     */
21482    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
21483            boolean migrateAppData) {
21484        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
21485                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
21486
21487        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
21488        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
21489
21490        // First look for stale data that doesn't belong, and check if things
21491        // have changed since we did our last restorecon
21492        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21493            if (StorageManager.isFileEncryptedNativeOrEmulated()
21494                    && !StorageManager.isUserKeyUnlocked(userId)) {
21495                throw new RuntimeException(
21496                        "Yikes, someone asked us to reconcile CE storage while " + userId
21497                                + " was still locked; this would have caused massive data loss!");
21498            }
21499
21500            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
21501            for (File file : files) {
21502                final String packageName = file.getName();
21503                try {
21504                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21505                } catch (PackageManagerException e) {
21506                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21507                    try {
21508                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21509                                StorageManager.FLAG_STORAGE_CE, 0);
21510                    } catch (InstallerException e2) {
21511                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21512                    }
21513                }
21514            }
21515        }
21516        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
21517            final File[] files = FileUtils.listFilesOrEmpty(deDir);
21518            for (File file : files) {
21519                final String packageName = file.getName();
21520                try {
21521                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
21522                } catch (PackageManagerException e) {
21523                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
21524                    try {
21525                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
21526                                StorageManager.FLAG_STORAGE_DE, 0);
21527                    } catch (InstallerException e2) {
21528                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
21529                    }
21530                }
21531            }
21532        }
21533
21534        // Ensure that data directories are ready to roll for all packages
21535        // installed for this volume and user
21536        final List<PackageSetting> packages;
21537        synchronized (mPackages) {
21538            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21539        }
21540        int preparedCount = 0;
21541        for (PackageSetting ps : packages) {
21542            final String packageName = ps.name;
21543            if (ps.pkg == null) {
21544                Slog.w(TAG, "Odd, missing scanned package " + packageName);
21545                // TODO: might be due to legacy ASEC apps; we should circle back
21546                // and reconcile again once they're scanned
21547                continue;
21548            }
21549
21550            if (ps.getInstalled(userId)) {
21551                prepareAppDataLIF(ps.pkg, userId, flags);
21552
21553                if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) {
21554                    // We may have just shuffled around app data directories, so
21555                    // prepare them one more time
21556                    prepareAppDataLIF(ps.pkg, userId, flags);
21557                }
21558
21559                preparedCount++;
21560            }
21561        }
21562
21563        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
21564    }
21565
21566    /**
21567     * Prepare app data for the given app just after it was installed or
21568     * upgraded. This method carefully only touches users that it's installed
21569     * for, and it forces a restorecon to handle any seinfo changes.
21570     * <p>
21571     * Verifies that directories exist and that ownership and labeling is
21572     * correct for all installed apps. If there is an ownership mismatch, it
21573     * will try recovering system apps by wiping data; third-party app data is
21574     * left intact.
21575     * <p>
21576     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
21577     */
21578    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
21579        final PackageSetting ps;
21580        synchronized (mPackages) {
21581            ps = mSettings.mPackages.get(pkg.packageName);
21582            mSettings.writeKernelMappingLPr(ps);
21583        }
21584
21585        final UserManager um = mContext.getSystemService(UserManager.class);
21586        UserManagerInternal umInternal = getUserManagerInternal();
21587        for (UserInfo user : um.getUsers()) {
21588            final int flags;
21589            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21590                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21591            } else if (umInternal.isUserRunning(user.id)) {
21592                flags = StorageManager.FLAG_STORAGE_DE;
21593            } else {
21594                continue;
21595            }
21596
21597            if (ps.getInstalled(user.id)) {
21598                // TODO: when user data is locked, mark that we're still dirty
21599                prepareAppDataLIF(pkg, user.id, flags);
21600            }
21601        }
21602    }
21603
21604    /**
21605     * Prepare app data for the given app.
21606     * <p>
21607     * Verifies that directories exist and that ownership and labeling is
21608     * correct for all installed apps. If there is an ownership mismatch, this
21609     * will try recovering system apps by wiping data; third-party app data is
21610     * left intact.
21611     */
21612    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
21613        if (pkg == null) {
21614            Slog.wtf(TAG, "Package was null!", new Throwable());
21615            return;
21616        }
21617        prepareAppDataLeafLIF(pkg, userId, flags);
21618        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21619        for (int i = 0; i < childCount; i++) {
21620            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
21621        }
21622    }
21623
21624    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21625        if (DEBUG_APP_DATA) {
21626            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
21627                    + Integer.toHexString(flags));
21628        }
21629
21630        final String volumeUuid = pkg.volumeUuid;
21631        final String packageName = pkg.packageName;
21632        final ApplicationInfo app = pkg.applicationInfo;
21633        final int appId = UserHandle.getAppId(app.uid);
21634
21635        Preconditions.checkNotNull(app.seinfo);
21636
21637        long ceDataInode = -1;
21638        try {
21639            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21640                    appId, app.seinfo, app.targetSdkVersion);
21641        } catch (InstallerException e) {
21642            if (app.isSystemApp()) {
21643                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
21644                        + ", but trying to recover: " + e);
21645                destroyAppDataLeafLIF(pkg, userId, flags);
21646                try {
21647                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
21648                            appId, app.seinfo, app.targetSdkVersion);
21649                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
21650                } catch (InstallerException e2) {
21651                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
21652                }
21653            } else {
21654                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
21655            }
21656        }
21657
21658        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
21659            // TODO: mark this structure as dirty so we persist it!
21660            synchronized (mPackages) {
21661                final PackageSetting ps = mSettings.mPackages.get(packageName);
21662                if (ps != null) {
21663                    ps.setCeDataInode(ceDataInode, userId);
21664                }
21665            }
21666        }
21667
21668        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21669    }
21670
21671    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
21672        if (pkg == null) {
21673            Slog.wtf(TAG, "Package was null!", new Throwable());
21674            return;
21675        }
21676        prepareAppDataContentsLeafLIF(pkg, userId, flags);
21677        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
21678        for (int i = 0; i < childCount; i++) {
21679            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
21680        }
21681    }
21682
21683    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
21684        final String volumeUuid = pkg.volumeUuid;
21685        final String packageName = pkg.packageName;
21686        final ApplicationInfo app = pkg.applicationInfo;
21687
21688        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
21689            // Create a native library symlink only if we have native libraries
21690            // and if the native libraries are 32 bit libraries. We do not provide
21691            // this symlink for 64 bit libraries.
21692            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
21693                final String nativeLibPath = app.nativeLibraryDir;
21694                try {
21695                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
21696                            nativeLibPath, userId);
21697                } catch (InstallerException e) {
21698                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
21699                }
21700            }
21701        }
21702    }
21703
21704    /**
21705     * For system apps on non-FBE devices, this method migrates any existing
21706     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
21707     * requested by the app.
21708     */
21709    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
21710        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
21711                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
21712            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
21713                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
21714            try {
21715                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
21716                        storageTarget);
21717            } catch (InstallerException e) {
21718                logCriticalInfo(Log.WARN,
21719                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
21720            }
21721            return true;
21722        } else {
21723            return false;
21724        }
21725    }
21726
21727    public PackageFreezer freezePackage(String packageName, String killReason) {
21728        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
21729    }
21730
21731    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
21732        return new PackageFreezer(packageName, userId, killReason);
21733    }
21734
21735    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
21736            String killReason) {
21737        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
21738    }
21739
21740    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
21741            String killReason) {
21742        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
21743            return new PackageFreezer();
21744        } else {
21745            return freezePackage(packageName, userId, killReason);
21746        }
21747    }
21748
21749    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
21750            String killReason) {
21751        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
21752    }
21753
21754    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
21755            String killReason) {
21756        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
21757            return new PackageFreezer();
21758        } else {
21759            return freezePackage(packageName, userId, killReason);
21760        }
21761    }
21762
21763    /**
21764     * Class that freezes and kills the given package upon creation, and
21765     * unfreezes it upon closing. This is typically used when doing surgery on
21766     * app code/data to prevent the app from running while you're working.
21767     */
21768    private class PackageFreezer implements AutoCloseable {
21769        private final String mPackageName;
21770        private final PackageFreezer[] mChildren;
21771
21772        private final boolean mWeFroze;
21773
21774        private final AtomicBoolean mClosed = new AtomicBoolean();
21775        private final CloseGuard mCloseGuard = CloseGuard.get();
21776
21777        /**
21778         * Create and return a stub freezer that doesn't actually do anything,
21779         * typically used when someone requested
21780         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
21781         * {@link PackageManager#DELETE_DONT_KILL_APP}.
21782         */
21783        public PackageFreezer() {
21784            mPackageName = null;
21785            mChildren = null;
21786            mWeFroze = false;
21787            mCloseGuard.open("close");
21788        }
21789
21790        public PackageFreezer(String packageName, int userId, String killReason) {
21791            synchronized (mPackages) {
21792                mPackageName = packageName;
21793                mWeFroze = mFrozenPackages.add(mPackageName);
21794
21795                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
21796                if (ps != null) {
21797                    killApplication(ps.name, ps.appId, userId, killReason);
21798                }
21799
21800                final PackageParser.Package p = mPackages.get(packageName);
21801                if (p != null && p.childPackages != null) {
21802                    final int N = p.childPackages.size();
21803                    mChildren = new PackageFreezer[N];
21804                    for (int i = 0; i < N; i++) {
21805                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
21806                                userId, killReason);
21807                    }
21808                } else {
21809                    mChildren = null;
21810                }
21811            }
21812            mCloseGuard.open("close");
21813        }
21814
21815        @Override
21816        protected void finalize() throws Throwable {
21817            try {
21818                mCloseGuard.warnIfOpen();
21819                close();
21820            } finally {
21821                super.finalize();
21822            }
21823        }
21824
21825        @Override
21826        public void close() {
21827            mCloseGuard.close();
21828            if (mClosed.compareAndSet(false, true)) {
21829                synchronized (mPackages) {
21830                    if (mWeFroze) {
21831                        mFrozenPackages.remove(mPackageName);
21832                    }
21833
21834                    if (mChildren != null) {
21835                        for (PackageFreezer freezer : mChildren) {
21836                            freezer.close();
21837                        }
21838                    }
21839                }
21840            }
21841        }
21842    }
21843
21844    /**
21845     * Verify that given package is currently frozen.
21846     */
21847    private void checkPackageFrozen(String packageName) {
21848        synchronized (mPackages) {
21849            if (!mFrozenPackages.contains(packageName)) {
21850                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
21851            }
21852        }
21853    }
21854
21855    @Override
21856    public int movePackage(final String packageName, final String volumeUuid) {
21857        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
21858
21859        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
21860        final int moveId = mNextMoveId.getAndIncrement();
21861        mHandler.post(new Runnable() {
21862            @Override
21863            public void run() {
21864                try {
21865                    movePackageInternal(packageName, volumeUuid, moveId, user);
21866                } catch (PackageManagerException e) {
21867                    Slog.w(TAG, "Failed to move " + packageName, e);
21868                    mMoveCallbacks.notifyStatusChanged(moveId,
21869                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
21870                }
21871            }
21872        });
21873        return moveId;
21874    }
21875
21876    private void movePackageInternal(final String packageName, final String volumeUuid,
21877            final int moveId, UserHandle user) throws PackageManagerException {
21878        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21879        final PackageManager pm = mContext.getPackageManager();
21880
21881        final boolean currentAsec;
21882        final String currentVolumeUuid;
21883        final File codeFile;
21884        final String installerPackageName;
21885        final String packageAbiOverride;
21886        final int appId;
21887        final String seinfo;
21888        final String label;
21889        final int targetSdkVersion;
21890        final PackageFreezer freezer;
21891        final int[] installedUserIds;
21892
21893        // reader
21894        synchronized (mPackages) {
21895            final PackageParser.Package pkg = mPackages.get(packageName);
21896            final PackageSetting ps = mSettings.mPackages.get(packageName);
21897            if (pkg == null || ps == null) {
21898                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
21899            }
21900
21901            if (pkg.applicationInfo.isSystemApp()) {
21902                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
21903                        "Cannot move system application");
21904            }
21905
21906            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
21907            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
21908                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
21909            if (isInternalStorage && !allow3rdPartyOnInternal) {
21910                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
21911                        "3rd party apps are not allowed on internal storage");
21912            }
21913
21914            if (pkg.applicationInfo.isExternalAsec()) {
21915                currentAsec = true;
21916                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
21917            } else if (pkg.applicationInfo.isForwardLocked()) {
21918                currentAsec = true;
21919                currentVolumeUuid = "forward_locked";
21920            } else {
21921                currentAsec = false;
21922                currentVolumeUuid = ps.volumeUuid;
21923
21924                final File probe = new File(pkg.codePath);
21925                final File probeOat = new File(probe, "oat");
21926                if (!probe.isDirectory() || !probeOat.isDirectory()) {
21927                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21928                            "Move only supported for modern cluster style installs");
21929                }
21930            }
21931
21932            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
21933                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21934                        "Package already moved to " + volumeUuid);
21935            }
21936            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
21937                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
21938                        "Device admin cannot be moved");
21939            }
21940
21941            if (mFrozenPackages.contains(packageName)) {
21942                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
21943                        "Failed to move already frozen package");
21944            }
21945
21946            codeFile = new File(pkg.codePath);
21947            installerPackageName = ps.installerPackageName;
21948            packageAbiOverride = ps.cpuAbiOverrideString;
21949            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
21950            seinfo = pkg.applicationInfo.seinfo;
21951            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
21952            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
21953            freezer = freezePackage(packageName, "movePackageInternal");
21954            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
21955        }
21956
21957        final Bundle extras = new Bundle();
21958        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
21959        extras.putString(Intent.EXTRA_TITLE, label);
21960        mMoveCallbacks.notifyCreated(moveId, extras);
21961
21962        int installFlags;
21963        final boolean moveCompleteApp;
21964        final File measurePath;
21965
21966        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
21967            installFlags = INSTALL_INTERNAL;
21968            moveCompleteApp = !currentAsec;
21969            measurePath = Environment.getDataAppDirectory(volumeUuid);
21970        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
21971            installFlags = INSTALL_EXTERNAL;
21972            moveCompleteApp = false;
21973            measurePath = storage.getPrimaryPhysicalVolume().getPath();
21974        } else {
21975            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
21976            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
21977                    || !volume.isMountedWritable()) {
21978                freezer.close();
21979                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21980                        "Move location not mounted private volume");
21981            }
21982
21983            Preconditions.checkState(!currentAsec);
21984
21985            installFlags = INSTALL_INTERNAL;
21986            moveCompleteApp = true;
21987            measurePath = Environment.getDataAppDirectory(volumeUuid);
21988        }
21989
21990        final PackageStats stats = new PackageStats(null, -1);
21991        synchronized (mInstaller) {
21992            for (int userId : installedUserIds) {
21993                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
21994                    freezer.close();
21995                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
21996                            "Failed to measure package size");
21997                }
21998            }
21999        }
22000
22001        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22002                + stats.dataSize);
22003
22004        final long startFreeBytes = measurePath.getFreeSpace();
22005        final long sizeBytes;
22006        if (moveCompleteApp) {
22007            sizeBytes = stats.codeSize + stats.dataSize;
22008        } else {
22009            sizeBytes = stats.codeSize;
22010        }
22011
22012        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22013            freezer.close();
22014            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22015                    "Not enough free space to move");
22016        }
22017
22018        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22019
22020        final CountDownLatch installedLatch = new CountDownLatch(1);
22021        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22022            @Override
22023            public void onUserActionRequired(Intent intent) throws RemoteException {
22024                throw new IllegalStateException();
22025            }
22026
22027            @Override
22028            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22029                    Bundle extras) throws RemoteException {
22030                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22031                        + PackageManager.installStatusToString(returnCode, msg));
22032
22033                installedLatch.countDown();
22034                freezer.close();
22035
22036                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22037                switch (status) {
22038                    case PackageInstaller.STATUS_SUCCESS:
22039                        mMoveCallbacks.notifyStatusChanged(moveId,
22040                                PackageManager.MOVE_SUCCEEDED);
22041                        break;
22042                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22043                        mMoveCallbacks.notifyStatusChanged(moveId,
22044                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22045                        break;
22046                    default:
22047                        mMoveCallbacks.notifyStatusChanged(moveId,
22048                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22049                        break;
22050                }
22051            }
22052        };
22053
22054        final MoveInfo move;
22055        if (moveCompleteApp) {
22056            // Kick off a thread to report progress estimates
22057            new Thread() {
22058                @Override
22059                public void run() {
22060                    while (true) {
22061                        try {
22062                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22063                                break;
22064                            }
22065                        } catch (InterruptedException ignored) {
22066                        }
22067
22068                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
22069                        final int progress = 10 + (int) MathUtils.constrain(
22070                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22071                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22072                    }
22073                }
22074            }.start();
22075
22076            final String dataAppName = codeFile.getName();
22077            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22078                    dataAppName, appId, seinfo, targetSdkVersion);
22079        } else {
22080            move = null;
22081        }
22082
22083        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22084
22085        final Message msg = mHandler.obtainMessage(INIT_COPY);
22086        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22087        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22088                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22089                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
22090                PackageManager.INSTALL_REASON_UNKNOWN);
22091        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22092        msg.obj = params;
22093
22094        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22095                System.identityHashCode(msg.obj));
22096        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22097                System.identityHashCode(msg.obj));
22098
22099        mHandler.sendMessage(msg);
22100    }
22101
22102    @Override
22103    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22104        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22105
22106        final int realMoveId = mNextMoveId.getAndIncrement();
22107        final Bundle extras = new Bundle();
22108        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22109        mMoveCallbacks.notifyCreated(realMoveId, extras);
22110
22111        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22112            @Override
22113            public void onCreated(int moveId, Bundle extras) {
22114                // Ignored
22115            }
22116
22117            @Override
22118            public void onStatusChanged(int moveId, int status, long estMillis) {
22119                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22120            }
22121        };
22122
22123        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22124        storage.setPrimaryStorageUuid(volumeUuid, callback);
22125        return realMoveId;
22126    }
22127
22128    @Override
22129    public int getMoveStatus(int moveId) {
22130        mContext.enforceCallingOrSelfPermission(
22131                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22132        return mMoveCallbacks.mLastStatus.get(moveId);
22133    }
22134
22135    @Override
22136    public void registerMoveCallback(IPackageMoveObserver callback) {
22137        mContext.enforceCallingOrSelfPermission(
22138                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22139        mMoveCallbacks.register(callback);
22140    }
22141
22142    @Override
22143    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22144        mContext.enforceCallingOrSelfPermission(
22145                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22146        mMoveCallbacks.unregister(callback);
22147    }
22148
22149    @Override
22150    public boolean setInstallLocation(int loc) {
22151        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22152                null);
22153        if (getInstallLocation() == loc) {
22154            return true;
22155        }
22156        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22157                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22158            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22159                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22160            return true;
22161        }
22162        return false;
22163   }
22164
22165    @Override
22166    public int getInstallLocation() {
22167        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22168                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22169                PackageHelper.APP_INSTALL_AUTO);
22170    }
22171
22172    /** Called by UserManagerService */
22173    void cleanUpUser(UserManagerService userManager, int userHandle) {
22174        synchronized (mPackages) {
22175            mDirtyUsers.remove(userHandle);
22176            mUserNeedsBadging.delete(userHandle);
22177            mSettings.removeUserLPw(userHandle);
22178            mPendingBroadcasts.remove(userHandle);
22179            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22180            removeUnusedPackagesLPw(userManager, userHandle);
22181        }
22182    }
22183
22184    /**
22185     * We're removing userHandle and would like to remove any downloaded packages
22186     * that are no longer in use by any other user.
22187     * @param userHandle the user being removed
22188     */
22189    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22190        final boolean DEBUG_CLEAN_APKS = false;
22191        int [] users = userManager.getUserIds();
22192        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22193        while (psit.hasNext()) {
22194            PackageSetting ps = psit.next();
22195            if (ps.pkg == null) {
22196                continue;
22197            }
22198            final String packageName = ps.pkg.packageName;
22199            // Skip over if system app
22200            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22201                continue;
22202            }
22203            if (DEBUG_CLEAN_APKS) {
22204                Slog.i(TAG, "Checking package " + packageName);
22205            }
22206            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22207            if (keep) {
22208                if (DEBUG_CLEAN_APKS) {
22209                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22210                }
22211            } else {
22212                for (int i = 0; i < users.length; i++) {
22213                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22214                        keep = true;
22215                        if (DEBUG_CLEAN_APKS) {
22216                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22217                                    + users[i]);
22218                        }
22219                        break;
22220                    }
22221                }
22222            }
22223            if (!keep) {
22224                if (DEBUG_CLEAN_APKS) {
22225                    Slog.i(TAG, "  Removing package " + packageName);
22226                }
22227                mHandler.post(new Runnable() {
22228                    public void run() {
22229                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22230                                userHandle, 0);
22231                    } //end run
22232                });
22233            }
22234        }
22235    }
22236
22237    /** Called by UserManagerService */
22238    void createNewUser(int userId, String[] disallowedPackages) {
22239        synchronized (mInstallLock) {
22240            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22241        }
22242        synchronized (mPackages) {
22243            scheduleWritePackageRestrictionsLocked(userId);
22244            scheduleWritePackageListLocked(userId);
22245            applyFactoryDefaultBrowserLPw(userId);
22246            primeDomainVerificationsLPw(userId);
22247        }
22248    }
22249
22250    void onNewUserCreated(final int userId) {
22251        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
22252        // If permission review for legacy apps is required, we represent
22253        // dagerous permissions for such apps as always granted runtime
22254        // permissions to keep per user flag state whether review is needed.
22255        // Hence, if a new user is added we have to propagate dangerous
22256        // permission grants for these legacy apps.
22257        if (mPermissionReviewRequired) {
22258            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
22259                    | UPDATE_PERMISSIONS_REPLACE_ALL);
22260        }
22261    }
22262
22263    @Override
22264    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
22265        mContext.enforceCallingOrSelfPermission(
22266                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
22267                "Only package verification agents can read the verifier device identity");
22268
22269        synchronized (mPackages) {
22270            return mSettings.getVerifierDeviceIdentityLPw();
22271        }
22272    }
22273
22274    @Override
22275    public void setPermissionEnforced(String permission, boolean enforced) {
22276        // TODO: Now that we no longer change GID for storage, this should to away.
22277        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
22278                "setPermissionEnforced");
22279        if (READ_EXTERNAL_STORAGE.equals(permission)) {
22280            synchronized (mPackages) {
22281                if (mSettings.mReadExternalStorageEnforced == null
22282                        || mSettings.mReadExternalStorageEnforced != enforced) {
22283                    mSettings.mReadExternalStorageEnforced = enforced;
22284                    mSettings.writeLPr();
22285                }
22286            }
22287            // kill any non-foreground processes so we restart them and
22288            // grant/revoke the GID.
22289            final IActivityManager am = ActivityManager.getService();
22290            if (am != null) {
22291                final long token = Binder.clearCallingIdentity();
22292                try {
22293                    am.killProcessesBelowForeground("setPermissionEnforcement");
22294                } catch (RemoteException e) {
22295                } finally {
22296                    Binder.restoreCallingIdentity(token);
22297                }
22298            }
22299        } else {
22300            throw new IllegalArgumentException("No selective enforcement for " + permission);
22301        }
22302    }
22303
22304    @Override
22305    @Deprecated
22306    public boolean isPermissionEnforced(String permission) {
22307        return true;
22308    }
22309
22310    @Override
22311    public boolean isStorageLow() {
22312        final long token = Binder.clearCallingIdentity();
22313        try {
22314            final DeviceStorageMonitorInternal
22315                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
22316            if (dsm != null) {
22317                return dsm.isMemoryLow();
22318            } else {
22319                return false;
22320            }
22321        } finally {
22322            Binder.restoreCallingIdentity(token);
22323        }
22324    }
22325
22326    @Override
22327    public IPackageInstaller getPackageInstaller() {
22328        return mInstallerService;
22329    }
22330
22331    private boolean userNeedsBadging(int userId) {
22332        int index = mUserNeedsBadging.indexOfKey(userId);
22333        if (index < 0) {
22334            final UserInfo userInfo;
22335            final long token = Binder.clearCallingIdentity();
22336            try {
22337                userInfo = sUserManager.getUserInfo(userId);
22338            } finally {
22339                Binder.restoreCallingIdentity(token);
22340            }
22341            final boolean b;
22342            if (userInfo != null && userInfo.isManagedProfile()) {
22343                b = true;
22344            } else {
22345                b = false;
22346            }
22347            mUserNeedsBadging.put(userId, b);
22348            return b;
22349        }
22350        return mUserNeedsBadging.valueAt(index);
22351    }
22352
22353    @Override
22354    public KeySet getKeySetByAlias(String packageName, String alias) {
22355        if (packageName == null || alias == null) {
22356            return null;
22357        }
22358        synchronized(mPackages) {
22359            final PackageParser.Package pkg = mPackages.get(packageName);
22360            if (pkg == null) {
22361                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22362                throw new IllegalArgumentException("Unknown package: " + packageName);
22363            }
22364            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22365            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
22366        }
22367    }
22368
22369    @Override
22370    public KeySet getSigningKeySet(String packageName) {
22371        if (packageName == null) {
22372            return null;
22373        }
22374        synchronized(mPackages) {
22375            final PackageParser.Package pkg = mPackages.get(packageName);
22376            if (pkg == null) {
22377                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22378                throw new IllegalArgumentException("Unknown package: " + packageName);
22379            }
22380            if (pkg.applicationInfo.uid != Binder.getCallingUid()
22381                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
22382                throw new SecurityException("May not access signing KeySet of other apps.");
22383            }
22384            KeySetManagerService ksms = mSettings.mKeySetManagerService;
22385            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
22386        }
22387    }
22388
22389    @Override
22390    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
22391        if (packageName == null || ks == null) {
22392            return false;
22393        }
22394        synchronized(mPackages) {
22395            final PackageParser.Package pkg = mPackages.get(packageName);
22396            if (pkg == null) {
22397                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22398                throw new IllegalArgumentException("Unknown package: " + packageName);
22399            }
22400            IBinder ksh = ks.getToken();
22401            if (ksh instanceof KeySetHandle) {
22402                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22403                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
22404            }
22405            return false;
22406        }
22407    }
22408
22409    @Override
22410    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
22411        if (packageName == null || ks == null) {
22412            return false;
22413        }
22414        synchronized(mPackages) {
22415            final PackageParser.Package pkg = mPackages.get(packageName);
22416            if (pkg == null) {
22417                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
22418                throw new IllegalArgumentException("Unknown package: " + packageName);
22419            }
22420            IBinder ksh = ks.getToken();
22421            if (ksh instanceof KeySetHandle) {
22422                KeySetManagerService ksms = mSettings.mKeySetManagerService;
22423                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
22424            }
22425            return false;
22426        }
22427    }
22428
22429    private void deletePackageIfUnusedLPr(final String packageName) {
22430        PackageSetting ps = mSettings.mPackages.get(packageName);
22431        if (ps == null) {
22432            return;
22433        }
22434        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
22435            // TODO Implement atomic delete if package is unused
22436            // It is currently possible that the package will be deleted even if it is installed
22437            // after this method returns.
22438            mHandler.post(new Runnable() {
22439                public void run() {
22440                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22441                            0, PackageManager.DELETE_ALL_USERS);
22442                }
22443            });
22444        }
22445    }
22446
22447    /**
22448     * Check and throw if the given before/after packages would be considered a
22449     * downgrade.
22450     */
22451    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
22452            throws PackageManagerException {
22453        if (after.versionCode < before.mVersionCode) {
22454            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22455                    "Update version code " + after.versionCode + " is older than current "
22456                    + before.mVersionCode);
22457        } else if (after.versionCode == before.mVersionCode) {
22458            if (after.baseRevisionCode < before.baseRevisionCode) {
22459                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22460                        "Update base revision code " + after.baseRevisionCode
22461                        + " is older than current " + before.baseRevisionCode);
22462            }
22463
22464            if (!ArrayUtils.isEmpty(after.splitNames)) {
22465                for (int i = 0; i < after.splitNames.length; i++) {
22466                    final String splitName = after.splitNames[i];
22467                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
22468                    if (j != -1) {
22469                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
22470                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
22471                                    "Update split " + splitName + " revision code "
22472                                    + after.splitRevisionCodes[i] + " is older than current "
22473                                    + before.splitRevisionCodes[j]);
22474                        }
22475                    }
22476                }
22477            }
22478        }
22479    }
22480
22481    private static class MoveCallbacks extends Handler {
22482        private static final int MSG_CREATED = 1;
22483        private static final int MSG_STATUS_CHANGED = 2;
22484
22485        private final RemoteCallbackList<IPackageMoveObserver>
22486                mCallbacks = new RemoteCallbackList<>();
22487
22488        private final SparseIntArray mLastStatus = new SparseIntArray();
22489
22490        public MoveCallbacks(Looper looper) {
22491            super(looper);
22492        }
22493
22494        public void register(IPackageMoveObserver callback) {
22495            mCallbacks.register(callback);
22496        }
22497
22498        public void unregister(IPackageMoveObserver callback) {
22499            mCallbacks.unregister(callback);
22500        }
22501
22502        @Override
22503        public void handleMessage(Message msg) {
22504            final SomeArgs args = (SomeArgs) msg.obj;
22505            final int n = mCallbacks.beginBroadcast();
22506            for (int i = 0; i < n; i++) {
22507                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
22508                try {
22509                    invokeCallback(callback, msg.what, args);
22510                } catch (RemoteException ignored) {
22511                }
22512            }
22513            mCallbacks.finishBroadcast();
22514            args.recycle();
22515        }
22516
22517        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
22518                throws RemoteException {
22519            switch (what) {
22520                case MSG_CREATED: {
22521                    callback.onCreated(args.argi1, (Bundle) args.arg2);
22522                    break;
22523                }
22524                case MSG_STATUS_CHANGED: {
22525                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
22526                    break;
22527                }
22528            }
22529        }
22530
22531        private void notifyCreated(int moveId, Bundle extras) {
22532            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
22533
22534            final SomeArgs args = SomeArgs.obtain();
22535            args.argi1 = moveId;
22536            args.arg2 = extras;
22537            obtainMessage(MSG_CREATED, args).sendToTarget();
22538        }
22539
22540        private void notifyStatusChanged(int moveId, int status) {
22541            notifyStatusChanged(moveId, status, -1);
22542        }
22543
22544        private void notifyStatusChanged(int moveId, int status, long estMillis) {
22545            Slog.v(TAG, "Move " + moveId + " status " + status);
22546
22547            final SomeArgs args = SomeArgs.obtain();
22548            args.argi1 = moveId;
22549            args.argi2 = status;
22550            args.arg3 = estMillis;
22551            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
22552
22553            synchronized (mLastStatus) {
22554                mLastStatus.put(moveId, status);
22555            }
22556        }
22557    }
22558
22559    private final static class OnPermissionChangeListeners extends Handler {
22560        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
22561
22562        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
22563                new RemoteCallbackList<>();
22564
22565        public OnPermissionChangeListeners(Looper looper) {
22566            super(looper);
22567        }
22568
22569        @Override
22570        public void handleMessage(Message msg) {
22571            switch (msg.what) {
22572                case MSG_ON_PERMISSIONS_CHANGED: {
22573                    final int uid = msg.arg1;
22574                    handleOnPermissionsChanged(uid);
22575                } break;
22576            }
22577        }
22578
22579        public void addListenerLocked(IOnPermissionsChangeListener listener) {
22580            mPermissionListeners.register(listener);
22581
22582        }
22583
22584        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
22585            mPermissionListeners.unregister(listener);
22586        }
22587
22588        public void onPermissionsChanged(int uid) {
22589            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
22590                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
22591            }
22592        }
22593
22594        private void handleOnPermissionsChanged(int uid) {
22595            final int count = mPermissionListeners.beginBroadcast();
22596            try {
22597                for (int i = 0; i < count; i++) {
22598                    IOnPermissionsChangeListener callback = mPermissionListeners
22599                            .getBroadcastItem(i);
22600                    try {
22601                        callback.onPermissionsChanged(uid);
22602                    } catch (RemoteException e) {
22603                        Log.e(TAG, "Permission listener is dead", e);
22604                    }
22605                }
22606            } finally {
22607                mPermissionListeners.finishBroadcast();
22608            }
22609        }
22610    }
22611
22612    private class PackageManagerInternalImpl extends PackageManagerInternal {
22613        @Override
22614        public void setLocationPackagesProvider(PackagesProvider provider) {
22615            synchronized (mPackages) {
22616                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
22617            }
22618        }
22619
22620        @Override
22621        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
22622            synchronized (mPackages) {
22623                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
22624            }
22625        }
22626
22627        @Override
22628        public void setSmsAppPackagesProvider(PackagesProvider provider) {
22629            synchronized (mPackages) {
22630                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
22631            }
22632        }
22633
22634        @Override
22635        public void setDialerAppPackagesProvider(PackagesProvider provider) {
22636            synchronized (mPackages) {
22637                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
22638            }
22639        }
22640
22641        @Override
22642        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
22643            synchronized (mPackages) {
22644                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
22645            }
22646        }
22647
22648        @Override
22649        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
22650            synchronized (mPackages) {
22651                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
22652            }
22653        }
22654
22655        @Override
22656        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
22657            synchronized (mPackages) {
22658                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
22659                        packageName, userId);
22660            }
22661        }
22662
22663        @Override
22664        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
22665            synchronized (mPackages) {
22666                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
22667                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
22668                        packageName, userId);
22669            }
22670        }
22671
22672        @Override
22673        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
22674            synchronized (mPackages) {
22675                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
22676                        packageName, userId);
22677            }
22678        }
22679
22680        @Override
22681        public void setKeepUninstalledPackages(final List<String> packageList) {
22682            Preconditions.checkNotNull(packageList);
22683            List<String> removedFromList = null;
22684            synchronized (mPackages) {
22685                if (mKeepUninstalledPackages != null) {
22686                    final int packagesCount = mKeepUninstalledPackages.size();
22687                    for (int i = 0; i < packagesCount; i++) {
22688                        String oldPackage = mKeepUninstalledPackages.get(i);
22689                        if (packageList != null && packageList.contains(oldPackage)) {
22690                            continue;
22691                        }
22692                        if (removedFromList == null) {
22693                            removedFromList = new ArrayList<>();
22694                        }
22695                        removedFromList.add(oldPackage);
22696                    }
22697                }
22698                mKeepUninstalledPackages = new ArrayList<>(packageList);
22699                if (removedFromList != null) {
22700                    final int removedCount = removedFromList.size();
22701                    for (int i = 0; i < removedCount; i++) {
22702                        deletePackageIfUnusedLPr(removedFromList.get(i));
22703                    }
22704                }
22705            }
22706        }
22707
22708        @Override
22709        public boolean isPermissionsReviewRequired(String packageName, int userId) {
22710            synchronized (mPackages) {
22711                // If we do not support permission review, done.
22712                if (!mPermissionReviewRequired) {
22713                    return false;
22714                }
22715
22716                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
22717                if (packageSetting == null) {
22718                    return false;
22719                }
22720
22721                // Permission review applies only to apps not supporting the new permission model.
22722                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
22723                    return false;
22724                }
22725
22726                // Legacy apps have the permission and get user consent on launch.
22727                PermissionsState permissionsState = packageSetting.getPermissionsState();
22728                return permissionsState.isPermissionReviewRequired(userId);
22729            }
22730        }
22731
22732        @Override
22733        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
22734            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
22735        }
22736
22737        @Override
22738        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
22739                int userId) {
22740            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
22741        }
22742
22743        @Override
22744        public void setDeviceAndProfileOwnerPackages(
22745                int deviceOwnerUserId, String deviceOwnerPackage,
22746                SparseArray<String> profileOwnerPackages) {
22747            mProtectedPackages.setDeviceAndProfileOwnerPackages(
22748                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
22749        }
22750
22751        @Override
22752        public boolean isPackageDataProtected(int userId, String packageName) {
22753            return mProtectedPackages.isPackageDataProtected(userId, packageName);
22754        }
22755
22756        @Override
22757        public boolean isPackageEphemeral(int userId, String packageName) {
22758            synchronized (mPackages) {
22759                PackageParser.Package p = mPackages.get(packageName);
22760                return p != null ? p.applicationInfo.isInstantApp() : false;
22761            }
22762        }
22763
22764        @Override
22765        public boolean wasPackageEverLaunched(String packageName, int userId) {
22766            synchronized (mPackages) {
22767                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
22768            }
22769        }
22770
22771        @Override
22772        public void grantRuntimePermission(String packageName, String name, int userId,
22773                boolean overridePolicy) {
22774            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
22775                    overridePolicy);
22776        }
22777
22778        @Override
22779        public void revokeRuntimePermission(String packageName, String name, int userId,
22780                boolean overridePolicy) {
22781            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
22782                    overridePolicy);
22783        }
22784
22785        @Override
22786        public String getNameForUid(int uid) {
22787            return PackageManagerService.this.getNameForUid(uid);
22788        }
22789
22790        @Override
22791        public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj,
22792                Intent origIntent, String resolvedType, Intent launchIntent,
22793                String callingPackage, int userId) {
22794            PackageManagerService.this.requestEphemeralResolutionPhaseTwo(
22795                    responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId);
22796        }
22797
22798        @Override
22799        public void grantEphemeralAccess(int userId, Intent intent,
22800                int targetAppId, int ephemeralAppId) {
22801            synchronized (mPackages) {
22802                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
22803                        targetAppId, ephemeralAppId);
22804            }
22805        }
22806
22807        @Override
22808        public void pruneInstantApps() {
22809            synchronized (mPackages) {
22810                mInstantAppRegistry.pruneInstantAppsLPw();
22811            }
22812        }
22813
22814        @Override
22815        public String getSetupWizardPackageName() {
22816            return mSetupWizardPackage;
22817        }
22818
22819        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
22820            if (policy != null) {
22821                mExternalSourcesPolicy = policy;
22822            }
22823        }
22824
22825        @Override
22826        public List<PackageInfo> getOverlayPackages(int userId) {
22827            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
22828            synchronized (mPackages) {
22829                for (PackageParser.Package p : mPackages.values()) {
22830                    if (p.mOverlayTarget != null) {
22831                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
22832                        if (pkg != null) {
22833                            overlayPackages.add(pkg);
22834                        }
22835                    }
22836                }
22837            }
22838            return overlayPackages;
22839        }
22840
22841        @Override
22842        public List<String> getTargetPackageNames(int userId) {
22843            List<String> targetPackages = new ArrayList<>();
22844            synchronized (mPackages) {
22845                for (PackageParser.Package p : mPackages.values()) {
22846                    if (p.mOverlayTarget == null) {
22847                        targetPackages.add(p.packageName);
22848                    }
22849                }
22850            }
22851            return targetPackages;
22852        }
22853
22854
22855        @Override
22856        public boolean setEnabledOverlayPackages(int userId, String targetPackageName,
22857                List<String> overlayPackageNames) {
22858            // TODO: implement when we integrate OMS properly
22859            return false;
22860        }
22861    }
22862
22863    @Override
22864    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
22865        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
22866        synchronized (mPackages) {
22867            final long identity = Binder.clearCallingIdentity();
22868            try {
22869                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
22870                        packageNames, userId);
22871            } finally {
22872                Binder.restoreCallingIdentity(identity);
22873            }
22874        }
22875    }
22876
22877    private static void enforceSystemOrPhoneCaller(String tag) {
22878        int callingUid = Binder.getCallingUid();
22879        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
22880            throw new SecurityException(
22881                    "Cannot call " + tag + " from UID " + callingUid);
22882        }
22883    }
22884
22885    boolean isHistoricalPackageUsageAvailable() {
22886        return mPackageUsage.isHistoricalPackageUsageAvailable();
22887    }
22888
22889    /**
22890     * Return a <b>copy</b> of the collection of packages known to the package manager.
22891     * @return A copy of the values of mPackages.
22892     */
22893    Collection<PackageParser.Package> getPackages() {
22894        synchronized (mPackages) {
22895            return new ArrayList<>(mPackages.values());
22896        }
22897    }
22898
22899    /**
22900     * Logs process start information (including base APK hash) to the security log.
22901     * @hide
22902     */
22903    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
22904            String apkFile, int pid) {
22905        if (!SecurityLog.isLoggingEnabled()) {
22906            return;
22907        }
22908        Bundle data = new Bundle();
22909        data.putLong("startTimestamp", System.currentTimeMillis());
22910        data.putString("processName", processName);
22911        data.putInt("uid", uid);
22912        data.putString("seinfo", seinfo);
22913        data.putString("apkFile", apkFile);
22914        data.putInt("pid", pid);
22915        Message msg = mProcessLoggingHandler.obtainMessage(
22916                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
22917        msg.setData(data);
22918        mProcessLoggingHandler.sendMessage(msg);
22919    }
22920
22921    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
22922        return mCompilerStats.getPackageStats(pkgName);
22923    }
22924
22925    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
22926        return getOrCreateCompilerPackageStats(pkg.packageName);
22927    }
22928
22929    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
22930        return mCompilerStats.getOrCreatePackageStats(pkgName);
22931    }
22932
22933    public void deleteCompilerPackageStats(String pkgName) {
22934        mCompilerStats.deletePackageStats(pkgName);
22935    }
22936
22937    @Override
22938    public int getInstallReason(String packageName, int userId) {
22939        enforceCrossUserPermission(Binder.getCallingUid(), userId,
22940                true /* requireFullPermission */, false /* checkShell */,
22941                "get install reason");
22942        synchronized (mPackages) {
22943            final PackageSetting ps = mSettings.mPackages.get(packageName);
22944            if (ps != null) {
22945                return ps.getInstallReason(userId);
22946            }
22947        }
22948        return PackageManager.INSTALL_REASON_UNKNOWN;
22949    }
22950
22951    @Override
22952    public boolean canRequestPackageInstalls(String packageName, int userId) {
22953        int callingUid = Binder.getCallingUid();
22954        int uid = getPackageUid(packageName, 0, userId);
22955        if (callingUid != uid && callingUid != Process.ROOT_UID
22956                && callingUid != Process.SYSTEM_UID) {
22957            throw new SecurityException(
22958                    "Caller uid " + callingUid + " does not own package " + packageName);
22959        }
22960        ApplicationInfo info = getApplicationInfo(packageName, 0, userId);
22961        if (info == null) {
22962            return false;
22963        }
22964        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
22965            throw new UnsupportedOperationException(
22966                    "Operation only supported on apps targeting Android O or higher");
22967        }
22968        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
22969        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
22970        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
22971            throw new SecurityException("Need to declare " + appOpPermission + " to call this api");
22972        }
22973        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
22974            return false;
22975        }
22976        if (mExternalSourcesPolicy != null) {
22977            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
22978            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
22979                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
22980            }
22981        }
22982        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
22983    }
22984}
22985